This commit is contained in:
Kurt Himebauch authored and GitHub committed 2026-10-13 21:27:42 -04:00
1 parent 5fd47421f9
commit aecd2ebe1d
852 files changed
+4844 -46144

No files matched your search

@@ -5,11 +5,6 @@ import com.droiddeck.launcher.runtime.BwrapSpawner
import com.droiddeck.launcher.session.CrashHandler
import com.droiddeck.launcher.session.GpuClockPin
/**
* Process-wide setup: the crash handler, so a session's folder is finished even when we die, and
* the GPU clock pin cleared in case a killed process left it set, and the socket Flatpak's
* sandboxes are started through (BwrapSpawner).
*/
class App : Application() {
override fun attachBaseContext(base: android.content.Context) =
super.attachBaseContext(com.droiddeck.launcher.core.AppLanguage.wrap(base))
@@ -28,7 +23,6 @@ class App : Application() {
GpuClockPin.clearLeftover(this)
BwrapSpawner.start(this)
com.droiddeck.launcher.frontend.GameFileSync.start(this)
// The game stores the Stores section can talk to; the native engine loads only when one needs it.
com.droiddeck.launcher.stores.StoresState.init(this)
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.gog.GogBackend)
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.epic.EpicBackend)
@@ -8,10 +8,6 @@ import androidx.compose.runtime.setValue
import com.droiddeck.launcher.session.ComponentsManager
import com.droiddeck.launcher.session.ProtonDefault
/**
* Component state and work for the launcher and session drawer: the Protons and their
* DXVK/VKD3D sets, the Nightlies catalog, downloads and the swap/restore actions.
*/
internal class ComponentsMenu(private val activity: android.app.Activity, private val ui: Handler) {
var compSnapshot by mutableStateOf<ComponentsManager.Snapshot?>(null)
var compCatalog by mutableStateOf<List<ComponentsManager.CatalogItem>>(emptyList())
@@ -26,7 +22,6 @@ internal class ComponentsMenu(private val activity: android.app.Activity, privat
val compDownloadRevision: Long get() = downloadRevision
private var shownDefault: String? = null
/** Reads the Protons (and on first open saves their originals) off the UI thread; the Nightlies list comes from its cache. */
fun refreshComponents(snapshotFirst: Boolean = false) {
Thread({
if (snapshotFirst) runCatching { ComponentsManager.snapshotAll(activity) }
@@ -107,8 +102,6 @@ internal class ComponentsMenu(private val activity: android.app.Activity, privat
private companion object {
const val TAG = "ComponentsMenu"
// Both screens use the same package store and .part files. Keep the in-flight registry
// across menu/activity instances so a package cannot be downloaded twice at once.
var downloads by mutableStateOf<Map<String, Int>>(emptyMap())
var downloadRevision by mutableStateOf(0L)
}
@@ -9,17 +9,12 @@ import com.droiddeck.launcher.runtime.DeckyManager
import com.droiddeck.launcher.session.SessionState
import java.io.File
/**
* Decky Loader's state in the launcher: what is installed, the releases on offer and an install
* in progress. The launcher screen keeps one and shows it.
*/
internal class DeckyMenu(private val activity: android.app.Activity, private val ui: android.os.Handler) {
var deckyInstalled by mutableStateOf<String?>(null)
var deckyReleases by mutableStateOf<List<DeckyManager.Release>>(emptyList())
var deckyChecking by mutableStateOf(false)
var deckyStage by mutableStateOf<String?>(null)
var deckyPercent by mutableIntStateOf(-1)
/** True while the stage is the plugin's binary download (DeckyManager.downloadingBinary). */
var deckyDownloadingBinary by mutableStateOf(false)
var deckySupervisor by mutableStateOf(false)
var deckyReleaseRequest = 0
@@ -32,8 +27,6 @@ internal class DeckyMenu(private val activity: android.app.Activity, private val
.getOrElse { DeckyManager.ReleaseChannels(emptyList(), emptyList()) }
ui.post {
if (request == deckyReleaseRequest) {
// Use the newest compatible stable build, or the newest compatible
// prerelease when the fork has not published a stable ARM64 asset.
deckyReleases = channels.stable.ifEmpty { channels.prerelease }
deckyChecking = false
}
@@ -25,35 +25,21 @@ import com.droiddeck.launcher.ui.GpuDriversState
import com.droiddeck.launcher.ui.PairRow
import com.droiddeck.launcher.wayland.CompositorHost
/**
* The GPU drivers: what this GPU is, the matched driver pairs the release repos offer for it, and
* - in Auto, the default - keeping the recommended pair installed and set. Under Advanced, the
* Linux (runtime) and Android (display) lists as before, each picked on its own - except a
* bundle's two halves (DriverBundle), which are always picked, and deleted, together. The launcher
* screen keeps one and hands it to the Components page's GPU drivers tab.
*/
internal class DriverMenus(private val activity: Activity, private val ui: Handler) {
var linuxRows by mutableStateOf<List<DriverRow>>(emptyList())
/** The latest Banners-Turnip release as each driver menu offers it (see [refreshReleaseRows]). */
var linuxDownloads by mutableStateOf<List<com.droiddeck.launcher.ui.DownloadRow>>(emptyList())
var androidDownloads by mutableStateOf<List<com.droiddeck.launcher.ui.DownloadRow>>(emptyList())
// Empty until the first refresh: the activity has no context yet while its fields are made.
var releaseStatus by mutableStateOf("")
var releaseChecking by mutableStateOf(false)
var canRestoreBundled by mutableStateOf(false)
/** Asset name -> download percent, while it downloads. */
private val releaseProgress = HashMap<String, Int>()
var linuxSelected by mutableStateOf("")
val gpu: GpuInfo = GpuInfo.detect()
// Read in refreshDrivers/ensureAuto: the activity has no context yet while its fields are made.
var mode by mutableStateOf(SessionPrefs.GPU_DRIVERS_AUTO)
var pairRows by mutableStateOf<List<PairRow>>(emptyList())
/** The pair being installed, and how far along. */
var pairBusy by mutableStateOf<String?>(null)
var pairPercent by mutableIntStateOf(-1)
/** What Auto last did or found, for the line under the pair in use. */
var autoStatus by mutableStateOf("")
/** The bundle both drivers are set to, as "DD-Turnip 0.1.0", or null when they are not one. */
var activeBundle by mutableStateOf<String?>(null)
private var autoCheckedThisProcess = false
@@ -107,14 +93,12 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
refreshPairs()
}
/** One line for the settings row that opens this: "Auto · WinNative · Balanced". */
fun summary(): String {
val active = pairRows.firstOrNull { it.active }?.name ?: activeBundle
val label = activity.getString(if (mode == SessionPrefs.GPU_DRIVERS_AUTO) R.string.common_auto else R.string.drivers_manual)
return active?.let { activity.getString(R.string.drivers_summary, label, it) } ?: label
}
/** The pairs the last check found, with what is installed and in use; this GPU's first. */
fun refreshPairs() {
val lm = LinuxVulkanDriverManager(activity)
val td = TurnipDriver(activity)
@@ -143,12 +127,6 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
if (auto) ensureAuto(force = false)
}
/**
* Auto: make the recommended pair for this GPU the one installed and set. Looks online when
* [force]d (refresh), or when the last check is a day old - Banners-Turnip rebuilds hourly, and
* a new pair a day is plenty - otherwise works from the last check. Once per app start on its
* own; the pair it replaces is removed, anything the user imported or picked is left alone.
*/
fun ensureAuto(force: Boolean) {
mode = SessionPrefs.gpuDriverMode(activity)
if (mode != SessionPrefs.GPU_DRIVERS_AUTO || pairBusy != null || releaseChecking) return
@@ -184,18 +162,12 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
}, "gpu-driver-auto").start()
}
/** Manual: install (if need be) and set both halves of a pair. */
fun selectPair(key: String) {
if (pairBusy != null) return
val pair = DriverPairs.from(TurnipReleases.cached(activity)).firstOrNull { it.key == key && it.complete } ?: return
installPair(pair, auto = false)
}
/**
* Download what is missing of [pair], then set both halves - only once both are in, so a
* failed download never leaves a half-changed pair. Auto's own downloads are recorded, and the
* ones the new pair replaces are removed.
*/
private fun installPair(pair: DriverPairs.DriverPair, auto: Boolean) {
if (!pair.complete) return
pairBusy = pair.key
@@ -252,21 +224,15 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
}, "gpu-driver-pair").start()
}
/** The bundle a release bundle was downloaded as, while both its halves are installed. */
private fun installedBundle(asset: TurnipReleases.Asset): DriverBundle.Bundle? =
TurnipReleases.installedId(activity, asset) { DriverBundle.get(activity, it) != null }?.let { DriverBundle.get(activity, it) }
/** The id a release asset was installed as (a bundle's id for a bundle), or null when it is not installed. */
private fun installedIdOf(asset: TurnipReleases.Asset): String? = when {
asset.bundle -> installedBundle(asset)?.id
asset.linux -> TurnipReleases.installedId(activity, asset, LinuxVulkanDriverManager(activity)::isInstalled)
else -> TurnipReleases.installedId(activity, asset, TurnipDriver(activity)::isInstalled)
}
/**
* One release asset, downloaded, checked and installed through the importer; returns its id,
* a bundle's id for a bundle.
*/
private fun installAsset(asset: TurnipReleases.Asset, progress: (Int) -> Unit): String {
var file: File? = null
try {
@@ -284,12 +250,6 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
}
}
/**
* Import off the main thread - a driver zip is a few MB and the glibc check reads the whole
* library - then say what happened. A refusal's message is the user-facing reason. A bundle,
* from any import, installs both halves and is set as both drivers at once. [linux] null (the
* tab's own Import .zip) takes a single driver to whichever list its libc belongs in.
*/
fun importDriver(uri: Uri, linux: Boolean?) {
val name = activity.displayNameOf(uri)
Thread({
@@ -328,10 +288,6 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
}, "import-driver").start()
}
/**
* Pick one driver from a list, which is Manual (Auto would put its pair back). A bundle's half
* sets the bundle's other half in the other list as well.
*/
fun selectDriver(id: String, linux: Boolean) {
val bundle = DriverBundle.containing(activity, id, linux)
when {
@@ -343,7 +299,6 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
refreshDrivers()
}
/** Set both halves of [bundle] as the drivers in use; returns what to tell the user. */
private fun useBundle(bundle: DriverBundle.Bundle): String {
val displayChanged = SessionPrefs.androidDriver(activity) != bundle.androidId
DriverBundle.select(activity, bundle)
@@ -354,11 +309,6 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
)
}
/**
* Delete an imported or downloaded driver. A mode still set to it goes back to its default, so a
* session never starts on a driver that is gone; a release download is forgotten, so the menu
* offers it again.
*/
fun deleteDriver(id: String, linux: Boolean) {
val bundle = DriverBundle.containing(activity, id, linux)
if (bundle != null) {
@@ -381,7 +331,6 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
refreshDrivers()
}
/** The download entries and the refresh line, from what the last check found. */
fun refreshReleaseRows() {
val check = TurnipReleases.cached(activity)
fun rows(linux: Boolean) = check?.assets.orEmpty()
@@ -413,7 +362,6 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
}
}
/** Only when the user taps refresh: nothing goes online on its own. */
fun checkLatestTurnip() {
if (releaseChecking) return
releaseChecking = true
@@ -431,7 +379,6 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
}, "turnip-release-check").start()
}
/** Download one release driver and import it through the same importer a picked zip uses. */
fun downloadReleaseDriver(assetName: String) {
val asset = TurnipReleases.cached(activity)?.assets?.firstOrNull { it.name == assetName } ?: return
if (releaseProgress.containsKey(assetName)) return
@@ -5,7 +5,6 @@ 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 attachBaseContext(newBase: android.content.Context) {
super.attachBaseContext(newBase)
@@ -13,7 +13,6 @@ 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,
@@ -22,17 +21,10 @@ object HomeApp {
val icon: Bitmap?,
)
/**
* Whether the app offers itself as a Home app at all. HomeActivity is declared disabled and
* only enabled when the user turns on "Use as a Home screen": a player who does not want a
* launcher never gets Android's "which Home app?" question, and it is one apk either way.
* The setting is the component's own state, which Android keeps across updates.
*/
fun isHomeScreenEnabled(context: Context): Boolean =
context.packageManager.getComponentEnabledSetting(ComponentName(context, HomeActivity::class.java)) ==
PackageManager.COMPONENT_ENABLED_STATE_ENABLED
/** Turned off while DroidDeck is the Home app, the phone goes back to its own launcher. */
fun setHomeScreenEnabled(context: Context, enabled: Boolean) {
context.packageManager.setComponentEnabledSetting(
ComponentName(context, HomeActivity::class.java),
@@ -113,7 +105,6 @@ object HomeApp {
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)
}
@@ -79,11 +79,6 @@ import com.droiddeck.launcher.session.GameStorage
import com.droiddeck.launcher.input.SecondScreenDisplay
import com.droiddeck.launcher.input.SecondScreenDisplays
/**
* 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() {
override fun attachBaseContext(newBase: android.content.Context) {
super.attachBaseContext(newBase)
@@ -97,13 +92,10 @@ class MainActivity : ComponentActivity() {
private val updates = UpdatesMenu(this, ui)
private val protons = ProtonMenu(this, ui)
// The screen's state. Compose redraws whatever reads these when they change.
private var installed by mutableStateOf<String?>(null)
/** A session launch waiting on its button to fill the page (LaunchFlood). */
private var flood by mutableStateOf<PendingFlood?>(null)
private var floodProgress by androidx.compose.runtime.mutableFloatStateOf(0f)
private class PendingFlood(val from: androidx.compose.ui.geometry.Rect, val intent: Intent)
/** A session stopped behind a flood: its blue, drawn back into the button it started from (FloodReturn). */
private var returning by mutableStateOf<ReturningFlood?>(null)
private class ReturningFlood(val color: Int, val to: androidx.compose.ui.geometry.Rect?)
private var ready by mutableStateOf(false)
@@ -123,12 +115,10 @@ class MainActivity : ComponentActivity() {
private var steamRepairQueued by mutableStateOf(false)
private var mangoapp by mutableStateOf(true)
private var steamController by mutableStateOf(SessionPrefs.CONTROLLER_DECK)
// Components page: FEX / DXVK / VKD3D-Proton per Proton (ComponentsManager).
private var showComponents by mutableStateOf(false)
private var focusComponentsContent by mutableStateOf(true)
private var showMapping by mutableStateOf(false)
private var saveBusy: String? = null
/** What to do with the zip or folder the file picker hands back after a game page's Manage saves. */
private var onSavePicked: ((File) -> Unit)? = null
private var controllerSettings by mutableStateOf<ControllerPrefs.Settings?>(null)
private var catalog by mutableStateOf<List<DesktopCatalog.Entry>?>(null)
@@ -167,7 +157,6 @@ class MainActivity : ComponentActivity() {
private var gameStoresEnabled by mutableStateOf(true)
private var gameStoresSpeedTier by mutableStateOf("fast")
private var storesOpenTab by mutableStateOf(SessionPrefs.STORES_OPEN_LIBRARY)
/** A page a notification asked for ("stores:downloads", "app:<id>"), until the front end has gone there. */
private var navRequest by mutableStateOf<String?>(null)
private var storesShowMature by mutableStateOf(false)
private var mic by mutableStateOf(false)
@@ -200,8 +189,6 @@ class MainActivity : ComponentActivity() {
refreshWifiDiscovery()
}
// 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 pickComponent = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedUri(r.data)?.let { importComponent(it) }
}
@@ -235,7 +222,6 @@ class MainActivity : ComponentActivity() {
wifiDiscoveryAsked = SessionPrefs.wifiDiscoveryAsked(this)
wifiDiscoveryBlocked = !wifiDiscoveryPermission && wifiDiscoveryAsked &&
WifiDiscovery.permissions.none { shouldShowRequestPermissionRationale(it) }
// A revoked grant must not leave an enabled switch behind.
if (!wifiDiscoveryPermission && SessionPrefs.wifiDiscoveryEnabled(this)) {
SessionPrefs.setWifiDiscoveryEnabled(this, false)
}
@@ -251,7 +237,6 @@ class MainActivity : ComponentActivity() {
}
}
/** Takes a new or updated Lossless Scaling from Steam and shows what LSFG can use. */
private fun syncLossless() {
Thread({
Lossless.sync(this)
@@ -271,7 +256,6 @@ class MainActivity : ComponentActivity() {
}, "lossless-import").start()
}
/** Import a save zip into [game]: pick it in the app's file picker, then back up and unzip off the main thread. */
private fun importSaves(name: String, game: () -> GameSaves.Game) {
if (SessionState.running) {
android.widget.Toast.makeText(this, R.string.main_saves_close_session, android.widget.Toast.LENGTH_LONG).show()
@@ -290,7 +274,6 @@ class MainActivity : ComponentActivity() {
pickSaveZip.launch(InAppFilePicker.buildIntent(this, listOf("zip"), getString(R.string.main_saves_pick_zip, name), GameSaves.savesDir().parentFile?.parentFile?.path))
}
/** Export [game]'s saves in [layout] to a folder picked in the app's file picker. */
private fun exportSaves(name: String, layout: GameSaves.Layout, game: () -> GameSaves.Game) {
onSavePicked = { dir ->
saveAction(getString(R.string.main_saves_exporting, name)) {
@@ -301,7 +284,6 @@ class MainActivity : ComponentActivity() {
GameSaves.savesDir().mkdirs()
pickSaveDir.launch(InAppFilePicker.buildDirIntent(this, getString(R.string.main_saves_pick_folder, name, layout.label(this)), GameSaves.savesDir().path))
}
/** The Games tab's +: the picked .exe becomes a game (or selects / switches the one it belongs to). */
private fun addGameExe(path: String) {
val exe = java.io.File(path)
Thread({
@@ -327,7 +309,6 @@ class MainActivity : ComponentActivity() {
}
private var addedGamesArt by mutableStateOf(true)
@Volatile private var artFetchRunning = false
/** The user entered a SteamGridDB API key of their own. */
private var sgdbUserKey by mutableStateOf(false)
private val pickRomsDir = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedPath(r.data)?.let { path ->
@@ -335,7 +316,6 @@ class MainActivity : ComponentActivity() {
romsDir = path
}
}
// The mode whose lifted sheet last read its settings, with what it shows; refreshed by loadModeSettings().
private var settingsMode by mutableStateOf<String?>(null)
private var resolution by mutableStateOf(com.droiddeck.launcher.session.SessionDisplay.DEFAULT_RESOLUTION)
private var fexPreset by mutableStateOf("")
@@ -386,7 +366,6 @@ class MainActivity : ComponentActivity() {
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 {
@@ -406,8 +385,6 @@ class MainActivity : ComponentActivity() {
}
if (intent?.component?.className == SessionActivity::class.java.name) {
if (flood != null) return
// Started by a blue button: it floods the page first. A running session is re-joined
// as before, rising over the front end.
val from = com.droiddeck.launcher.ui.LaunchOrigin.take()
if (from != null && !SessionState.running && com.droiddeck.launcher.ui.Motion.scale != 0f) {
flood = PendingFlood(from, intent)
@@ -419,7 +396,6 @@ class MainActivity : ComponentActivity() {
if (intent?.component?.className == SessionActivity::class.java.name) overridePendingTransition(R.anim.session_rise, R.anim.session_hold)
}
/** The page is all blue: the session opens on the same blue, with no animation of its own. */
private fun launchFlooded(f: PendingFlood) {
if (busy || LinuxRuntimeInstaller.isBusy()) { flood = null; floodProgress = 0f; return }
val signal = com.droiddeck.launcher.ui.Themes.byId(theme).signal
@@ -453,7 +429,6 @@ class MainActivity : ComponentActivity() {
request.getStringExtra(com.droiddeck.launcher.stores.download.StoreDownloadService.EXTRA_NAV)?.let { navRequest = it; request.removeExtra(com.droiddeck.launcher.stores.download.StoreDownloadService.EXTRA_NAV) }
shortcutPicker = request.action == Intent.ACTION_CREATE_SHORTCUT
if (shortcutPicker) {
// The shortcut picker must only offer games from the scan started for this request.
steamGames = emptyList()
shortcutLibraryScanning = true
} else shortcutLibraryScanning = false
@@ -531,7 +506,6 @@ class MainActivity : ComponentActivity() {
theme = SessionPrefs.theme(this)
frameGenLabel = getString(R.string.frame_gen_off)
appScale = com.droiddeck.launcher.core.AppUiPrefs.scale(this)
// Last start's game list, so the Steam wall is up on the first frame; refresh() replaces it.
steamGames = if (shortcutPicker) emptyList() else com.droiddeck.launcher.frontend.LibraryCache.load(this)
backActionsInverted = SessionPrefs.backActionsInverted(this)
orientation = SessionPrefs.orientation(this)
@@ -603,18 +577,14 @@ class MainActivity : ComponentActivity() {
),
FrontEndActions(
onPlay = { startSteamSession() },
// The client's desktop UI, with gamescope's Deck integration disabled.
onPlayDesktopUi = {
startSession(Intent(this, SessionActivity::class.java)
.putExtra(SessionService.EXTRA_MODE, SessionService.MODE_STEAM)
.putExtra(SessionService.EXTRA_STEAM_UI, "desktop"), steamSession = true)
},
// A store game may need something done first (an Epic game its sign-in code).
onSteamGame = { g ->
if (shortcutPicker) chooseGameShortcut(g)
else {
// The launch takes the Windows components already on; the game's list is
// looked at again in the background once the session is over.
com.droiddeck.launcher.frontend.AutoComponents.beforeLaunch(this, g)
com.droiddeck.launcher.stores.StoreLaunch.prepare(this, g) { launchGame(g) }
}
@@ -624,7 +594,6 @@ class MainActivity : ComponentActivity() {
onSyncGameFiles = { pickGameExport(null) },
onAddGameExe = { path -> addGameExe(path) },
onAddedGamesChanged = { folders ->
// New games want art; an edit does not.
val known = steamGames.mapNotNull { it.gameFiles?.path }.toSet()
updateAddedGames(folders, then = { if (folders.any { it !in known }) fetchAddedGameArt() })
},
@@ -652,7 +621,6 @@ class MainActivity : ComponentActivity() {
.putExtra(SessionService.EXTRA_MODE, SessionService.MODE_DESKTOP))
},
onEmulator = { e -> launchProgram(e.program) },
// An app added on the Desktop page, full screen under gamescope like an emulator.
onUserApp = { app ->
app.args.firstOrNull()?.let { Library.flatpakNames[it] = app.name }
startActivity(Intent(this, SessionActivity::class.java)
@@ -660,7 +628,6 @@ class MainActivity : ComponentActivity() {
.putExtra(SessionService.EXTRA_PROGRAM, app.program)
.putExtra(SessionService.EXTRA_PROGRAM_ARGS, app.args.toTypedArray()))
},
// A Flatpak app from the store, full screen under gamescope like an emulator.
onFlatpakApp = { id, name ->
Library.flatpakNames[id] = name
startActivity(Intent(this, SessionActivity::class.java)
@@ -675,7 +642,6 @@ class MainActivity : ComponentActivity() {
.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 = { loadModeSettings(SessionService.MODE_STEAM) },
onRemoveDesktop = { removeDesktop() },
@@ -694,7 +660,6 @@ class MainActivity : ComponentActivity() {
onProtons = { openProtons() },
onComponents = { focusContent -> openComponents(focusContent) },
onComponentsTab = { tab -> openComponents(focusContent = true, tab = tab) },
// A game page's Manage saves: the game's Proton and saves are read when the work runs, off the main thread.
onSaveImport = { sg -> importSaves(sg.name) { GameSaves.game(sg) } },
onSaveExport = { sg, layout -> exportSaves(sg.name, layout) { GameSaves.game(sg) } },
onPerformance = { refreshCores(); showComponents = false; showMapping = false; showPerformance = true },
@@ -742,7 +707,6 @@ class MainActivity : ComponentActivity() {
onLanguage = { tag ->
if (tag != com.droiddeck.launcher.core.AppLanguage.chosen(this)) {
com.droiddeck.launcher.core.AppLanguage.setChosen(this, tag)
// Redrawn in the new language; Setup's page and tab are saved state.
recreate()
}
},
@@ -895,25 +859,17 @@ class MainActivity : ComponentActivity() {
if (savedInstanceState == null) ui.post { startSteamAtStartupIfEnabled() }
// 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 off by default. Someone who turned it on before the permission was
// granted is asked once here, with the storage prompt; 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 store sign-in an earlier build left in plain text is sealed with the Keystore key.
Thread({ com.droiddeck.launcher.stores.StoreAccounts.encryptAll(this) }, "store-credentials").start()
// A session folder left without its ending - the process was killed - gets it now.
if (!SessionState.running) Thread({
com.droiddeck.launcher.session.LogMigration.run(this)
com.droiddeck.launcher.frontend.GamesFolderMigration.run(this)
@@ -969,7 +925,6 @@ class MainActivity : ComponentActivity() {
}
}
/** On the Components page the pad's LB / RB step through the stack's layers, wrapping around. */
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
if (event.keyCode == KeyEvent.KEYCODE_BUTTON_A) com.droiddeck.launcher.ui.HeldKeys.confirm = event.action == KeyEvent.ACTION_DOWN
if (showComponents && (event.keyCode == KeyEvent.KEYCODE_BUTTON_L1 || event.keyCode == KeyEvent.KEYCODE_BUTTON_R1)) {
@@ -978,8 +933,6 @@ class MainActivity : ComponentActivity() {
}
return true
}
// Compose throws when its focus tree has lost the focused node; one key is dropped
// instead of the app.
return try {
super.dispatchKeyEvent(event)
} catch (e: IllegalStateException) {
@@ -994,25 +947,17 @@ class MainActivity : ComponentActivity() {
orientation = SessionPrefs.orientation(this)
requestedOrientation = orientation
refreshWifiDiscovery()
// Back from a store's sign-in page: the Stores chips show the account at once. A store
// install finishing while this screen is up rebuilds the Games list through the listener.
com.droiddeck.launcher.stores.StoresState.refresh(this)
com.droiddeck.launcher.stores.StoresState.libraryListener = { refreshAddedGames(); refresh() }
com.droiddeck.launcher.ui.Motion.refresh(this)
// Back from a session stopped behind a flood: open on its blue, before the first frame.
com.droiddeck.launcher.ui.QuitFlood.take()?.let { c ->
returning = ReturningFlood(c, com.droiddeck.launcher.ui.LaunchOrigin.takeReturn())
}
refreshPhantomStatus()
syncLossless()
// Opening the app and coming back from a session both land here.
updates.onResume()
// Auto keeps this GPU's recommended driver pair installed and set: once per app start.
drivers.ensureAuto(force = false)
// Newer GE-Proton / proton-cachyos / DroidDeck-Proton releases: looked up every few hours at most.
protons.checkUpdates()
// Swaps queued while a game ran on that Proton go in once nothing uses it (usually the
// session has just ended). Cheap when nothing is queued.
if (!SessionState.running) Thread({
val applied = runCatching { ComponentsManager.applyQueued(this) }.getOrDefault(emptyList())
if (applied.isNotEmpty()) ui.post {
@@ -1029,8 +974,6 @@ class MainActivity : ComponentActivity() {
decky.deckyInstalled = DeckyManager.installed(this)
DeckyManager.syncCefMarker(this)
decky.deckySupervisor = DeckyManager.supervisorEnabled(this)
// 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()
@@ -1057,10 +1000,8 @@ class MainActivity : ComponentActivity() {
unregisterReceiver(wifiLocationReceiver)
unregisterReceiver(mediaReceiver)
ui.removeCallbacks(mediaRefresh)
// An install finishing while this screen is away is picked up by onResume's refresh.
com.droiddeck.launcher.stores.StoresState.libraryListener = null
displayManager.unregisterDisplayListener(secondScreenDisplayListener)
// The session covers the page by now; coming back finds it as it was.
flood = null
returning = null
floodProgress = 0f
@@ -1116,7 +1057,6 @@ class MainActivity : ComponentActivity() {
}, "catalog-desktop").start()
}
/** Runs a save import or export off the main thread, one at a time, and says how it went. */
private fun saveAction(label: String, work: () -> String) {
if (busy || LinuxRuntimeInstaller.isBusy() || saveBusy != null) return
saveBusy = label
@@ -1129,7 +1069,6 @@ class MainActivity : ComponentActivity() {
}, "game-saves-action").start()
}
/** The Protons DroidDeck installs are the Components page's Proton layer. */
private fun openProtons() = openComponents(focusContent = true, tab = com.droiddeck.launcher.ui.PROTON_TAB)
private fun refreshController() {
@@ -1153,7 +1092,6 @@ class MainActivity : ComponentActivity() {
showPerformance = false
showMapping = false
showComponents = true
// The Proton layer's options for every Proton, as they are now.
fexPreset = SessionPrefs.fexPreset(this)
forceSsbs = SessionPrefs.forceSsbs(this)
fastSync = SessionPrefs.fastSync(this)
@@ -1196,7 +1134,6 @@ class MainActivity : ComponentActivity() {
onDownload = { components.downloadComponent(it) },
onRefresh = { components.refreshComponentCatalog() },
onImport = { pickComponent.launch(InAppFilePicker.buildIntent(this, WCP_EXT, getString(R.string.comp_pick_wcp))) },
// Reached by a hop (a game's Components card, Play's Graphics drivers): back the way it came.
onBack = { if (!com.droiddeck.launcher.ui.Hops.back { showComponents = false }) showComponents = false },
games = steamGames,
generalFexPreset = fexPreset,
@@ -1206,7 +1143,6 @@ class MainActivity : ComponentActivity() {
onAuto = { on -> drivers.setMode(on) },
onPair = { key -> drivers.selectPair(key) },
onRefresh = { if (drivers.mode == SessionPrefs.GPU_DRIVERS_AUTO) drivers.ensureAuto(force = true) else drivers.checkLatestTurnip() },
// Picking one driver on its own is Manual: Auto would put its pair back.
onSelectLinux = { id -> drivers.selectDriver(id, linux = true) },
onSelectAndroid = { id -> drivers.selectDriver(id, linux = false) },
onRemoveLinux = { id -> drivers.deleteDriver(id, linux = true) },
@@ -1241,9 +1177,7 @@ class MainActivity : ComponentActivity() {
)
},
)
// A download can finish in the session drawer while this page is visible.
androidx.compose.runtime.LaunchedEffect(components.compDownloadRevision) { components.refreshComponents() }
// A Proton installed or removed changes the stack's list of Protons.
androidx.compose.runtime.LaunchedEffect(protons.protonBusyId) { if (protons.protonBusyId == null) components.refreshComponents() }
}
@@ -1292,7 +1226,6 @@ class MainActivity : ComponentActivity() {
@Composable
private fun ModeSheetHost(mode: String, tab: String, extras: com.droiddeck.launcher.ui.SheetExtras) {
// Read for the other mode last (or not yet): what this one shows is read as it opens.
if (settingsMode != mode) return
com.droiddeck.launcher.ui.ModeSheetRows(
ModeSettings(
@@ -1377,8 +1310,6 @@ class MainActivity : ComponentActivity() {
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)
}
@@ -1461,17 +1392,12 @@ class MainActivity : ComponentActivity() {
)
}
/**
* The Games tab after these added games were added or edited: each read alone and put in
* place of its old entry (or added), no library-wide scan. [then] runs after, on the main thread.
*/
private fun updateAddedGames(folders: List<String>, then: () -> Unit = {}) {
if (folders.isEmpty()) return
Thread({
val fresh = folders.mapNotNull { f ->
com.droiddeck.launcher.frontend.AddedGames.single(this, f)?.let { com.droiddeck.launcher.frontend.Library.addedGame(this, it) }
}
// An added or edited game's Windows components, from its source's list.
fresh.forEach { com.droiddeck.launcher.frontend.AutoComponents.refreshLater(this, it) }
ui.post {
val paths = folders.toSet()
@@ -1481,19 +1407,16 @@ class MainActivity : ComponentActivity() {
}, "added-games-update").start()
}
/** An added game removed: off the Games tab now; the rest (cache, Steam, listing) off the main thread. */
private fun removeAddedGame(folder: String, appId: Long?, name: String) {
steamGames = steamGames.filterNot { it.library == Library.ADDED && it.gameFiles?.path == folder }
Thread({ com.droiddeck.launcher.frontend.AddedGames.remove(this, java.io.File(folder), appId, name) }, "added-game-remove").start()
}
/** After the added games changed: art that is missing is fetched (off the main thread). */
private fun refreshAddedGames() {
sgdbKeyKnown()
fetchAddedGameArt()
}
/** Whether the user has a SteamGridDB key of their own, for Setup; read off the main thread. */
private fun sgdbKeyKnown() {
Thread({
val set = com.droiddeck.launcher.frontend.SteamGridDb.userKey(this).isNotEmpty()
@@ -1502,8 +1425,6 @@ class MainActivity : ComponentActivity() {
}
private fun fetchAddedGameArt() {
// 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({
@@ -1550,8 +1471,6 @@ class MainActivity : ComponentActivity() {
gameStorage = SessionPrefs.gameStorage(this)
storageDiagnostics = SessionPrefs.storageDiagnosticsEnabled(this)
settingsMode = mode
// The sheet lifts at once, on what was last read; the slow part (driver files, a walk of the
// added-games folders, the storage volumes) lands while it rises.
Thread({
val zram = com.droiddeck.launcher.core.ZramSupport.supported()
val zramOn = SessionPrefs.zramCompression(this)
@@ -1572,7 +1491,6 @@ class MainActivity : ComponentActivity() {
}, "mode-settings").start()
}
/** 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(this, path)
@@ -1585,7 +1503,6 @@ class MainActivity : ComponentActivity() {
gameStorage = path
}
/** 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)
@@ -1626,17 +1543,11 @@ class MainActivity : ComponentActivity() {
?: SessionState.program?.substringAfterLast('/')?.substringBefore('.') ?: getString(R.string.main_running_program)
else -> "Steam"
} else null
// The libraries, off the main thread: manifests and a folder scan.
val scanGeneration = ++libraryScanGeneration
if (shortcutPicker) shortcutLibraryScanning = true
Thread({
// The emulators first: they need no walk of the games, and Desktop's dock is made of them.
val emus = Library.emulators(this) { id -> DesktopCatalog.installed(this, id) != null }
ui.post { if (scanGeneration == libraryScanGeneration) emulatorList = emus }
// Steam's own games next, from their manifests alone (quick), beside the added games
// already listed: a game Steam installed during the session shows as the session ends,
// without waiting for the added games' walk below. Its Windows components' list is
// queued then too, on the low-priority worker, so its page is usually ready.
if (ready) {
val quick = runCatching { Library.steamGames(this) }.getOrNull()
if (quick != null) ui.post {
@@ -1650,15 +1561,9 @@ class MainActivity : ComponentActivity() {
}
}
}
// Then one update with the whole list: the wall places games by their position in it,
// so a partial list first would shuffle every capsule when the rest arrived.
// LibraryCache covers the wait.
val games = if (ready) Library.launchableGames(this) else emptyList()
val all = games.distinctBy { it.gameId }
if (ready) com.droiddeck.launcher.frontend.LibraryCache.save(this, all)
// Once per app start: the Steam games' Windows components from Steam's lists.
// Queued only, after the launcher has been up a little; the worker takes them one at a time.
// And again after each session (a game installed in it, files changed).
val endedSession = SessionState.sessionId.takeIf { !SessionState.running && it != null && it != componentSweepSession }
if (ready && (!componentSweepDone || endedSession != null)) {
componentSweepDone = true
@@ -1672,8 +1577,6 @@ class MainActivity : ComponentActivity() {
handleGameLink(all)
}
}
// Box art for the games that have none, fetched after the list is up; the list is
// rebuilt once if any was found.
if (!OfflineMode.enabled(this) && CoverArt.fetchMissing(this, emus.flatMap { it.games })) {
val refreshed = Library.emulators(this) { id -> DesktopCatalog.installed(this, id) != null }
ui.post { emulatorList = refreshed }
@@ -1685,7 +1588,6 @@ class MainActivity : ComponentActivity() {
if (runtimeChangesBlocked()) return
val release = available
if (removalPending || installed != null && release?.version == installed) {
// Nothing to install: offer the one destructive thing this screen can do.
showRemove = true
return
}
@@ -1693,14 +1595,10 @@ class MainActivity : ComponentActivity() {
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, steamSession: Boolean = false): Boolean {
if (busy || LinuxRuntimeInstaller.isBusy()) return false
refreshPhantomStatus()
@@ -1759,7 +1657,6 @@ class MainActivity : ComponentActivity() {
}
}
/** Setup's Reset all settings; the activity is recreated so every screen reads the defaults (and the language) again. */
private fun resetSettings(gameProfiles: Boolean) {
if (SessionState.running) return
val scopes = steamGames.map { it.profileKey }
@@ -1784,16 +1681,10 @@ class MainActivity : ComponentActivity() {
}
private fun install(release: LinuxRuntimeInstaller.Release) {
// The service keeps the process alive if the user switches away; this screen joins the
// same install (or starts it, if it gets there first) to show the progress.
com.droiddeck.launcher.runtime.RuntimeInstallService.start(this, release)
followRuntimeOperation { listener -> LinuxRuntimeInstaller.install(this, release, listener) }
}
/**
* Shows a runtime operation's progress until it ends. [run] either starts one or joins the one already
* running (null: nothing was), which is how a launcher rebuilt mid-install picks it back up.
*/
private fun followRuntimeOperation(run: (LinuxRuntimeInstaller.ProgressListener) -> Boolean?) {
busy = true
failed = false
@@ -1823,7 +1714,6 @@ class MainActivity : ComponentActivity() {
companion object {
private const val TAG = "MainActivity"
private const val MEDIA_SETTLE_MS = 1500L
/** What the picker offers for a driver zip; some file apps label a zip as a plain stream. */
private val ZIP_EXT = listOf("zip")
private val WCP_EXT = listOf("wcp")
}
@@ -9,11 +9,6 @@ import com.droiddeck.launcher.session.ProtonExtras
import com.droiddeck.launcher.ui.ProtonRow
import com.droiddeck.launcher.session.SessionState
/**
* The optional ARM64 Protons (GE-Proton, proton-cachyos, DroidDeck-Proton): the rows the page lists,
* an install or removal in progress, and whether a newer release is out. The launcher screen keeps
* one and shows it.
*/
internal class ProtonMenu(private val activity: android.app.Activity, private val ui: android.os.Handler) {
var protonRows by mutableStateOf<List<ProtonRow>>(emptyList())
var protonBusyId by mutableStateOf<String?>(null)
@@ -42,7 +37,6 @@ internal class ProtonMenu(private val activity: android.app.Activity, private va
}, "install-proton-$id").start()
}
/** Removes the build in [dir], or with [older] every build of it but the newest. */
fun removeProton(id: String, dir: String? = null, older: Boolean = false) {
val tool = ProtonExtras.tools.firstOrNull { it.id == id } ?: return
if (protonBusyId != null || SessionState.running) return
@@ -66,7 +60,6 @@ internal class ProtonMenu(private val activity: android.app.Activity, private va
}
}
/** Looks for newer releases, at most every few hours (see ProtonExtras.checkLatest); quiet offline. */
fun checkUpdates(force: Boolean = false) {
if (!checking.compareAndSet(false, true)) return
Thread({
File diff suppressed because it is too large. Load diff
@@ -18,13 +18,7 @@ import com.droiddeck.launcher.ui.UpdatesState
import com.droiddeck.launcher.update.AppUpdates
import com.droiddeck.launcher.update.SelfInstaller
/**
* The Updates page's state: the channels' latest builds, the one followed, and an update being
* downloaded or installed. Checked when the launcher comes to the front - opening the app, and
* coming back from a session - at most once a minute.
*/
internal class UpdatesMenu(private val activity: Activity, private val ui: Handler) {
// Read in start(): the activity has no context yet while its fields are made.
var catalog by mutableStateOf<AppUpdates.Catalog?>(null)
var follow by mutableStateOf(AppUpdates.Follow(AppUpdates.Channel.STABLE))
var checking by mutableStateOf(false)
@@ -32,7 +26,6 @@ internal class UpdatesMenu(private val activity: Activity, private val ui: Handl
var stage by mutableStateOf<String?>(null)
var percent by mutableIntStateOf(-1)
var askPermission by mutableStateOf(false)
// An install waiting for the user to allow "Install unknown apps"; it goes on when they come back.
private var pending: AppUpdates.Release? = null
private var lastCheck = 0L
private var request = 0
@@ -53,7 +46,6 @@ internal class UpdatesMenu(private val activity: Activity, private val ui: Handl
val hasUpdate: Boolean get() = AppUpdates.hasUpdate(catalog, follow)
/** On every return to the launcher: go on with an install the user just allowed, and check if due. */
fun onResume() {
pending?.let { r ->
if (SelfInstaller.canInstall(activity)) { pending = null; install(r) }
@@ -107,7 +99,6 @@ internal class UpdatesMenu(private val activity: Activity, private val ui: Handl
}, "app-update-install").start()
}
/** PackageInstaller's answer: Android's confirm prompt to show, or why it failed. Success restarts the app. */
private val receiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
when (val status = intent.getIntExtra(PackageInstaller.EXTRA_STATUS, PackageInstaller.STATUS_FAILURE)) {
@@ -127,7 +118,6 @@ internal class UpdatesMenu(private val activity: Activity, private val ui: Handl
}
}
/** From onCreate: the last check, the channel followed, and PackageInstaller's answers. */
fun start() {
catalog = AppUpdates.cached(activity)
follow = AppUpdates.follow(activity, catalog)
@@ -2,26 +2,16 @@ package com.droiddeck.launcher.agent
import android.content.Context
/**
* Who may run code through the agent bridge. Reading state, starting and stopping sessions,
* launching and quitting games and sending input only need the shell (the provider's DUMP
* permission). Running commands in the guest, evaluating JavaScript in the Steam client, session
* environment, binary overrides and preference writes reach inside the app's sandbox - the guest
* holds the Steam login - which the shell of a stock device otherwise cannot. They require
* Setup > Diagnostics > Debugging tools to be on, in every build. The bridge itself cannot turn it on.
*/
object AgentAccess {
const val MAX_REQUEST_CHARS = 256 * 1024
private const val PREFS = "agent"
private const val KEY_COMMANDS = "commands"
/** The preferences file the bridge must never write: set-pref refuses it. */
const val PROTECTED_PREFS = PREFS
fun commandsAllowed(context: Context): Boolean =
prefs(context).getBoolean(KEY_COMMANDS, false)
/** The Setup toggle's own state. */
fun commandsEnabled(context: Context): Boolean = prefs(context).getBoolean(KEY_COMMANDS, false)
fun setCommandsEnabled(context: Context, enabled: Boolean) {
@@ -44,5 +34,4 @@ object AgentAccess {
private fun prefs(context: Context) = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
}
/** A refusal with a stable code, answered as {"ok": false, "error": {code, message}}. */
class AgentException(val code: String, message: String) : RuntimeException(message)
@@ -27,14 +27,6 @@ import java.io.File
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
/**
* The shell's control surface (docs/agent-control.md), in every build: the provider and its start
* Activity need android.permission.DUMP, held by the shell and privileged or explicitly granted callers. Commands that
* reach into the app's sandbox are further gated by [AgentAccess].
*
* A method's request is JSON, base64-encoded in the "request" extra; every answer is JSON in the
* "json" key of the returned Bundle, {"ok": true, ...} or {"ok": false, "error": {code, message}}.
*/
class AgentBridgeProvider : ContentProvider() {
override fun onCreate(): Boolean {
val appContext = context?.applicationContext ?: return false
@@ -58,7 +50,6 @@ class AgentBridgeProvider : ContentProvider() {
val response = try {
val request = decode(extras?.getString(EXTRA_REQUEST))
// Binder identity is the shell's; everything below acts as the app.
val token = Binder.clearCallingIdentity()
try {
dispatch(context, method, request)
@@ -136,8 +127,6 @@ class AgentBridgeProvider : ContentProvider() {
.put("status", SessionState.failureStatus ?: JSONObject.NULL)
session.put("failure", failure)
// gamescope's focus as last published by the guest agent, without the window lists
// (the focus command returns those, fresh).
val focus = AgentGuest.focus(context)?.let { snap ->
JSONObject()
.put("focusedApp", snap.opt("focusedApp") ?: JSONObject.NULL)
@@ -225,11 +214,9 @@ class AgentBridgeProvider : ContentProvider() {
return result.put("ok", true).put("command", "prefs")
}
/** A guest agent request; its own answer already carries ok or error. */
private fun guest(context: Context, request: JSONObject, timeoutMs: Long): JSONObject =
AgentGuest.call(context, request, timeoutMs)
/** The guest's own timeout plus slack for the round trip. */
private fun timeoutMs(request: JSONObject, defaultSeconds: Double, slackMs: Long): Long {
val seconds = if (request.has("timeout")) request.opt("timeout")?.toString()?.toDoubleOrNull()
?: throw AgentException("INVALID_REQUEST", "timeout must be a number") else defaultSeconds
@@ -262,7 +249,6 @@ class AgentBridgeProvider : ContentProvider() {
companion object {
const val RESULT_JSON = "json"
const val EXTRA_REQUEST = "request"
/** 2 added agent and session.focus; everything in 1 is unchanged. */
const val SCHEMA = 2
private val recoveryComplete = CountDownLatch(1)
@@ -10,18 +10,6 @@ import java.nio.file.Files
import java.nio.file.LinkOption.NOFOLLOW_LINKS
import java.nio.file.StandardOpenOption.READ
/**
* Experiment switches an agent sets without touching Download/droiddeck-env or rebuilding the apk:
*
* - environment lines (KEY=VALUE) for the session, applied after the user's own droiddeck-env, so
* they win. "next" lines are taken by the next session that starts and dropped when it ends;
* "persistent" ones stay until cleared.
* - binary overrides: a file pushed to the app's external files (agent-inbox/<name>) is installed
* as /opt/droiddeck-agent/bin/<name> in the rootfs and put first on the next session's PATH -
* a gamescope build under test, say. Removed when that session ends.
*
* Kept in the app's own files (agent-env.json), never in a place the shell can write.
*/
object AgentEnv {
private const val TAG = "AgentEnv"
private const val FILE = "agent-env.json"
@@ -38,7 +26,6 @@ object AgentEnv {
load(context)
}
/** Add [lines] for the next session ([persistent] = every session until cleared). */
fun set(context: Context, lines: List<String>, persistent: Boolean): JSONObject = synchronized(lock) {
AgentAccess.requireCommands(context)
if (lines.any { line -> KEY.matchEntire(line.substringBefore('=', "")) == null || !line.contains('=') || line.any { it == '\n' || it == '\r' || it == '\u0000' } }) {
@@ -52,7 +39,6 @@ object AgentEnv {
state
}
/** Drop lines: [scope] is "next", "persistent" or "all". */
fun clear(context: Context, scope: String): JSONObject = synchronized(lock) {
AgentAccess.requireCommands(context)
val state = load(context)
@@ -66,7 +52,6 @@ object AgentEnv {
state
}
/** Install agent-inbox/[name] as an override for the next session. */
fun override(context: Context, name: String): JSONObject = synchronized(lock) {
AgentAccess.requireCommands(context)
if (NAME.matchEntire(name) == null || name in setOf(".", "..")) throw AgentException("INVALID_NAME", "Override names are letters, digits, '.', '_' and '-'")
@@ -93,10 +78,6 @@ object AgentEnv {
state.put("installed", "$GUEST_BIN/$name")
}
/**
* At session start: the lines this session gets, after the user's droiddeck-env. Pending lines
* and overrides become this session's own, to be dropped by [endSession].
*/
fun beginSession(context: Context): List<String> = synchronized(lock) {
if (!AgentAccess.commandsAllowed(context)) {
revoke(context)
@@ -108,7 +89,6 @@ object AgentEnv {
state.put("active", JSONArray(active)).put("pending", JSONArray())
state.put("activeOverrides", JSONArray(overrides)).put("pendingOverrides", JSONArray())
save(context, state)
// Anything else there was left by a session that never reached endSession (the app died).
bin(context).listFiles()
?.filter { it.name !in overrides }?.forEach { it.delete() }
val lines = strings(state.optJSONArray("persistent")) + active
@@ -124,7 +104,6 @@ object AgentEnv {
bin(context).listFiles()?.forEach { it.delete() }
}
/** At session end: this session's lines and override binaries go. */
fun endSession(context: Context) = synchronized(lock) {
val state = load(context)
val overrides = strings(state.optJSONArray("activeOverrides"))
@@ -135,7 +114,6 @@ object AgentEnv {
save(context, state)
}
/** A PATH= line among [lines] (the user's or an agent's) is extended rather than replaced. */
private fun pathOf(lines: List<String>) =
lines.lastOrNull { it.startsWith("PATH=") }?.substringAfter('=')?.takeIf { it.isNotBlank() } ?: BASE_PATH
@@ -178,7 +156,6 @@ object AgentEnv {
}
}
/** Typed writes to the app's SharedPreferences, for driving a settings matrix without the UI. */
object AgentPrefs {
fun set(context: Context, file: String, key: String, type: String, value: String?): JSONObject {
AgentAccess.requireCommands(context)
@@ -15,11 +15,6 @@ import org.json.JSONObject
import java.io.File
import java.util.UUID
/**
* The app's side of the guest agent (tools/linuxfs/overlay/usr/local/bin/droiddeck-agent): requests
* go in as files under the session root's agent directory and answers come back the same way, so
* whatever runs does so inside the live session with its own environment.
*/
object AgentGuest {
private val main by lazy { Handler(Looper.getMainLooper()) }
var focusRevision by mutableIntStateOf(0)
@@ -32,11 +27,6 @@ object AgentGuest {
fun dir(context: Context) = File(LinuxRuntime.sessionRoot(context), "agent")
/**
* Before each session: nothing of the last one's daemon, answers or focus may be read as
* current. Then watch for the new daemon's hello and focus snapshots, which go into the
* session's events.jsonl.
*/
fun reset(context: Context) {
synchronized(lock) {
observer?.stopWatching()
@@ -59,7 +49,6 @@ object AgentGuest {
}
}
/** At the end of a session: no more events for a folder that is being closed. */
fun stop() {
synchronized(lock) {
observer?.stopWatching()
@@ -82,7 +71,6 @@ object AgentGuest {
SessionEvents.record("focus.changed", fields + ("seq" to snapshot.optInt("seq")))
}
/** The daemon's hello, when it is running in the current session. */
fun hello(context: Context): JSONObject? {
if (!SessionState.running) return null
val hello = readJson(File(dir(context), "hello.json")) ?: return null
@@ -90,18 +78,15 @@ object AgentGuest {
return hello.takeIf { pid > 1 && File("/proc/$pid").exists() }
}
/** The newest focus snapshot the daemon published, when a session is running. */
fun focus(context: Context): JSONObject? =
if (SessionState.running) readJson(File(dir(context), "focus.json")) else null
/** The Steam library game whose tile currently has controller or keyboard focus. */
fun selectedSteamAppId(context: Context): Long? {
val result = call(context, JSONObject().put("kind", "steam-selection"), 6_000)
if (!result.optBoolean("ok") || result.isNull("appId")) return null
return result.optLong("appId").takeIf { it in 1..4_294_967_295L }
}
/** The installed game Gamescope is presenting, including while Steam's overlay has focus. */
fun activeSteamAppId(context: Context, installedAppIds: Set<Long>): Long? {
val snapshot = focus(context) ?: return null
val focusedAppId = snapshot.optLong("focusedApp").takeIf { snapshot.has("focusedApp") }
@@ -151,7 +136,6 @@ object AgentGuest {
return null
}
/** Send one request and wait for its answer. Throws [AgentException] with a stable code. */
fun call(context: Context, request: JSONObject, timeoutMs: Long): JSONObject {
if (request.optString("kind") in setOf("exec", "cdp")) AgentAccess.requireCommands(context)
if (!SessionState.running) throw AgentException("NO_ACTIVE_SESSION", "There is no running session")
@@ -5,13 +5,7 @@ import com.droiddeck.launcher.session.SessionState
import com.droiddeck.launcher.wayland.WaylandCompositor
import org.json.JSONObject
/**
* Input into the running session the way a player gives it: keys and touches through the
* compositor (what the session screen sends), and the virtual pad through the same PadBridge the
* on-screen controls drive, so games that ignore touch still see a controller.
*/
object AgentInput {
/** Out of the way of real fingers, which Android numbers from 0. */
private const val TOUCH_ID = 9
private const val TOUCH_SCALE_X = 1919f
private const val TOUCH_SCALE_Y = 1079f
@@ -56,7 +50,6 @@ object AgentInput {
return JSONObject().put("code", code)
}
/** Typed as key presses (US layout), which reaches X programs that have no text-input support. */
private fun text(request: JSONObject): JSONObject {
val text = request.optString("text")
if (request.optBoolean("commit")) {
@@ -99,11 +92,6 @@ object AgentInput {
return JSONObject().put("from", org.json.JSONArray().put(x1).put(y1)).put("to", org.json.JSONArray().put(x2).put(y2))
}
/**
* A point in the compositor's touch space (0..1919 x 0..1079 whatever the session's size), from
* the session's output pixels (space "output", the default: what the guest draws at) or 0..1
* fractions (space "fraction").
*/
private fun point(request: JSONObject, xKey: String, yKey: String): Pair<Int, Int> {
if (!request.has(xKey) || !request.has(yKey)) throw AgentException("INVALID_INPUT", "$xKey and $yKey are required")
val x = request.getDouble(xKey)
@@ -183,7 +171,6 @@ object AgentInput {
"guide" to PadState.GUIDE, "steam" to PadState.GUIDE,
)
/** Linux evdev codes (input-event-codes.h) by name. */
private val KEYS: Map<String, Int> = buildMap {
"1234567890".forEachIndexed { i, c -> put(c.toString(), 2 + i) }
"QWERTYUIOP".forEachIndexed { i, c -> put(c.toString(), 16 + i) }
@@ -202,7 +189,6 @@ object AgentInput {
))
}
/** US-layout characters as (evdev code, shift). */
private val TYPED: Map<Char, Pair<Int, Boolean>> = buildMap {
for (c in 'a'..'z') put(c, KEYS.getValue(c.uppercase()) to false)
for (c in 'A'..'Z') put(c, KEYS.getValue(c.toString()) to true)
@@ -10,7 +10,6 @@ import com.droiddeck.launcher.session.SessionService
import org.json.JSONArray
import org.json.JSONObject
/** Shell-launched trampoline: Android permits the shell to start this protected debug Activity. */
class AgentStartActivity : Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
@@ -19,16 +19,8 @@ import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicReference
/**
* The app's own UI as an agent sees it: every Compose node in every window of the process (popups
* and menus included), read from Compose's semantics rather than through UI Automator, which on a
* dual-screen device dumps whichever window has focus - often not this app's. Nodes carry their
* test tag (ui/TestTags.kt), text, content description, role, state and on-screen bounds; click
* and set-text act on a node by tag or text, so a test needs no coordinates.
*/
object AgentUi {
private const val TIMEOUT_MS = 5_000L
/** Setup's Debugging tools toggle: the bridge never acts on its own gate (AgentAccess). */
private const val GATE_TAG = "setting-agent-commands"
fun handle(request: JSONObject): JSONObject = when (val op = request.optString("op", "dump")) {
@@ -106,10 +98,6 @@ object AgentUi {
return json
}
/**
* The node a request names by "tag" (exact) or "match" (text or description containing it,
* ignoring case); "index" picks among several, in tree order.
*/
private fun act(request: JSONObject, action: (SemanticsNode) -> Unit): JSONObject {
val tag = request.optString("tag").takeIf { it.isNotEmpty() }
val text = if (tag == null) request.optString("match").takeIf { it.isNotEmpty() } else null
@@ -9,34 +9,12 @@ 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;
@@ -45,7 +23,6 @@ public class DirectAudioRelayComponent extends SessionPart {
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;
}
@@ -60,21 +37,10 @@ public class DirectAudioRelayComponent extends SessionPart {
}
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) {
@@ -91,12 +57,8 @@ public class DirectAudioRelayComponent extends SessionPart {
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<>();
@@ -126,8 +88,6 @@ public class DirectAudioRelayComponent extends SessionPart {
@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;
}
@@ -17,30 +17,15 @@ 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-10-08-pa13-directaudio-native";
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;
private volatile int pid = -1;
@@ -48,13 +33,11 @@ public class PulseAudioComponent extends SessionPart {
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;
}
/** 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];
@@ -67,7 +50,6 @@ public class PulseAudioComponent extends SessionPart {
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;
}
@@ -80,18 +62,9 @@ public class PulseAudioComponent extends SessionPart {
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);
@@ -112,38 +85,18 @@ public class PulseAudioComponent extends SessionPart {
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.
// The client's sound: DirectAudio's own engine, in this process, one step from Android.
// decay=0: shrinking the device buffer after a quiet spell probes below what works and that
// probe is a click; the client plays menus. Between .nofail and .fail a module that cannot
// open its stream does not take the daemon down; ensureClientSink() then loads the plain
// AAudio sink in its place.
config.add(".nofail");
config.add("load-module module-directaudio-native-sink sink_name=DirectAudio performance_mode=1 adaptive=1 decay=0 limiter=1 watchdog=1 volume=1.0");
config.add("set-default-sink DirectAudio");
config.add(".fail");
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");
@@ -159,12 +112,7 @@ public class PulseAudioComponent extends SessionPart {
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 -> {
@@ -176,11 +124,6 @@ public class PulseAudioComponent extends SessionPart {
guard.start();
}
/**
* The fallback: once the daemon answers, if the DirectAudio sink is not
* there (the module failed to load or to open its stream), load the plain AAudio sink so the
* client is never left without an output. Says so in the audio log either way.
*/
private void ensureClientSink(java.io.PrintWriter out) {
try {
long deadline = System.currentTimeMillis() + 15000L;
@@ -208,7 +151,6 @@ public class PulseAudioComponent extends SessionPart {
}
}
/** Runs pactl against this daemon; its stdout, or null when it failed or timed out. */
private String pactl(String... args) {
File pactl = new File(workingDir, "pactl");
if (!pactl.isFile() || pid <= 1) return null;
@@ -298,7 +240,6 @@ public class PulseAudioComponent extends SessionPart {
}
}
/** 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 {
@@ -6,22 +6,9 @@ import android.content.res.Configuration
import android.os.LocaleList
import java.util.Locale
/**
* The language the app shows itself in.
*
* Nothing chosen (the default) means the system's: Android's own language, or the per-app language
* Android 13+ lets a user set for DroidDeck in its settings, exactly as Android resolves it. Picking
* one in Setup overrides that until the user picks "System default" again. Each activity and service
* applies the choice to its own context ([wrap], [applyTo]), so it works on every Android version
* the app runs on rather than only where the platform's per-app language API exists.
*
* Steam follows the same choice: [SteamLanguage] turns [effective] into the client's language.
*/
object AppLanguage {
/** The stored value meaning "follow the system". */
const val SYSTEM = ""
/** The languages the app ships, as BCP 47 tags, in the order the picker lists them. */
val supported: List<String> = listOf(
"en", "id", "ms", "cs", "da", "de", "es", "es-419", "fr", "it", "hu", "nl", "nb", "pl",
"pt-BR", "pt-PT", "ro", "fi", "sv", "vi", "tr", "el", "bg", "ru", "uk", "ar", "hi", "th",
@@ -31,10 +18,8 @@ object AppLanguage {
private const val PREFS = "language"
private const val KEY = "app_language"
/** The locale Android gave the process before any choice here was applied. */
@Volatile private var systemLocale: Locale? = null
/** The stored choice: one of [supported], or [SYSTEM]. */
fun chosen(context: Context): String =
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getString(KEY, SYSTEM)
?.takeIf { it in supported } ?: SYSTEM
@@ -44,7 +29,6 @@ object AppLanguage {
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putString(KEY, value).commit()
val locale = value.takeIf { it.isNotEmpty() }?.let(Locale::forLanguageTag) ?: system(context)
Locale.setDefault(locale)
// Code that reads strings through the application context sees the new language too.
val app = context.applicationContext
@Suppress("DEPRECATION")
app.resources.updateConfiguration(
@@ -53,24 +37,16 @@ object AppLanguage {
)
}
/** The locale Android chose for the app, ignoring the choice made here. */
fun system(context: Context): Locale =
systemLocale ?: context.resources.configuration.locales[0] ?: Locale.getDefault()
/** The locale the app is shown in: the chosen language, or else the system's. */
fun effective(context: Context): Locale =
chosen(context).takeIf { it.isNotEmpty() }?.let(Locale::forLanguageTag) ?: system(context)
/** Remembers the system's locale; call with the untouched base context, before [wrap]. */
fun noteSystem(base: Context) {
if (systemLocale == null) systemLocale = base.resources.configuration.locales[0]
}
/**
* [base], showing the chosen language: for an Application's or a Service's attachBaseContext.
* Only the locale is overridden, so screen size, density and night mode keep following the
* device as they change.
*/
fun wrap(base: Context): Context {
noteSystem(base)
val tag = chosen(base).ifEmpty { return base }
@@ -79,11 +55,6 @@ object AppLanguage {
return base.createConfigurationContext(override(locale))
}
/**
* Applies the chosen language to an activity; call from its attachBaseContext, after super.
* applyOverrideConfiguration keeps the locale through rotation and window resizes, which an
* activity here handles itself rather than being recreated.
*/
fun applyTo(activity: Activity, base: Context) {
noteSystem(base)
val tag = chosen(base).ifEmpty { return }
@@ -92,13 +63,10 @@ object AppLanguage {
activity.applyOverrideConfiguration(override(locale))
}
/** Follows a change of the system's language while the process lives (Application.onConfigurationChanged). */
fun systemChanged(config: Configuration) {
config.locales[0]?.let { systemLocale = it }
}
// A new Configuration's fontScale is 1, which as an override would undo the user's font size;
// 0 leaves it undefined, so only the locale is changed.
private fun override(locale: Locale) = Configuration().apply { fontScale = 0f; setLocales(LocaleList(locale)) }
private val latinAmerica = setOf(
@@ -106,7 +74,6 @@ object AppLanguage {
"PE", "PR", "PY", "SV", "US", "UY", "VE",
)
/** Which of the app's languages [locale] reads as, or null when the app does not ship it. */
fun supportedTag(locale: Locale): String? = when (locale.language) {
"en", "fr", "ru", "ja", "ko", "ms", "cs", "da", "de", "it", "hu", "nl", "nb", "pl", "ro", "fi",
"sv", "vi", "tr", "el", "bg", "uk", "ar", "hi", "th" -> locale.language
@@ -122,11 +89,9 @@ object AppLanguage {
else -> null
}
/** [locale]'s language named in itself, without its region unless the app tells them apart. */
fun displayName(locale: Locale): String =
supportedTag(locale)?.let(::nativeName) ?: locale.getDisplayLanguage(locale).replaceFirstChar { it.titlecase(locale) }
/** A language's name in that language, for the picker: what a reader of it looks for. */
fun nativeName(tag: String): String = when (tag) {
"en" -> "English"
"id" -> "Bahasa Indonesia"
@@ -3,18 +3,9 @@ package com.droiddeck.launcher.core;
import java.io.File;
import java.io.IOException;
/**
* Where an archive entry may land. An entry name ("../x", "/etc/x") or a symlink already written
* by an earlier entry can point outside the directory being filled; the canonical path follows
* both, so anything that does not resolve inside it is refused.
*/
public final class ArchivePaths {
private ArchivePaths() {}
/**
* The file for {@code name} under {@code destination}, or null when it would resolve outside
* it. The destination itself counts as inside (a "./" entry).
*/
public static File inside(File destination, String name) throws IOException {
String base = destination.getCanonicalPath();
File file = new File(destination, name);
@@ -3,7 +3,6 @@ package com.droiddeck.launcher.core
import com.droiddeck.launcher.gpu.GpuInfo
import com.droiddeck.launcher.gpu.SocNames
/** Device defaults only: affinity does not reserve cores or lock their clocks. */
object CpuAllocationDefaults {
data class Allocation(val client: String, val game: String)
@@ -12,7 +11,6 @@ object CpuAllocationDefaults {
CpuCores.all.associateWith(CpuCores::maxGhz))
}
/** Select by topology, including faster SM8550 variants; never guess core indices. */
fun forDevice(model: String, platform: String, frequencies: Map<Int, Double?>): Allocation? {
val chip = model.trim().uppercase().substringBefore('-')
val gen2 = chip in setOf("SM8550", "QCS8550") ||
@@ -2,17 +2,9 @@ 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 }
@@ -22,22 +14,14 @@ object CpuCores {
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)
}
/** An all-core game must undo the affinity inherited from a pinned Steam client. */
fun gameLaunchList(list: String, clientPinned: Boolean): String =
restrictionOrEmpty(list).ifEmpty { if (clientPinned) listOrAll("") else "" }
/**
* 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)
@@ -21,15 +21,6 @@ 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"
@@ -5,26 +5,14 @@ import android.os.Build
import com.droiddeck.launcher.R
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(context: Context): 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 { context.getString(R.string.gpu_this_gpu) }
}
/** False on the Odin 3 (CQ8725S): a low-latency Wi-Fi lock makes its WLAN firmware hang, and
* that firmware reboots the whole device instead of restarting Wi-Fi. */
fun lowLatencyWifiSafe(): Boolean = Build.VERSION.SDK_INT < 31 || Build.SOC_MODEL != "CQ8725S"
}
@@ -12,11 +12,6 @@ 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;
@@ -44,11 +39,6 @@ public final class Downloader {
}
}
/**
* 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;
@@ -59,10 +49,8 @@ public final class Downloader {
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);
}
@@ -73,7 +61,7 @@ public final class Downloader {
long length = connection.getContentLengthLong();
long total = length < 0 ? -1 : length + have;
File parent = destination.getParentFile();
if (parent != null && !parent.isDirectory()) //noinspection ResultOfMethodCallIgnored
if (parent != null && !parent.isDirectory())
parent.mkdirs();
long written = have;
try (InputStream in = new BufferedInputStream(connection.getInputStream(), 1 << 16);
@@ -83,8 +71,6 @@ public final class Downloader {
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);
@@ -28,7 +28,6 @@ object FexPreset {
fun byId(id: String): Preset = all.firstOrNull { it.id == id } ?: all[0]
/** Game-launch variables in KEY=VALUE form. */
fun env(id: String): List<String> = byId(id).env
val environmentKeys: Set<String> by lazy {
@@ -18,14 +18,12 @@ public final class 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();
}
@@ -37,7 +35,6 @@ public final class FileUtils {
}
}
/** Empties a directory without removing it. */
public static void clear(File dir) {
if (dir == null || !dir.isDirectory()) return;
File[] children = dir.listFiles();
@@ -47,7 +44,7 @@ public final class FileUtils {
public static boolean writeString(File file, String content) {
try {
File parent = file.getParentFile();
if (parent != null && !parent.isDirectory()) //noinspection ResultOfMethodCallIgnored
if (parent != null && !parent.isDirectory())
parent.mkdirs();
Files.write(file.toPath(), content.getBytes(StandardCharsets.UTF_8));
return true;
@@ -81,10 +78,9 @@ public final class FileUtils {
}
}
/** 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
if (parent != null && !parent.isDirectory())
parent.mkdirs();
try (InputStream in = context.getAssets().open(assetPath);
OutputStream out = new FileOutputStream(destination)) {
@@ -29,25 +29,15 @@ object GameEnvironment {
"MESA_SHADER_CACHE_DISABLE" to "false",
"VKD3D_FEATURE_LEVEL" to "12_2",
"VKD3D_SHADER_MODEL" to "6_9",
// .NET 7 and later reserve 256 GB of address space for the GC heap at startup, more than an
// Android process has free, and the runtime fails to start. 32 GB is plenty for a game.
// Older NativeAOT runtimes require bare hex digits. CoreCLR accepts this form too.
"DOTNET_GCRegionRange" to "800000000",
// .NET's W^X writes JIT code through a second mapping that FEX does not watch, so FEX keeps
// running the stale translation and the game hangs at startup.
"DOTNET_EnableWriteXorExecute" to "0",
).apply {
FexPreset.env(preset).forEach { put(it.substringBefore('='), it.substringAfter('=')) }
// Steam settings' Force SSBS: droiddeck-game-env preloads libssbs.so into the game's Wine.
if (forceSsbs) put(FORCE_SSBS, "1")
}
const val FORCE_SSBS = "DROIDDECK_FORCE_SSBS"
/**
* A game's Start without Steam: droiddeck-game-env launches it without Proton's steam.exe (umu's
* launch where the Proton has it, else runinprefix), for games that close right away.
*/
const val NO_STEAM = "DROIDDECK_NO_STEAM"
fun gameNoSteam(config: Config, scope: String): Boolean =
@@ -3,7 +3,6 @@ package com.droiddeck.launcher.core
import java.io.File
import java.security.MessageDigest
/** File checksums as lowercase hex, and GitHub's release-asset digests, in one place. */
object Hashes {
private val GITHUB_SHA256 = Regex("(?i)sha256:[0-9a-f]{64}")
@@ -13,11 +12,9 @@ object Hashes {
@JvmStatic
fun sha512(file: File): String = hex(file, "SHA-512")
/** True when [digest] is GitHub's asset digest form, "sha256:" and 64 hex digits. */
@JvmStatic
fun isGithubSha256(digest: String?): Boolean = digest != null && digest.matches(GITHUB_SHA256)
/** The hex of a GitHub asset digest ("sha256:<hex>"), or null when [digest] is not one. */
@JvmStatic
fun githubSha256(digest: String?): String? = digest?.takeIf { isGithubSha256(it) }?.substringAfter(':')
@@ -1,6 +1,5 @@
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>()
@@ -8,6 +7,5 @@ class HostEnvironment {
entries[name] = value
}
/** `NAME=VALUE` lines, the shape ProcessBuilder and proot take. */
fun asArray(): Array<String> = entries.map { (name, value) -> "$name=$value" }.toTypedArray()
}
@@ -4,27 +4,9 @@ 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)
@@ -46,14 +28,13 @@ object HostProcess {
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 */ }
try { status = process.waitFor() } catch (e: InterruptedException) { }
onExit.accept(status)
}, "proc-wait-$pid").apply { priority = Thread.NORM_PRIORITY - 1; start() }
}
@@ -75,7 +56,6 @@ object HostProcess {
-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>()
@@ -1,64 +1,28 @@
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 Valve's server 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.
*
* The device's OWN addresses are not kept: the client's IPv6 check logs "external address <ours>"
* about twenty times a session, and a public IPv6 address is the user's. [learnOwnAddresses] reads
* the link the session was given (etc/droiddeck-net) and every address on the same /64 - privacy
* addresses rotate inside it - or an own public IPv4 is replaced wherever it appears. Likewise every
* Steam account and persona name on the device ([learnAccounts]), for users who sign in with an
* account name rather than an email.
*/
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+)]")
/** "external address 2607:..." / "external IP: 203.0.113.9" - the client stating ours. */
private val EXTERNAL_ADDR = Regex("(?i)(external\\s+(?:ip\\s+)?address\\s*[:=]?\\s*|external\\s+ip\\s*[:=]?\\s*)([0-9A-Fa-f:.]{7,})")
private val IPV4 = Regex("(?<![0-9.])(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})(?![0-9.])")
/** An IPv6 literal: "::" somewhere, or all eight groups (a clock's 10:03:05 is neither). */
private val IPV6 = Regex("(?<![0-9A-Za-z:])[0-9A-Fa-f]{0,4}(?::[0-9A-Fa-f]{0,4}){2,7}(?:%[A-Za-z0-9_.]+)?(?![0-9A-Za-z:])")
private val MAC = Regex("(?i)(?<![0-9a-z:-])[0-9a-f]{2}([:-])(?:[0-9a-f]{2}\\1){4}[0-9a-f]{2}(?![0-9a-z:-])")
private val MAC_FIELD = Regex(
@@ -70,20 +34,9 @@ object LogRedactor {
"[\"']?\\s*[:=]\\s*)(\"[^\"\\r\\n<>]+\"|'[^'\\r\\n<>]+'|[^\\s\"'<>&;,\\[\\]{}]+)"
)
/**
* The account a Steam UI login line names ("Login: OnLoginStateChange <account> 2 1 0 0"): a
* user who signs in with a plain account name, not an email, had it in every log. The single
* space then a non-space keeps "OnLoginStateChange 0 1 0 0" (no account yet) as it is.
*/
private val LOGIN_STATE = Regex("(?i)(OnLoginStateChange:? )([^\\s<]\\S*)")
private val LOGIN_USERS = Regex("(OnLoginUsersChanged )(\\S.*)$")
/**
* An account name as a field: `AccountName`, `account_name`, `username` (`"AccountName"
* "someone"` in a VDF, `account_name=...`, `"username": "..."`) and `login` - the last only
* as `login=`, a quoted key or a VDF pair, so "Login: OnLoginStateChange ..." keeps its label.
* A quoted value is blanked whole; one already blanked is left as it is.
*/
private const val ACCOUNT_VALUE = "(\"[^\"<\\r\\n]+\"|'[^'<\\r\\n]+'|[^\\s\"'<>&;,}]+)"
private val ACCOUNT_KV = Regex(
"(?i)(?<![A-Za-z0-9_])(account[_-]?name|user[_-]?name|epicusername)" +
@@ -93,18 +46,11 @@ object LogRedactor {
"(?i)(?<![A-Za-z0-9_])(login)(\\s*=\\s*|[\"']\\s*[=:]\\s*|[\"']\\s+)" + ACCOUNT_VALUE
)
/** A learned pattern and the text (lowercase) a line must hold for it to match; null when none can be said. */
private class Learned(val regex: Regex, val needs: String?)
/** The device's Steam accounts and persona names as patterns (see [learnAccounts]). */
@Volatile
private var accounts: List<Learned> = emptyList()
/**
* Learns every Steam account on the device from the client's loginusers.vdf - its AccountName
* and PersonaName - so they are replaced wherever a log mentions them, whoever the user is.
* Names under three characters are skipped: blanking every "a" would ruin a log.
*/
fun learnAccounts(loginUsers: java.io.File) {
val found = ArrayList<Learned>()
try {
@@ -121,21 +67,14 @@ object LogRedactor {
accounts = found
}
/** Everything the session's runtime can tell about whose logs these are: addresses and accounts. */
fun learnFromRuntime(root: java.io.File) {
learnOwnAddresses(java.io.File(root, "etc/droiddeck-net"))
learnAccounts(java.io.File(root, "root/.local/share/Steam/config/loginusers.vdf"))
}
/** This device's public addresses as patterns (see [learnOwnAddresses]); empty until learned. */
@Volatile
private var own: List<Learned> = emptyList()
/**
* Learns the device's addresses from the link file the app writes for the session
* (`addr <address> <prefix>` lines). Global IPv6 become their /64, public IPv4 stay exact;
* private, link-local and loopback addresses identify nobody and are left out.
*/
fun learnOwnAddresses(linkFile: java.io.File) {
val found = ArrayList<Learned>()
try {
@@ -144,7 +83,6 @@ object LogRedactor {
when (kind(addr)) {
"public IPv6" -> {
val groups = expand6(addr)?.take(4) ?: return@forEachLine
// Any spelling of an address in this /64: leading zeros dropped, :: anywhere after.
val prefix = groups.joinToString(":") { g -> "0{0,3}" + Regex.escape(g.trimStart('0').ifEmpty { "0" }) }
found += Learned(
Regex("(?i)(?<![0-9A-Fa-f:])$prefix(?::[0-9A-Fa-f]{0,4}){1,4}(?:%[A-Za-z0-9_.]+)?"),
@@ -160,7 +98,6 @@ object LogRedactor {
own = found
}
/** "public IPv6", "private IPv4", "link-local IPv6", ... for an address literal; null if it is not one. */
fun kind(address: String): String? {
val a = address.substringBefore('%')
IPV4.matchEntire(a)?.let { m ->
@@ -184,7 +121,6 @@ object LogRedactor {
}
}
/** The eight groups of an IPv6 literal, or null. */
private fun expand6(address: String): List<String>? {
val a = address.substringBefore('%')
if (!a.contains(':') || a.count { it == ':' } > 7 || a.contains(":::")) return null
@@ -200,17 +136,12 @@ object LogRedactor {
return parts.map { it.lowercase() }
}
/**
* Every IP address in [text] replaced by what kind it is ("<public IPv6>"), for reports whose
* point is the shape of the network, not its numbers.
*/
fun describeAddresses(text: String): String {
var out = IPV6.replace(text) { m -> kind(m.value)?.let { "<$it>" } ?: m.value }
out = IPV4.replace(out) { m -> kind(m.value)?.let { "<$it>" } ?: m.value }
return out
}
/** A file worth scrubbing: text (no NUL in its first 4 KB) and not huge. */
fun isText(file: java.io.File): Boolean = try {
file.isFile && file.length() < 64L * 1024 * 1024 && file.inputStream().use { input ->
val buf = ByteArray(4096)
@@ -221,34 +152,16 @@ object LogRedactor {
false
}
/**
* Bump whenever a pattern is added or tightened. A session folder records the version it was
* scrubbed under (SessionArtifacts.SCRUBBED_TREE_MARKER), and a share copies a file as it is
* only when that matches, so a folder scrubbed under older rules is scrubbed again on the way
* out.
*/
const val RULES_VERSION = 3
/**
* A private IPv4 address (10/8, 172.16/12, 192.168/16, link-local 169.254/16): the home
* network's layout, e.g. its router as the resolver. Blanked in a shared zip only; public
* server addresses stay. Not part of a longer dotted number (a version like 10.0.19041.1).
*/
private val LAN_IPV4 = Regex(
"(?<![\\d.])(?:10\\.\\d{1,3}|192\\.168|172\\.(?:1[6-9]|2\\d|3[01])|169\\.254)\\.\\d{1,3}\\.\\d{1,3}(?!\\.?\\d)"
)
/** [src]'s lines, scrubbed, to [out]. */
fun scrubTo(src: java.io.File, out: java.io.Writer) {
src.forEachLine { line -> out.write(redact(line)); out.write("\n") }
}
/**
* The last pass for a file going into a shared zip: [redact], then the rules the stores' log
* uses too ([SecretScrub]) - URLs without query, fragment and user:password and with any
* token-bearing path segment blanked, token values and Authorization / Cookie headers blanked
* - and private IPv4 addresses as `<lan-address>`. A line already clean comes out unchanged.
*/
fun redactForShare(line: String): String {
if (line.isEmpty()) return line
return try {
@@ -259,23 +172,15 @@ object LogRedactor {
}
}
/** [src]'s lines through [redactForShare], to [out]: the pass every text file in a shared zip gets. */
fun scrubForShare(src: java.io.File, out: java.io.Writer) {
src.forEachLine { line -> out.write(redactForShare(line)); out.write("\n") }
}
/** `<redacted:account>`, inside [value]'s quotes when it had them. */
private fun quoted(value: String): String {
val q = value.first().takeIf { it == '"' || it == '\'' }?.toString().orEmpty()
return "$q<redacted:account>$q"
}
/**
* A line on its way through [redact]. Each rule runs only on a line holding what it cannot match
* without - a word, enough separators, a long enough run: most of a Steam log is lines no rule
* touches, and a session's logs went through every rule at about a megabyte a second. A line with anything but ASCII in it goes through
* every case-insensitive rule, since Android's regex folds case more widely than lowercase().
*/
private class Line(var text: String) {
private val unfolded = text.any { it.code >= 0x80 }
private var lower: String? = null
@@ -308,7 +213,6 @@ object LogRedactor {
private fun isHex(c: Char) = c in '0'..'9' || c in 'a'..'f' || c in 'A'..'F'
/** [line] with every credential shape replaced. Null- and exception-safe by construction. */
fun redact(line: String): String {
if (line.isEmpty()) return line
return try {
@@ -328,7 +232,6 @@ object LogRedactor {
}
if (out.has("guard", "factor", "2fa")) out.set(GUARD_CODE.replace(out.text) { "${it.groupValues[1]}<redacted:code>" })
if (out.hasRun(32, ::isHex)) out.set(WEBAPI_KEY.replace(out.text, "<redacted:key>"))
// Mask, not delete: the last four digits let a reader correlate lines to one account.
if ("76561" in out.text) out.set(STEAMID64.replace(out.text) { "${it.groupValues[1]}********${it.groupValues[3]}" })
if ("[U:1:" in out.text) out.set(STEAMID3.replace(out.text) { m ->
val id = m.groupValues[1]
@@ -352,8 +255,6 @@ object LogRedactor {
}
out.text
} 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>"
}
}
@@ -10,24 +10,11 @@ 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's NetworkManager bridge reports Android's active link. Include whether the phone
* had a validated link and which DNS servers the app wrote into the runtime's `resolv.conf`.
*
* **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 {
// Addresses as their kind ("<public IPv6>"), never the numbers: a public address is the
// user's, and this file goes into shared session logs. The session's made-up hardware
// address is stable per device (seeded from ANDROID_ID), so it is masked too.
val text = LogRedactor.describeAddresses(build(context))
.replace(Regex("(?m)^(\\s*mac )\\S+"), "$1<masked>")
target.writeText(text)
@@ -82,8 +69,6 @@ object NetworkReport {
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")
@@ -5,7 +5,6 @@ import android.os.Build
import android.provider.Settings
import com.droiddeck.launcher.R
/** Android's phantom process monitor can kill the many child processes used by a Steam session. */
enum class PhantomProcessStatus {
NOT_APPLICABLE,
DISABLED,
@@ -68,12 +67,6 @@ object PhantomProcessLimit {
return status(global, systemProperty(OVERRIDE_PROPERTY))
}
/**
* The value Android itself acts on, in FeatureFlagUtils.isEnabled's order: the global setting
* when it is set, otherwise the feature-flag override property. Developer options' "Disable
* child process restrictions" writes only the property, so a device switched off there has no
* global setting at all and must not be reported as unset.
*/
fun status(global: String?, override: String?): PhantomProcessStatus {
val value = global?.trim()?.lowercase()?.takeIf { it.isNotEmpty() }
?: override?.trim()?.lowercase()?.takeIf { it.isNotEmpty() }
@@ -122,7 +115,6 @@ object PhantomProcessLimit {
fun fixSentence(context: Context, sdk: Int = Build.VERSION.SDK_INT): String =
context.getString(if (hasDeveloperToggle(sdk)) R.string.phantom_fix_toggle else R.string.phantom_fix_no_toggle)
/** English: for the device report. */
fun reportValue(status: PhantomProcessStatus): String = when (status) {
PhantomProcessStatus.DISABLED -> "disabled (good - the OS will not kill the session's children)"
PhantomProcessStatus.ENABLED -> "ENABLED (the OS may kill the session with no log; turn off Restrict child processes)"
@@ -1,21 +1,5 @@
package com.droiddeck.launcher.core
/**
* The one set of rules that keeps URLs and tokens out of anything the app writes or shares: the
* stores' log ([com.droiddeck.launcher.stores.StoreLog.redactLine]) and the last pass over every
* text file in a shared log zip ([LogRedactor.redactForShare]).
*
* - Every URL loses its query, fragment and `user:password@`. [Urls.SHORT] then keeps only the host
* and a plain first path segment (the stores' lines, where a GOG secure link carries its token in
* the path); [Urls.KEEP_PATH] keeps the path but blanks any segment that carries a token.
* - Outside URLs, the values of token-like keys (`token`, `__token__`, `f_token`, `hdnts`, access /
* refresh / id tokens; exchange and authorization codes of four characters or more, and a bare
* `code=` where it is one: in a query string or on a line with OAuth keys such as `client_id`,
* `redirect_uri` or `state`, never an 8-hex exception code like Proton's `code=c0000005`) and of
* Authorization / Cookie headers are blanked with [mark].
*
* A line already scrubbed comes out unchanged.
*/
object SecretScrub {
enum class Urls { SHORT, KEEP_PATH }
@@ -23,12 +7,9 @@ object SecretScrub {
private val SAFE_SEGMENT = Regex("""[A-Za-z0-9._\-]{1,40}""")
private val TOKEN_SEGMENT = Regex("""(?i)(token|hdnts|hmac|signature|sig|exp)=""")
private val TOKEN = Regex("""(?i)(?<![A-Za-z0-9_])(__token__|f_token|hdnts|access_token|refresh_token|id_token|token)(["']?\s*[=:]\s*["']?)[^\s&;,"'<>}]+""")
/** Codes that are only ever OAuth grants. */
private val GRANT_CODE = Regex("""(?i)(?<![A-Za-z0-9_])(exchange_code|authorization_?code)(["']?\s*=\s*["']?)[^\s&;,"'<>}]{4,}""")
/** A bare `code=`: a grant only right after `?` / `&` (a query string) or beside OAuth keys ([OAUTH_CONTEXT]). */
private val CODE = Regex("""(?i)(?<![A-Za-z0-9_])(code)(["']?\s*=\s*["']?)([^\s&;,"'<>}]{4,})""")
private val OAUTH_CONTEXT = Regex("""(?i)(?<![A-Za-z0-9_])(client_id|client_secret|redirect_uri|state|grant_type|response_type|access_token|refresh_token|id_token)["']?\s*[=:]""")
/** A Windows exception or status code (`code=c0000005`, `code=0x80000003`): never a grant. */
private val STATUS_CODE = Regex("""(?i)(0x)?[0-9a-f]{8}""")
private val HEADER = Regex("""(?i)\b(authorization|cookie|set-cookie)(\s*[:=]\s*).+""")
@@ -5,24 +5,6 @@ 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"
@@ -30,7 +12,6 @@ object SessionLogCapture {
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()
@@ -41,8 +22,6 @@ object SessionLogCapture {
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,
@@ -51,7 +30,6 @@ object SessionLogCapture {
try {
writer?.apply { write(line); newLine(); flush() }
} catch (e: Exception) {
// A full or unmounted card must not take the session with it.
}
}
}
@@ -65,7 +43,6 @@ object SessionLogCapture {
}
}
/** 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
@@ -86,23 +63,14 @@ object SessionLogCapture {
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() },
@@ -2,12 +2,6 @@ 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;
@@ -15,7 +9,6 @@ public abstract class SessionPart {
this.app = context.getApplicationContext();
}
/** The application context, valid after {@link #attach}. */
protected final Context app() {
return app;
}
@@ -13,11 +13,6 @@ 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";
@@ -33,7 +28,6 @@ public final class TarZst {
}
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)) {
@@ -42,15 +36,13 @@ public final class TarZst {
File file = ArchivePaths.inside(destination, entry.getName());
if (file == null) continue;
if (entry.isDirectory()) {
//noinspection ResultOfMethodCallIgnored
file.mkdirs();
continue;
}
File parent = file.getParentFile();
if (parent != null && !parent.isDirectory()) //noinspection ResultOfMethodCallIgnored
if (parent != null && !parent.isDirectory())
parent.mkdirs();
if (entry.isSymbolicLink()) {
//noinspection ResultOfMethodCallIgnored
file.delete();
FileUtils.symlink(entry.getLinkName(), file.getAbsolutePath());
continue;
@@ -59,7 +51,7 @@ public final class TarZst {
try (OutputStream out = new FileOutputStream(file)) {
FileUtils.copy(tar, out);
}
if ((entry.getMode() & 0111) != 0) //noinspection ResultOfMethodCallIgnored
if ((entry.getMode() & 0111) != 0)
file.setExecutable(true, false);
}
return true;
@@ -5,29 +5,15 @@ import kotlin.math.ln
import kotlin.math.max
import kotlin.math.min
/**
* Texture filtering for DirectX 9-11 games, as DXVK configuration options
* (d3d9/d3d11.samplerAnisotropy and samplerLodBias). VKD3D-Proton and WineD3D do not read them.
* Published into the game environment and read by DXVK when a game starts, so a change lands on
* the next launch, not the running game.
*/
object TextureFiltering {
/** 0 = the game's own filtering; otherwise that anisotropy on every linearly filtered sampler. */
val ANISOTROPY = listOf(0, 2, 4, 8, 16)
/** Negative mip LOD bias added to the game's own: sharper textures at the cost of some shimmer. */
const val LOD_BIAS_OFF = "0"
/** Derived from how far the session is enlarged to the panel (see [autoLodBias]). */
const val LOD_BIAS_AUTO = "auto"
val LOD_BIAS = listOf(LOD_BIAS_OFF, LOD_BIAS_AUTO, "-0.25", "-0.5", "-0.75", "-1.0")
private const val LOD_BIAS_MIN = -2f
/**
* The mip LOD bias for a picture enlarged by [scale] (panel size over session size, long side
* to long side): -log2(scale), AMD's FSR 1 guidance (a 1.5x enlargement - 720p on a 1080p
* panel - gives -0.58). 0 when the session is not enlarged or the scale is unknown.
*/
fun autoLodBias(scale: Float): Float {
if (scale.isNaN() || scale <= 1f) return 0f
return max((-ln(scale.toDouble()) / ln(2.0)).toFloat(), LOD_BIAS_MIN)
@@ -39,7 +25,6 @@ object TextureFiltering {
else -> choice.toFloatOrNull()?.let { max(min(it, 0f), LOD_BIAS_MIN) } ?: 0f
}
/** The DXVK_CONFIG options for the two settings, "" when both are left to the game. */
fun dxvkOptions(anisotropy: Int, lodBiasChoice: String, autoBias: Float): String {
val parts = ArrayList<String>(4)
val aniso = if (anisotropy in ANISOTROPY) anisotropy else 0
@@ -49,7 +34,6 @@ object TextureFiltering {
}
val bias = lodBias(lodBiasChoice, autoBias)
if (bias < 0f) {
// Locale.US: DXVK parses "-0.58", never "-0,58".
val b = String.format(Locale.US, "%.2f", bias)
parts += "d3d9.samplerLodBias = $b"
parts += "d3d11.samplerLodBias = $b"
@@ -7,11 +7,9 @@ import android.location.LocationManager
import android.os.Build
import com.droiddeck.launcher.session.SessionPrefs
/** Location is used only for Android's Wi-Fi names and scan results, never coordinates. */
object WifiDiscovery {
val permissions = arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION)
// targetSdk 28 accepts either grant for Wi-Fi scanning.
fun permissionGranted(context: Context): Boolean = permissions.any {
context.checkSelfPermission(it) == PackageManager.PERMISSION_GRANTED
}
@@ -16,7 +16,6 @@ import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicInteger
import java.util.ArrayDeque
/** A narrowly scoped Wireless debugging client for the child-process setting repair. */
object WirelessAdbFix {
private const val CERT_FILE = "wireless-adb-cert.pem"
private const val KEY_FILE = "wireless-adb-key.pem"
@@ -66,7 +65,6 @@ object WirelessAdbFix {
return SavedConnection(host, port)
}
/** A saved pairing skips the PIN; an unknown connection port can be filled in from Settings. */
fun savedConnectionAddress(context: Context): String? = savedConnection(context)?.let { saved ->
val host = if (':' in saved.host) "[${saved.host}]" else saved.host
"$host:${saved.port ?: ""}"
@@ -80,7 +78,6 @@ object WirelessAdbFix {
)
}
/** Finds this paired device's separate TLS connection port from Android's ADB mDNS record. */
fun isLocalAddress(address: InetAddress): Boolean = runCatching {
if (address.isLoopbackAddress) return true
NetworkInterface.getNetworkInterfaces()?.toList().orEmpty().any { network ->
@@ -184,7 +181,6 @@ object WirelessAdbFix {
saveConnection(context, host, port)
}
/** Tries the app's saved pairing without asking for a new pairing code. */
fun setUsingSavedPairing(context: Context, enabled: Boolean) {
val appContext = context.applicationContext
val saved = savedConnection(appContext)
@@ -5,7 +5,6 @@ import android.content.Context
import android.os.Build
import java.io.File
/** Whether the client's memory can be paged out to compressed swap: MADV_PAGEOUT (Linux 5.4) and a zram or other swap device. */
object ZramSupport {
private const val GIB = 1L shl 30
@@ -23,15 +23,6 @@ import java.nio.file.Path
import java.nio.file.SimpleFileVisitor
import java.nio.file.attribute.BasicFileAttributes
/**
* The app's own data folder (the Linux runtime, settings, logs) in Android's file picker, under the
* app's name beside the phone's storage - what MT Manager's "documents provider" injection does, as
* part of the app. Only the system's documents UI can bind it (MANAGE_DOCUMENTS); another app sees
* a file only when the user picks it there.
*
* A document id is the file's absolute path, and nothing outside the data folder is ever handed out
* or accepted: every id is resolved and checked to lie inside it.
*/
class AppFilesProvider : DocumentsProvider() {
private lateinit var base: File
private lateinit var baseCanonical: String
@@ -65,8 +56,6 @@ class AppFilesProvider : DocumentsProvider() {
override fun queryChildDocuments(parentDocumentId: String, projection: Array<String>?, sortOrder: String?): Cursor {
val result = MatrixCursor(projection ?: DOCUMENT_COLUMNS)
// A link in the runtime that leads out of the data folder (/etc/localtime and the like) is
// left out rather than listed as something that cannot be opened.
fileFor(parentDocumentId).listFiles()?.filter { inside(it) }?.forEach { addRow(result, it) }
return result
}
@@ -104,10 +93,6 @@ class AppFilesProvider : DocumentsProvider() {
}
}
/**
* Deletes a file or a folder and what is in it without ever following a link: the runtime holds
* links to places outside it, and deleting a folder must remove the link, not what it points at.
*/
private fun deleteTree(root: Path) {
if (!Files.isDirectory(root, LinkOption.NOFOLLOW_LINKS)) {
Files.delete(root)
@@ -158,7 +143,6 @@ class AppFilesProvider : DocumentsProvider() {
val needle = query.lowercase()
val pending = ArrayDeque(listOf(base))
var visited = 0
// The runtime is tens of thousands of files: a bounded walk, not the whole tree.
while (pending.isNotEmpty() && result.count < 50 && visited++ < 20000) {
val f = pending.removeFirst()
if (!inside(f)) continue
@@ -168,7 +152,6 @@ class AppFilesProvider : DocumentsProvider() {
return result
}
/** The file an id names, when it exists and lies inside the data folder (links followed). */
private fun fileFor(documentId: String): File {
val f = File(documentId)
if (!f.isAbsolute || !inside(f)) throw FileNotFoundException("$documentId is outside the app's files")
@@ -177,7 +160,6 @@ class AppFilesProvider : DocumentsProvider() {
}
private fun inside(f: File): Boolean {
// The folder's own entries are listed as they are; a link is judged by where it leads.
val abs = f.absoluteFile.normalize().path
if (abs != base.absolutePath && !abs.startsWith(base.absolutePath + "/")) return false
val real = runCatching { f.canonicalPath }.getOrNull() ?: return false
@@ -225,11 +207,6 @@ class AppFilesProvider : DocumentsProvider() {
Document.COLUMN_LAST_MODIFIED, Document.COLUMN_FLAGS, Document.COLUMN_SIZE,
)
/**
* The name in the picker. The same app ships under other package names (for the performance
* modes some phones give only named apps); each says which it is, so four installs are not
* four identical "DroidDeck" entries.
*/
fun titleFor(context: Context): String {
val name = context.getString(R.string.app_name)
return when (context.packageName) {
@@ -49,38 +49,26 @@ 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,
/** The under-icon label when the rail is collapsed, for names too long to fit; null derives one. */
val shortLabel: String? = null,
// onClick stays LAST so existing call sites can pass it as a trailing lambda; badge is an
// 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
"ENVIROMENT" -> return "ENVIRON"
"WIN COMPONENTS" -> return "WIN COMP"
}
if (label.contains(' ')) return label // multi-word → wraps to 2 lines
if (label.contains(' ')) return label
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) {
@@ -99,21 +87,10 @@ private fun RailItemIcon(item: RailItem, tint: androidx.compose.ui.graphics.Colo
}
}
/** 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,
)
@@ -121,15 +98,12 @@ class RailState internal constructor(
@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)
@@ -152,16 +126,6 @@ fun rememberRailState(screenKey: String): RailState {
)
}
/**
* 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,
@@ -170,12 +134,7 @@ fun CollapsibleRail(
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
@@ -187,7 +146,6 @@ fun CollapsibleRail(
.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,
@@ -228,14 +186,12 @@ fun CollapsibleRail(
}
}
}
// 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)) {
@@ -258,8 +214,6 @@ fun CollapsibleRail(
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)
@@ -283,8 +237,6 @@ fun CollapsibleRail(
}
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) {
@@ -308,9 +260,6 @@ fun CollapsibleRail(
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,
@@ -350,9 +299,8 @@ fun CollapsibleRail(
}
}
} // 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()
@@ -360,16 +308,6 @@ fun CollapsibleRail(
}
}
/**
* 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>,
@@ -391,7 +329,6 @@ fun RailTopTabs(
)
}
if (links.isNotEmpty()) {
// Faint separator: everything past here is an action button, not a tab.
Box(
modifier = Modifier
.padding(horizontal = 2.dp)
@@ -408,8 +345,6 @@ fun RailTopTabs(
}
}
/** 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,
@@ -3,15 +3,6 @@ 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"
@@ -20,7 +11,6 @@ object FavoritesStore {
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 {
@@ -31,7 +21,6 @@ object FavoritesStore {
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
@@ -44,7 +33,6 @@ object FavoritesStore {
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
@@ -4,30 +4,18 @@ import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue
import java.io.File
// Reading and setting a file's read-only and hidden attributes (the DOS attribute xattr).
// ── DOS file attributes (Read-only / Hidden) ──
// The in-container file manager (wfm.exe) exposes these in its Properties dialog; this mirrors the
// same two toggles for files browsed from the app side. No root - we only touch permission bits the
// app owns (container files) and the Wine DOS-attribute xattr.
// FILE_ATTRIBUTE_HIDDEN, as Wine encodes it in the user.DOSATTRIB extended attribute.
private const val FILE_ATTRIBUTE_HIDDEN = 0x2
private const val DOSATTRIB_XATTR = "user.DOSATTRIB"
// Snapshot of a file's two toggleable attributes. hiddenSupported is false when the underlying
// filesystem can't store the DOSATTRIB xattr (the FUSE /storage volumes) - the Hidden toggle is then
// disabled while Read-only keeps working.
internal data class FileAttrState(
val readOnly: Boolean,
val hidden: Boolean,
val hiddenSupported: Boolean,
)
// Wine (and Samba) store user.DOSATTRIB as an ASCII hex string ("0x22"), sometimes with trailing
// Samba fields after a separator. We only need the leading DOS-attribute hex, so read from the "0x"
// prefix and stop at the first non-hex character.
private fun parseDosAttrib(raw: ByteArray): Int {
val s = String(raw, Charsets.US_ASCII).trim()
val hex = if (s.startsWith("0x") || s.startsWith("0X")) s.substring(2) else s
@@ -35,11 +23,8 @@ private fun parseDosAttrib(raw: ByteArray): Int {
return digits.toIntOrNull(16) ?: 0
}
// Read the current read-only + Wine-hidden state. Never throws: an xattr-unsupported filesystem
// comes back hiddenSupported=false (Hidden toggle disabled), Read-only always resolves.
internal fun readFileAttrs(file: File): FileAttrState {
val path = file.absolutePath
// Read-only reflects the OWNER write bit - that's what Wine maps to FILE_ATTRIBUTE_READONLY.
val readOnly = runCatching {
(android.system.Os.stat(path).st_mode and android.system.OsConstants.S_IWUSR) == 0
}.getOrDefault(!file.canWrite())
@@ -49,8 +34,6 @@ internal fun readFileAttrs(file: File): FileAttrState {
try {
hidden = (parseDosAttrib(android.system.Os.getxattr(path, DOSATTRIB_XATTR)) and FILE_ATTRIBUTE_HIDDEN) != 0
} catch (e: android.system.ErrnoException) {
// ENODATA: xattr namespace works, the attribute just isn't set yet -> still toggleable.
// ENOTSUP/EOPNOTSUPP/anything else: the fs can't store it -> disable the Hidden toggle.
supported = e.errno == android.system.OsConstants.ENODATA
} catch (e: Exception) {
supported = false
@@ -58,10 +41,6 @@ internal fun readFileAttrs(file: File): FileAttrState {
return FileAttrState(readOnly, hidden, supported)
}
// Toggle read-only by flipping the write bits, preserving every other permission bit. Setting
// read-only clears owner/group/other write (so Wine sees FILE_ATTRIBUTE_READONLY regardless of which
// write bit it checks); clearing it restores owner write. Falls back to File.setWritable if chmod is
// somehow refused. Returns true on success.
internal fun setReadOnly(file: File, readOnly: Boolean): Boolean = runCatching {
val path = file.absolutePath
val mode = android.system.Os.stat(path).st_mode
@@ -73,10 +52,6 @@ internal fun setReadOnly(file: File, readOnly: Boolean): Boolean = runCatching {
true
}.getOrElse { file.setWritable(!readOnly, true) }
// Flip Wine's DOS hidden bit in user.DOSATTRIB, preserving the other DOS-attribute bits
// (archive/system/read-only) already encoded there, and synthesizing a minimal value when absent.
// Writes Wine's own "0x%x" format, which Wine reads back natively. Returns false when the fs can't
// store the xattr, so the caller can disable just the Hidden toggle.
internal fun setHidden(file: File, hidden: Boolean): Boolean = try {
val path = file.absolutePath
var attr = try {
@@ -13,7 +13,6 @@ import androidx.compose.ui.Modifier
import com.droiddeck.launcher.ui.DroidDeckTheme
import java.io.File
/** The File Manager as a screen of its own, from the Files tile on the main screen. */
class FileManagerActivity : ComponentActivity() {
override fun attachBaseContext(newBase: android.content.Context) {
super.attachBaseContext(newBase)
@@ -77,23 +77,16 @@ import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
// The File Manager's rows, tiles, favourites and context menu.
// Semantic identity colours for the favourite-card drive badge. Intentionally NOT theme
// accent colours - they identify the storage source at a glance. Returns (background, foreground).
private fun badgeColors(loc: FavLocation): Pair<Color, Color> {
val white = Color(0xFFFFFFFF)
return when {
loc.storage == FavStorage.INTERNAL -> Color(0xFF2E5FB0) to white // blue
loc.storage == FavStorage.SD -> Color(0xFF2E7D32) to white // green
else -> Color(0xFF555555) to white // grey
loc.storage == FavStorage.INTERNAL -> Color(0xFF2E5FB0) to white
loc.storage == FavStorage.SD -> Color(0xFF2E7D32) to white
else -> Color(0xFF555555) to white
}
}
// The context-menu item list shared by the list rows (FileItemRow) and the grid tiles
// (FileGridTile), so both open the identical menu. Gating (isDir/canRun/isInno/looksLikeArchive) is
// recomputed from [file] here - one source of truth for what each item shows. Every item dismisses
// the menu first, then runs its action.
@Composable
private fun FileContextMenuItems(
file: File,
@@ -114,15 +107,12 @@ private fun FileContextMenuItems(
onClick = { onDismissMenu(); onSelect() },
)
MenuItemDivider()
// Properties: basic info + Read-only / Hidden toggles, for ANY file or folder (handy for config
// files like .txt/.cfg/.ini). Kept near the top since it's a common reason to open this menu.
DropdownMenuItem(
text = { Text(stringResource(R.string.fm_properties)) },
leadingIcon = { Icon(Icons.Filled.Info, null, tint = MaterialTheme.colorScheme.primary) },
onClick = { onDismissMenu(); onProperties() },
)
MenuItemDivider()
// Favorites are directories - only folders get the pin toggle.
if (isDir) {
DropdownMenuItem(
text = { Text(if (isFavorite) stringResource(R.string.fm_favorite_remove) else stringResource(R.string.fm_favorite_add)) },
@@ -189,11 +179,8 @@ internal fun FileItemRow(
val context = LocalContext.current
val isDir = file.isDirectory
val isExe = !isDir && file.name.lowercase().let { it.endsWith(".exe") || it.endsWith(".bat") || it.endsWith(".msi") || it.endsWith(".sh") }
// Image files show a real thumbnail instead of the generic file icon (handy when picking a
// wallpaper/icon). Coil sizes the decode to the 36dp slot and caches it, so scrolling stays smooth.
val isImage = !isDir && file.extension.lowercase() in IMAGE_THUMB_EXTS
// For real PE executables, try to pull out the embedded application icon (async, off the main thread).
var exeIcon by remember(file.absolutePath) { mutableStateOf<ImageBitmap?>(null) }
if (!isDir && file.name.lowercase().endsWith(".exe")) {
LaunchedEffect(file.absolutePath) {
@@ -207,8 +194,6 @@ internal fun FileItemRow(
.fillMaxWidth()
.padding(horizontal = 12.dp, vertical = 3.dp)
.combinedClickable(
// In selection mode a tap toggles instead of opening, so you can rattle through a
// folder without long-pressing every single row.
onClick = { if (selectionMode) onToggleSelect() else onTap() },
onLongClick = onLongPress,
),
@@ -231,7 +216,6 @@ internal fun FileItemRow(
Spacer(Modifier.width(4.dp))
}
when {
// Show the executable's own embedded icon when we managed to extract one.
exeIcon != null -> Image(
bitmap = exeIcon!!,
contentDescription = null,
@@ -249,7 +233,6 @@ internal fun FileItemRow(
tint = MaterialTheme.colorScheme.primary,
modifier = Modifier.size(if (compact) 24.dp else 36.dp),
)
// Real image preview. Falls back to the generic file icon while loading or on decode failure.
isImage -> AsyncImage(
model = file,
contentDescription = null,
@@ -313,8 +296,6 @@ internal fun FileItemRow(
}
}
// The ".." row at the top of a folder: one level up, styled like a folder row so it reads as part
// of the list and takes controller focus the same way.
@Composable
internal fun ParentFolderRow(compact: Boolean = false, onTap: () -> Unit) {
Card(
@@ -354,8 +335,6 @@ internal fun ParentFolderRow(compact: Boolean = false, onTap: () -> Unit) {
}
}
// Dedicated Favorites list that replaces the file list while the star toggle is on.
// Reads the store keyed on [favTick] so it recomposes after any pin/unpin.
@Composable
internal fun FavoritesList(
currentDir: File,
@@ -431,9 +410,6 @@ internal fun FavoritesList(
}
}
// A single favourite - matches the FileItemRow card style (surfaceContainer + outline +
// RoundedCornerShape(10.dp)). Shows the folder name, a coloured drive badge + origin text,
// and the full display path; tapping jumps into it, the filled star unpins.
@Composable
private fun FavoriteCard(
file: File,
@@ -472,7 +448,6 @@ private fun FavoriteCard(
overflow = TextOverflow.Ellipsis,
)
Spacer(Modifier.height(2.dp))
// Origin line: coloured drive badge + source description.
Row(verticalAlignment = Alignment.CenterVertically) {
Text(
text = stringResource(loc.driveLabel),
@@ -517,13 +492,6 @@ private fun FavoriteCard(
}
}
/**
* One entry in the File Manager's grid view: a big thumbnail with the name under it.
*
* Deliberately drops size and date - at this width they truncate to noise. The grid is for
* recognising things by sight (screenshots, covers, game folders); the list stays the view for
* reading details.
*/
@OptIn(ExperimentalFoundationApi::class)
@Composable
internal fun FileGridTile(
@@ -554,7 +522,6 @@ internal fun FileGridTile(
if (bmp != null) exeIcon = bmp.asImageBitmap()
}
}
// The tile has no ⋮ button - long-press opens this menu, anchored to the Box around the Card.
Box {
Card(
modifier = Modifier
@@ -608,8 +575,6 @@ internal fun FileGridTile(
}
}
Spacer(Modifier.height(4.dp))
// Always reserve two lines (issue #475): a one-line name used to make its card shorter than
// its neighbours, so grid rows had ragged heights. Fixed min/max keeps every tile the same size.
Text(
file.name,
color = MaterialTheme.colorScheme.onSurface,
@@ -12,33 +12,8 @@ import androidx.annotation.StringRes
import com.droiddeck.launcher.R
import java.io.File
// The File Manager's non-UI helpers: sorting, paths, conflict choices and favourite locations.
/*
* Bannerlator's File Manager (ui/screens/FileManagerScreen.kt), carried over whole: the same
* browsing, grid and list, sorting, search, multi-select, copy/cut/paste with conflicts and
* progress, rename, delete, new folder, properties, favourites and the locations rail, and the
* same pick modes. What this app has no use for is not here: running a file in a Wine container,
* adding it to a container's shortcuts, the Drive C: / Drive Z: locations and the archive
* unpacker that installs into a prefix. Everything else is line for line the same so a fix in
* either app carries to the other.
*/
/**
* What to do when a pasted item already exists at the destination.
*
* OVERWRITE and MERGE resolve to the same call - `copyWithProgress` recurses into an existing
* directory and truncates existing files - but they mean different things to the user, so both are
* offered and the wording is chosen per item type (files overwrite, folders merge).
*/
enum class ConflictChoice { OVERWRITE, MERGE, KEEP_BOTH, SKIP }
/**
* Shortens a path from the LEFT, keeping whole segments.
*
* Compose's TextOverflow can only ellipsise the tail, which for a path throws away the part that
* matters - `/storage/emulated/0/Games/Racing/Dir…` tells you nothing about where you are.
*/
internal fun elidePathStart(path: String, max: Int): String {
if (path.length <= max) return path
val parts = path.split('/').filter { it.isNotEmpty() }
@@ -50,12 +25,9 @@ internal fun elidePathStart(path: String, max: Int): String {
return if (out.isEmpty()) "…" + path.takeLast(max - 1) else "…$out"
}
/** Folder-first ordering stays fixed across both sort directions. */
internal fun comparatorFor(sortBy: String, desc: Boolean): Comparator<File> {
val inner: Comparator<File> = when (sortBy) {
"date" -> compareBy { it.lastModified() }
// Directory length() is meaningless, so folders sort by name within the size ordering
// instead of pretending to have one.
"size" -> compareBy { if (it.isDirectory) -1L else it.length() }
else -> compareBy { it.name.lowercase() }
}
@@ -63,27 +35,23 @@ internal fun comparatorFor(sortBy: String, desc: Boolean): Comparator<File> {
return compareBy<File> { if (it.isDirectory) 0 else 1 }.then(directed)
}
// Image extensions that get a real thumbnail (via Coil) instead of the generic file icon.
internal val IMAGE_THUMB_EXTS = setOf("jpg", "jpeg", "png", "webp", "bmp", "gif")
// True when [child] is [ancestor] itself or lives anywhere inside it.
internal fun isWithin(child: File, ancestor: File): Boolean {
val c = runCatching { child.canonicalPath }.getOrDefault(child.absolutePath)
val a = runCatching { ancestor.canonicalPath }.getOrDefault(ancestor.absolutePath)
return c == a || c.startsWith(a + File.separator)
}
// ── Favorites: origin resolution ──
enum class FavStorage { INTERNAL, SD, OTHER }
data class FavLocation(
val storage: FavStorage,
@StringRes val driveLabel: Int, // Internal, SD card, or Storage
val displayPath: String // the unix absolute path
@StringRes val driveLabel: Int,
val displayPath: String
)
// Resolve where [file] lives (storage source + a friendly label) by prefix-matching its path.
fun describeLocation(file: File): FavLocation {
val abs = file.absolutePath
@@ -99,7 +67,6 @@ fun describeLocation(file: File): FavLocation {
}
}
// The Linux system's root (the app's files/linuxfs, the sessions' /) and anything under it.
if (Regex("/files/linuxfs(/|$)").containsMatchIn(abs)) {
return FavLocation(FavStorage.OTHER, R.string.fm_drive_linux, abs)
}
@@ -98,12 +98,7 @@ import java.util.Date
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun FileManagerScreen(
// Pick mode (issue #73): reuse this File Manager as a themed file picker. When on, editing/run
// features are gated off and tapping a matching file returns it via [onPick]. Defaults keep the
// full-featured File Manager nav destination unchanged.
pickMode: Boolean = false,
// Directory-pick mode (issue #70): only folders are listed, files are hidden, and a
// "Select this folder" action returns the current directory via [onPick]. Implies pickMode.
pickDirMode: Boolean = false,
pickExtensions: List<String> = emptyList(),
initialDir: File? = null,
@@ -113,7 +108,6 @@ fun FileManagerScreen(
val context = LocalContext.current
val scope = rememberCoroutineScope()
// Only matching files are shown in pick mode (directories are always shown). Empty = all files.
val lowerExts = remember(pickExtensions) { pickExtensions.map { it.lowercase() } }
fun matchesPickExt(file: File): Boolean {
if (lowerExts.isEmpty()) return true
@@ -124,18 +118,10 @@ fun FileManagerScreen(
val pickPrefs = remember { context.getSharedPreferences("file_manager", android.content.Context.MODE_PRIVATE) }
val browsePrefs = pickPrefs
val rootDir = remember {
// Both modes: honour an explicit caller-supplied start dir (e.g. Log Manager's game-log
// folder), else open at the INTERNAL STORAGE ROOT. Selection screens (drive-folder pick,
// local component pick, imports) previously defaulted to Download which - combined with the
// currentRoot floor below - trapped users in Download with no way up (reported bug).
initialDir?.takeIf { it.isDirectory } ?: File("/storage/emulated/0")
}
var currentDir by remember { mutableStateOf(rootDir) }
// The up/back FLOOR - back + the up-arrow are disabled while currentDir == currentRoot. It MUST be
// the VOLUME ROOT of the start dir (internal /storage/emulated/0, or an SD card /storage/XXXX-XXXX),
// NOT the start dir itself: otherwise opening at any subfolder disables up/back and traps the user
// there. (Mirrors the volume-root logic in favLocationOf above.)
var currentRoot by remember {
val abs = rootDir.absolutePath
val internal = "/storage/emulated/0"
@@ -145,8 +131,6 @@ fun FileManagerScreen(
val name = abs.removePrefix("/storage/").substringBefore('/')
if (name.isNotEmpty() && name != "emulated" && name != "self") File("/storage/$name") else rootDir
}
// A game's own folder or Proton prefix lives in the app's private storage, which has no
// volume above it: floor at the app's files dir so up/back still reach the library roots.
else -> {
val appFiles = runCatching { context.filesDir.canonicalPath }.getOrNull()
generateSequence(rootDir) { it.parentFile }
@@ -159,40 +143,26 @@ fun FileManagerScreen(
var entries by remember { mutableStateOf(listOf<File>()) }
var selectedEntry by remember { mutableStateOf<File?>(null) }
var showMenuFor by remember { mutableStateOf<File?>(null) }
// Clipboard holds a LIST so one paste can carry a whole selection. Cut/copy semantics are a
// flag on the batch rather than per item - mixing the two in one clipboard has no sane meaning.
var clipboardFiles by remember { mutableStateOf<List<File>>(emptyList()) }
var isCutOperation by remember { mutableStateOf(false) }
// Multi-select. Keyed by absolute path rather than File so a directory reload (which builds
// fresh File objects) doesn't silently drop the selection.
var selectionMode by remember { mutableStateOf(false) }
var selectedPaths by remember { mutableStateOf<Set<String>>(emptySet()) }
// Paste conflict resolution, surfaced from the IO coroutine and answered by the dialog.
var pendingConflict by remember { mutableStateOf<File?>(null) }
var conflictChoice by remember { mutableStateOf<ConflictChoice?>(null) }
var conflictApplyToAll by remember { mutableStateOf(false) }
// Set while a copy/move runs so the progress UI can offer a cancel.
var operationJob by remember { mutableStateOf<kotlinx.coroutines.Job?>(null) }
var pendingBulkDelete by remember { mutableStateOf<List<File>>(emptyList()) }
// Browse controls. Persisted so the list doesn't reset its order every time you open a folder.
var searchQuery by remember { mutableStateOf("") }
var showSearch by remember { mutableStateOf(false) }
var sortBy by remember { mutableStateOf(browsePrefs.getString("fmSortBy", "name") ?: "name") }
var sortDesc by remember { mutableStateOf(browsePrefs.getBoolean("fmSortDesc", false)) }
var showHidden by remember { mutableStateOf(browsePrefs.getBoolean("fmShowHidden", true)) }
var showSortMenu by remember { mutableStateOf(false) }
// View mode: list of cards (default) or a thumbnail grid. Density applies to the list only -
// a grid tile has no second line to compact.
// The grid/list toggle is the SOURCE OF TRUTH in BOTH orientations (it drives the view and its
// choice persists across rotation). Grid is the default - most useful in landscape, and in
// portrait GridCells.Adaptive naturally renders fewer columns (~2). Do NOT force portrait to list:
// that broke the toggle on-device (tapping it did nothing in portrait).
var gridView by remember { mutableStateOf(browsePrefs.getBoolean("fmGridView", true)) }
val showGrid = gridView
var compactRows by remember { mutableStateOf(browsePrefs.getBoolean("fmCompactRows", false)) }
var showNewFolderDialog by remember { mutableStateOf(false) }
var renameTarget by remember { mutableStateOf<File?>(null) }
// Properties sheet (basic info + Read-only / Hidden toggles) target; null when closed.
var propertiesTarget by remember { mutableStateOf<File?>(null) }
var isOperationRunning by remember { mutableStateOf(false) }
var operationLabel by remember { mutableStateOf("") }
@@ -201,24 +171,16 @@ fun FileManagerScreen(
val listState = rememberLazyListState()
val pullState = rememberPullToRefreshState()
// Favorites view: when on, a dedicated bookmarks list replaces the file list.
// favTick is bumped on any add/remove/toggle so the favorites view + per-row star recompute.
var showFavorites by remember { mutableStateOf(false) }
var favTick by remember { mutableIntStateOf(0) }
// resetScroll: jump to the top of the list (true for navigation; false for in-place reloads
// after delete/paste/rename/refresh so the user keeps their scroll position).
fun loadDirectory(dir: File, resetScroll: Boolean = true) {
currentDir = dir
// Remember the browsed directory so the next pick resumes here.
if (pickMode) pickPrefs.edit().putString("lastFilePickerDir", dir.absolutePath).apply()
scope.launch {
val list = withContext(Dispatchers.IO) {
dir.listFiles()?.toList()
// Dir-pick mode: folders only. File-pick: folders + matching files. Else: all.
?.filter { if (pickDirMode) it.isDirectory else !pickMode || it.isDirectory || matchesPickExt(it) }
// Dotfiles are noise in a storage root (.aya, .$recycle_bin$) but occasionally
// the thing you came for, so it's a toggle rather than a permanent filter.
?.filter { showHidden || !it.name.startsWith(".") }
?.sortedWith(comparatorFor(sortBy, sortDesc)) ?: emptyList()
}
@@ -227,7 +189,6 @@ fun FileManagerScreen(
}
}
// Pull-to-refresh: re-list the current directory, keeping scroll position.
if (pullState.isRefreshing) {
LaunchedEffect(true) {
loadDirectory(currentDir, resetScroll = false)
@@ -235,19 +196,13 @@ fun FileManagerScreen(
}
}
// Jump to a drive's root; pins the Back boundary so we don't climb above it.
fun openDrive(dir: File) {
currentRoot = dir
loadDirectory(dir)
}
// Open the start dir without openDrive(): that pins the floor to the start dir itself, which
// greyed out up/back whenever the manager was opened at a game's folder.
LaunchedEffect(Unit) { loadDirectory(rootDir) }
// System/gesture Back: while the Favorites view is open it closes that first; otherwise
// it goes up one directory. Only at the current drive's root with Favorites closed is it
// disabled, letting Back propagate to close the File Manager.
BackHandler(enabled = showFavorites || currentDir != currentRoot) {
if (showFavorites) {
showFavorites = false
@@ -257,15 +212,12 @@ fun FileManagerScreen(
if (parent != null && parent.exists()) loadDirectory(parent)
}
// One level up, never above the current drive's root: shared by the toolbar arrow and the
// ".." row at the top of the list.
val canGoUp = currentDir != currentRoot && currentDir.parentFile?.exists() == true
fun goUp() {
val parent = currentDir.parentFile
if (currentDir != currentRoot && parent != null && parent.exists()) loadDirectory(parent)
}
// Resolve a non-colliding destination in [dir] for [name] (foo.txt -> "foo (1).txt").
fun uniqueDestination(dir: File, name: String): File {
var candidate = File(dir, name)
if (!candidate.exists()) return candidate
@@ -291,12 +243,9 @@ fun FileManagerScreen(
}
}
/** Waits for the user to answer the conflict dialog for [file]; null if they cancelled it. */
suspend fun askConflict(file: File): ConflictChoice? {
pendingConflict = file
conflictChoice = null
// Poll rather than plumb a CompletableDeferred through Compose state - the dialog answers
// by setting conflictChoice, and this coroutine is already off the critical path.
while (pendingConflict != null && conflictChoice == null) kotlinx.coroutines.delay(50)
return conflictChoice
}
@@ -319,12 +268,10 @@ fun FileManagerScreen(
var done = 0
for (src in sources) {
// Pasting a folder into itself or its own subtree would recurse forever.
if (src.isDirectory && isWithin(dstDir, src)) {
failed++
continue
}
// Moving into the folder it already sits in is a no-op.
if (cut && src.parentFile?.absolutePath == dstDir.absolutePath) {
skipped++
continue
@@ -336,16 +283,12 @@ fun FileManagerScreen(
if (conflictApplyToAll) applyToAll = it
} ?: run { skipped++; null } ?: continue
when (choice) {
// Overwrite and Merge both paste onto the real destination: copyWithProgress
// recurses into an existing directory and truncates existing files, so the
// two differ only in what the user expects, not in what we call.
ConflictChoice.OVERWRITE, ConflictChoice.MERGE -> Unit
ConflictChoice.KEEP_BOTH -> dst = uniqueDestination(dstDir, src.name)
ConflictChoice.SKIP -> { skipped++; continue }
}
}
// Progress is per item; with a batch the label carries the overall position.
operationLabel = if (sources.size > 1) {
context.getString(if (cut) R.string.fm_op_moving_batch else R.string.fm_op_copying_batch, done + 1, sources.size, src.name)
} else {
@@ -419,8 +362,6 @@ fun FileManagerScreen(
}
var showDriveMenu by remember { mutableStateOf(false) }
// Re-enumerated whenever we come back to the screen: returning from a container can leave this
// process on a stale storage view, and the volume set has to be re-read rather than cached.
var storageTick by remember { mutableIntStateOf(0) }
val lifecycleOwner = LocalLifecycleOwner.current
DisposableEffect(lifecycleOwner) {
@@ -435,7 +376,6 @@ fun FileManagerScreen(
com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(context).takeIf { File(it, "usr").isDirectory }
}
// ── Dialogs ──
if (showNewFolderDialog) {
var folderName by remember { mutableStateOf("") }
@@ -488,8 +428,6 @@ fun FileManagerScreen(
FilePropertiesDialog(
file = file,
onDismiss = { propertiesTarget = null },
// Attribute changes affect Hidden/read-only which the listing filters/sorts on, so refresh
// in place (keeping scroll) after any toggle applies.
onChanged = { loadDirectory(currentDir, resetScroll = false) },
)
}
@@ -519,7 +457,6 @@ fun FileManagerScreen(
Column {
Text(stringResource(R.string.fm_cannot_undo))
Spacer(Modifier.height(6.dp))
// Name a few so an accidental Select-All is obvious before it's too late.
victims.take(5).forEach {
Text("• ${it.name}", color = MaterialTheme.colorScheme.onSurfaceVariant, fontSize = 12.sp)
}
@@ -557,7 +494,6 @@ fun FileManagerScreen(
)
}
// Paste conflict - one per colliding item, with "apply to all" for a long batch.
pendingConflict?.let { conflict ->
val isDir = conflict.isDirectory
OutlinedAlertDialog(
@@ -605,7 +541,6 @@ fun FileManagerScreen(
}
Column(modifier = Modifier.fillMaxSize()) {
// ── Pick-mode title ──
if (pickMode && !pickerTitle.isNullOrEmpty()) {
Text(
text = pickerTitle,
@@ -618,7 +553,6 @@ fun FileManagerScreen(
.padding(horizontal = 16.dp, vertical = 10.dp),
)
}
// ── Dir-pick action bar: confirm the currently-browsed folder ──
if (pickDirMode) {
Button(
onClick = { onPick?.invoke(currentDir) },
@@ -631,7 +565,6 @@ fun FileManagerScreen(
Text(stringResource(R.string.fm_select_this_folder))
}
}
// ── Path bar ──
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier
@@ -644,12 +577,8 @@ fun FileManagerScreen(
}
val currentDriveLabel = stringResource(describeLocation(currentDir).driveLabel)
// Dim the drive chip while the Favorites list is open (it's not the active context).
val driveChipAlpha = if (showFavorites) 0.45f else 1f
Box {
// The drive/location selector opens the drive dropdown, so give it the same outlined
// look as the "New Folder" button + the rail location items - it reads as a button, not
// plain text. Border uses the theme accent token; behaviour unchanged.
val driveChipShape = RoundedCornerShape(8.dp)
Text(
text = " $currentDriveLabel ▾",
@@ -720,13 +649,8 @@ fun FileManagerScreen(
modifier = Modifier.weight(1f),
)
} else if (LocalConfiguration.current.orientation == Configuration.ORIENTATION_PORTRAIT) {
// PORTRAIT: hide the current-folder name - it's redundant with the path bar directly
// below (which shows the full path). The spacer keeps the action icons right-aligned.
Spacer(Modifier.weight(1f))
} else {
// LANDSCAPE: the CURRENT FOLDER, not the full path. A path ellipsised on the right
// hides its tail - the only part that says where you are ("…/Games/Racing/Dir…"). The
// full path moves to the line below, where it has room.
Text(
text = currentDir.name.ifBlank { currentDir.absolutePath },
color = MaterialTheme.colorScheme.onSurface,
@@ -739,7 +663,6 @@ fun FileManagerScreen(
}
if (!showFavorites) {
// Keep New Folder in the toolbar so the file list uses the full height.
if (!pickMode) {
OutlinedButton(
onClick = { showNewFolderDialog = true },
@@ -777,8 +700,6 @@ fun FileManagerScreen(
Text(if (sortBy == key) "$label ${if (sortDesc) "↓" else "↑"}" else label)
},
onClick = {
// Tapping the active field flips direction; a different
// field switches to it ascending.
if (sortBy == key) sortDesc = !sortDesc else { sortBy = key; sortDesc = false }
browsePrefs.edit().putString("fmSortBy", sortBy)
.putBoolean("fmSortDesc", sortDesc).apply()
@@ -809,7 +730,6 @@ fun FileManagerScreen(
}
}
// Star toggle: open/close the dedicated Favorites list.
IconButton(onClick = { showFavorites = !showFavorites }) {
if (showFavorites) {
Icon(Icons.Filled.Star, stringResource(R.string.fm_hide_favorites), tint = MaterialTheme.colorScheme.primary)
@@ -819,7 +739,6 @@ fun FileManagerScreen(
}
}
// ── Search field ── filters the current folder only; it is not a recursive search.
if (showSearch && !showFavorites) {
OutlinedTextField(
value = searchQuery,
@@ -830,7 +749,6 @@ fun FileManagerScreen(
)
}
// Free space on the volume being browsed - worth knowing before starting a 60 GB copy.
val freeSpace = remember(currentDir.absolutePath, entries) {
runCatching { currentDir.usableSpace }.getOrDefault(0L)
}
@@ -840,14 +758,10 @@ fun FileManagerScreen(
modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 2.dp),
) {
Text(
// Elided from the LEFT: the deepest part of a path is the informative part, so
// when it doesn't fit we drop the /storage/emulated/0 prefix, not the tail.
text = elidePathStart(currentDir.absolutePath, 52),
color = MaterialTheme.colorScheme.onSurfaceVariant,
fontSize = 12.sp,
maxLines = 1,
// fill = true: the path takes all remaining width, so the free-space figure
// is pinned to the right edge instead of sliding around with the path length.
modifier = Modifier.weight(1f),
)
if (freeSpace > 0) {
@@ -863,7 +777,6 @@ fun FileManagerScreen(
HorizontalDivider(color = MaterialTheme.colorScheme.outline)
// ── Selection bar ── replaces the paste banner while picking items.
if (selectionMode) {
Row(
verticalAlignment = Alignment.CenterVertically,
@@ -878,7 +791,6 @@ fun FileManagerScreen(
fontSize = 13.sp,
modifier = Modifier.weight(1f),
)
// Compact outlined buttons so all five fit one row alongside the count.
val selBarPadding = PaddingValues(horizontal = 10.dp, vertical = 2.dp)
OutlinedButton(
onClick = {
@@ -924,7 +836,6 @@ fun FileManagerScreen(
}
}
// ── Paste banner ──
if (clipboardFiles.isNotEmpty()) {
Row(
verticalAlignment = Alignment.CenterVertically,
@@ -948,7 +859,6 @@ fun FileManagerScreen(
}
}
// ── Progress overlay ──
if (isOperationRunning) {
Column(
modifier = Modifier
@@ -966,8 +876,6 @@ fun FileManagerScreen(
overflow = TextOverflow.Ellipsis,
modifier = Modifier.weight(1f),
)
// A multi-gigabyte copy onto a slow card is exactly when you discover you
// picked the wrong folder; without this the only way out was killing the app.
if (operationJob != null) {
TextButton(onClick = {
operationJob?.cancel()
@@ -996,10 +904,6 @@ fun FileManagerScreen(
}
}
// ── Left locations rail (mockup Option 2) + content ──
// Shared collapsible rail: landscape expanded by default, portrait collapsed icon-only. Not
// shown in pick mode (the themed picker keeps its slim layout). Built each recompose (cheap)
// so it tracks the current drive/favourites without stale click lambdas.
val fmRailState = rememberRailState("filemanager")
fun locItem(label: String, icon: androidx.compose.ui.graphics.vector.ImageVector, dir: File, shortLabel: String? = null) =
RailItem(label, icon, !showFavorites && currentRoot.absolutePath == dir.absolutePath, shortLabel = shortLabel) {
@@ -1012,15 +916,12 @@ fun FileManagerScreen(
showFavorites = false; if (d.readable) openDrive(d.dir)
})
}
// The Linux system the sessions run in: its own / (the desktop's root), once installed.
linuxRoot?.let { add(locItem(stringResource(R.string.fm_drive_linux), Icons.Filled.Terminal, it)) }
}
val quickItems = buildList {
File("/storage/emulated/0/Download").takeIf { it.isDirectory }?.let { add(locItem(stringResource(R.string.fm_rail_downloads), Icons.Filled.Download, it, stringResource(R.string.fm_rail_downloads_short))) }
// The ROMs folder chosen on the main screen: what the session shows as /root/ROMs.
SessionPrefs.romsDir(context).takeIf { it.isNotEmpty() }?.let(::File)?.takeIf { it.isDirectory }
?.let { add(locItem(stringResource(R.string.fm_rail_roms), Icons.Filled.SportsEsports, it)) }
// The app's own logs folder: private, which this file manager (the app itself) can read.
com.droiddeck.launcher.runtime.LinuxRuntime.logDir(context).takeIf { it.isDirectory }?.let { add(locItem(stringResource(R.string.fm_rail_session_logs), Icons.Filled.Description, it)) }
File("/storage/emulated/0/Pictures").takeIf { it.isDirectory }?.let { add(locItem(stringResource(R.string.fm_rail_pictures), Icons.Filled.Image, it)) }
}
@@ -1033,12 +934,10 @@ fun FileManagerScreen(
}
Row(modifier = Modifier.weight(1f).fillMaxWidth()) {
// The slim picker keeps its layout: no rail.
if (!pickMode) {
CollapsibleRail(state = fmRailState, title = stringResource(R.string.fm_rail_title), sections = locationSections, outlinedItems = true)
}
Box(modifier = Modifier.weight(1f).fillMaxSize()) {
// ── Favorites list OR file list ──
if (showFavorites) {
FavoritesList(
currentDir = currentDir,
@@ -1060,7 +959,6 @@ fun FileManagerScreen(
modifier = Modifier.fillMaxSize(),
)
} else {
// ── File list (pull down to refresh) ──
Box(
modifier = Modifier
.fillMaxSize()
@@ -1088,8 +986,6 @@ fun FileManagerScreen(
selected = file.absolutePath in selectedPaths,
onLongPress = {
if (!pickMode) {
// In selection mode a long-press toggles; otherwise it opens the
// same context menu the list rows show (the tile has no ⋮ button).
if (selectionMode) {
selectedPaths = if (file.absolutePath in selectedPaths)
selectedPaths - file.absolutePath
@@ -1168,8 +1064,6 @@ fun FileManagerScreen(
selectionMode = selectionMode,
selected = file.absolutePath in selectedPaths,
onLongPress = {
// In selection mode a long-press toggles; otherwise it opens the
// per-item context menu (matching the grid tiles).
if (!pickMode) {
if (selectionMode) {
selectedPaths = if (file.absolutePath in selectedPaths)
@@ -1223,8 +1117,6 @@ fun FileManagerScreen(
}
}
}
// material3 1.2.0's PullToRefreshContainer draws its indicator even at rest;
// only show it while the user is actively pulling or a refresh is running.
if (pullState.verticalOffset > 0.5f || pullState.isRefreshing) {
PullToRefreshContainer(
state = pullState,
@@ -1233,7 +1125,7 @@ fun FileManagerScreen(
}
}
}
} // end content Box (beside the rail)
} // end rail + content Row
}
}
}
}
@@ -10,15 +10,9 @@ 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(context: Context, bytes: Long): String {
@@ -30,7 +24,6 @@ object FileOps {
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)) {
@@ -46,20 +39,12 @@ object FileOps {
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)) {
@@ -70,7 +55,6 @@ object FileOps {
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)
@@ -96,7 +80,7 @@ object FileOps {
}
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
val chunk = 4L * 1024 * 1024
try {
FileInputStream(src).channel.use { input ->
FileOutputStream(dst).channel.use { output ->
@@ -123,7 +107,6 @@ object FileOps {
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 }
@@ -16,16 +16,6 @@ import com.droiddeck.launcher.R
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 attachBaseContext(newBase: android.content.Context) {
super.attachBaseContext(newBase)
@@ -36,7 +26,6 @@ class FilePickerActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
requestedOrientation = com.droiddeck.launcher.session.SessionPrefs.orientation(this)
// 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)
}
@@ -44,7 +33,6 @@ class FilePickerActivity : ComponentActivity() {
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 }
@@ -70,7 +58,6 @@ class FilePickerActivity : ComponentActivity() {
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()
}
@@ -39,17 +39,7 @@ import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
// The File Manager's properties dialog.
/**
* Properties sheet for a single file or folder: basic info plus the two Windows/Wine file attributes
* the in-container file manager (wfm.exe) also exposes - Read-only and Hidden. Each toggle applies
* immediately (off the main thread) and refreshes the listing via [onChanged].
*
* State is keyed on the file so it always reflects the entry it was opened for. On a filesystem that
* can't store Wine's DOSATTRIB xattr (the FUSE /storage volumes) only the Hidden toggle is disabled;
* Read-only keeps working everywhere.
*/
@Composable
internal fun FilePropertiesDialog(
file: File,
@@ -60,7 +50,6 @@ internal fun FilePropertiesDialog(
val scope = rememberCoroutineScope()
val dateFormat = remember { SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault()) }
var attrs by remember(file.absolutePath) { mutableStateOf<FileAttrState?>(null) }
// Guards against a second toggle landing while the first is still being applied off-thread.
var busy by remember(file.absolutePath) { mutableStateOf(false) }
LaunchedEffect(file.absolutePath) {
attrs = withContext(Dispatchers.IO) { readFileAttrs(file) }
@@ -71,7 +60,6 @@ internal fun FilePropertiesDialog(
title = { Text(stringResource(R.string.fm_properties)) },
text = {
Column(modifier = Modifier.verticalScroll(rememberScrollState())) {
// ── Basic info ──
Text(
text = file.name,
color = MaterialTheme.colorScheme.onBackground,
@@ -95,7 +83,6 @@ internal fun FilePropertiesDialog(
Spacer(Modifier.height(6.dp))
val state = attrs
// ── Read-only ── checked when the owner can't write (Wine's FILE_ATTRIBUTE_READONLY).
AttributeToggleRow(
label = stringResource(R.string.fm_read_only),
description = stringResource(R.string.fm_read_only_hint),
@@ -116,7 +103,6 @@ internal fun FilePropertiesDialog(
},
)
Spacer(Modifier.height(2.dp))
// ── Hidden ── Wine's DOS hidden bit in the user.DOSATTRIB xattr.
val hiddenSupported = state?.hiddenSupported == true
AttributeToggleRow(
label = stringResource(R.string.fm_hidden),
@@ -134,7 +120,6 @@ internal fun FilePropertiesDialog(
attrs = attrs?.copy(hidden = want)
onChanged()
} else {
// The write failed after all - disable the toggle rather than lie.
attrs = attrs?.copy(hiddenSupported = false)
Toast.makeText(context, R.string.fm_hidden_failed, Toast.LENGTH_SHORT).show()
}
@@ -147,7 +132,6 @@ internal fun FilePropertiesDialog(
)
}
// One "label: value" line in the Properties info block.
@Composable
private fun PropertyLine(label: String, value: String) {
Row(modifier = Modifier.fillMaxWidth().padding(vertical = 2.dp)) {
@@ -168,7 +152,6 @@ private fun PropertyLine(label: String, value: String) {
}
}
// A labelled attribute switch with a one-line description, used by the Properties sheet.
@Composable
private fun AttributeToggleRow(
label: String,
@@ -5,14 +5,7 @@ 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(),
@@ -24,7 +17,6 @@ object InAppFilePicker {
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,
@@ -39,6 +31,5 @@ object InAppFilePicker {
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) }
}
@@ -10,9 +10,6 @@ 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
@@ -23,7 +20,6 @@ internal fun Modifier.outlinedMenuCard(): Modifier {
.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))
@@ -12,12 +12,6 @@ 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,
@@ -6,21 +6,11 @@ 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_RES_SECTION = 64 * 1024 * 1024
private const val MAX_ICON_DIM = 1024
fun extract(file: File): Bitmap? = try {
@@ -31,11 +21,11 @@ object PeIconExtractor {
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"
if (u8(dos, 0) != 0x4D || u8(dos, 1) != 0x5A) return null
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"
if (u8(coff, 0) != 0x50 || u8(coff, 1) != 0x45 || u8(coff, 2) != 0 || u8(coff, 3) != 0) return null
val numSections = u16(coff, 6)
val sizeOpt = u16(coff, 20)
if (numSections <= 0 || numSections > 96 || sizeOpt <= 0) return null
@@ -43,8 +33,8 @@ object PeIconExtractor {
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
val ddOff = if (magic == 0x20B) 112 else 96
val resDirEntry = ddOff + 2 * 8
if (resDirEntry + 8 > opt.size) return null
val resRVA = u32(opt, resDirEntry).toInt()
val resSize = u32(opt, resDirEntry + 4).toInt()
@@ -75,7 +65,6 @@ object PeIconExtractor {
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
@@ -97,7 +86,6 @@ object PeIconExtractor {
}
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
@@ -106,9 +94,7 @@ object PeIconExtractor {
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)
@@ -126,7 +112,6 @@ object PeIconExtractor {
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
@@ -140,7 +125,6 @@ object PeIconExtractor {
}
}
/** 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()
@@ -150,7 +134,6 @@ object PeIconExtractor {
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) {
@@ -164,7 +147,7 @@ object PeIconExtractor {
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 height = heightFull / 2
val bitCount = u16(b, 14)
if (width <= 0 || height <= 0 || width > MAX_ICON_DIM || height > MAX_ICON_DIM) return null
@@ -183,7 +166,6 @@ object PeIconExtractor {
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
@@ -245,7 +227,6 @@ object PeIconExtractor {
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
@@ -253,7 +234,6 @@ object PeIconExtractor {
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)
@@ -8,52 +8,24 @@ import android.os.storage.StorageVolume
import com.droiddeck.launcher.R
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>()
}
@@ -62,7 +34,6 @@ object StorageRoots {
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 = context.getString(R.string.fm_drive_internal)
removable = false
@@ -72,7 +43,6 @@ object StorageRoots {
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 ->
@@ -86,14 +56,11 @@ object StorageRoots {
}
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
@@ -102,7 +69,6 @@ object StorageRoots {
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)
@@ -117,11 +83,9 @@ object StorageRoots {
}
private fun Volume.toRoot(context: Context): 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")
@@ -135,7 +99,6 @@ object StorageRoots {
private fun Volume.defaultLabel(context: Context): String = if (removable) context.getString(R.string.fm_drive_sd) 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 ->
@@ -143,7 +106,6 @@ object StorageRoots {
}
}
/** 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
@@ -154,7 +116,6 @@ object StorageRoots {
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) }
@@ -178,11 +139,6 @@ object StorageRoots {
}
}
/**
* 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 context.getString(R.string.fm_drive_internal)
if (volume.isRemovable) return context.getString(R.string.fm_drive_sd)
@@ -5,15 +5,7 @@ import org.json.JSONArray
import org.json.JSONObject
import java.io.File
/**
* Games added from the Games tab's + rather than a Games folder: one picked .exe, or each game
* "Add all games in this folder" found. Kept by the game's folder in `files/added-exes.json`,
* which [AddedGames.scan] merges in. The exe chosen later, the shortcut appid, the edits and the
* removal live where every added game keeps them ([com.droiddeck.launcher.session.SessionPrefs]);
* this holds which folders are games and the exe they came with.
*/
object AddedExes {
/** [picked]: the user chose [exe]; false = [GameExePicker]'s best guess, which a scan ranks again. */
class Entry(val folder: String, val exe: String, val picked: Boolean = true)
private fun file(context: Context) = File(context.filesDir, "added-exes.json")
@@ -30,7 +22,6 @@ object AddedExes {
emptyList()
}
/** Adds [entry], replacing one for the same folder. */
@Synchronized
fun put(context: Context, entry: Entry) = write(context, list(context).filter { it.folder != entry.folder } + entry)
@@ -11,14 +11,6 @@ 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 has
* for it - by the Steam appid its files name, else by a store search on its title - else what
* SteamGridDB has ([SteamGridDb]), 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="
@@ -29,15 +21,10 @@ object AddedGameArt {
val any get() = portrait != null || header != null || hero != null || logo != null
}
/**
* The pieces a user can choose, as the client takes them: [assetType] is its custom-artwork
* number (null: the icon, set by path); [cacheName] the automatic file in the game's cache.
*/
enum class Slot(val key: String, val cacheName: String, val assetType: Int?) {
COVER("p", "p.jpg", 0), BACKGROUND("hero", "hero.jpg", 1), LOGO("logo", "logo.png", 2), ICON("icon", "icon.png", null),
}
/** Where a piece came from; [AUTO] = nothing found yet. */
const val FOLDER = "folder"
const val STEAM = "steam"
const val SGDB = "sgdb"
@@ -45,10 +32,8 @@ object AddedGameArt {
const val EXE = "exe"
const val AUTO = ""
/** A slot as it stands: the file shown and where it came from (one of [FOLDER].. [AUTO]); [chosen] = the user picked it. */
class SlotState(val slot: Slot, val file: File?, val source: String, val chosen: Boolean)
/** One image the chooser offers: its group ([FOLDER], [STEAM], [SGDB]), a thumbnail and the full image (URL or path). */
class Option(val group: String, val thumb: String, val full: String)
private val CHOSEN = Regex("""chosen-(\w+)\.(\w+)""")
@@ -64,7 +49,6 @@ object AddedGameArt {
internal 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) {
@@ -74,7 +58,6 @@ object AddedGameArt {
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(
@@ -86,7 +69,6 @@ object AddedGameArt {
)
}
/** The user's choice for each piece, else the folder's art, else the cached art; no network. */
fun resolve(context: Context, game: AddedGames.Game): Art {
val own = local(game)
val cache = cacheDir(context, game)
@@ -100,7 +82,6 @@ object AddedGameArt {
)
}
/** Each choosable piece with its file and where it came from, for the game's editor; no network. */
fun describe(context: Context, game: AddedGames.Game): List<SlotState> {
val own = local(game)
val cache = cacheDir(context, game)
@@ -122,17 +103,11 @@ object AddedGameArt {
private val CHOOSABLE = setOf("png", "jpg", "jpeg", "webp")
/** Images in the game's folder (and its art folders) that could stand for a piece. */
internal fun folderImages(folder: File): List<File> =
listOf(folder, File(folder, "art"), File(folder, ".art")).flatMap { dir ->
dir.listFiles { f -> f.isFile && f.extension.lowercase() in CHOOSABLE }?.sortedBy { it.name.lowercase() }.orEmpty()
}.take(12)
/**
* What the chooser offers for [slot]: the game folder's images, Steam's official piece (when the
* game has a Steam appid and Steam has the piece), and SteamGridDB's best few (with a key).
* Blocking: it asks the network.
*/
fun options(context: Context, game: AddedGames.Game, slot: Slot): List<Option> {
val out = ArrayList<Option>()
folderImages(game.folder).forEach { out.add(Option(FOLDER, it.path, it.path)) }
@@ -155,7 +130,6 @@ object AddedGameArt {
return out
}
/** Sets [slot] to [option] (a file is copied, a URL fetched) and records where it came from. False when it could not be had. Blocking. */
fun choose(context: Context, game: AddedGames.Game, slot: Slot, option: Option): Boolean {
val bytes = if (option.full.startsWith("https://")) get(option.full) else runCatching { File(option.full).readBytes() }.getOrNull()
bytes ?: return false
@@ -170,13 +144,11 @@ object AddedGameArt {
return true
}
/** Where the user's choice for [slot] came from and which image it was ("" both when automatic). */
fun chosenSource(context: Context, game: AddedGames.Game, slot: Slot): Pair<String, String> {
val value = SessionPrefs.addedGameArtSource(context, game.folder.path, slot.key)
return value.substringBefore('|') to value.substringAfter('|', "")
}
/** [slot] back to what is found by itself. */
fun reset(context: Context, game: AddedGames.Game, slot: Slot) {
chosen(cacheDir(context, game), slot)?.delete()
SessionPrefs.setAddedGameArtSource(context, game.folder.path, slot.key, "")
@@ -191,7 +163,6 @@ object AddedGameArt {
try { c.responseCode == 200 } finally { c.disconnect() }
}.getOrDefault(false)
/** 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")
@@ -206,12 +177,6 @@ object AddedGameArt {
return if (tmp.renameTo(png)) png else null
}
/**
* Fetches the art that is missing: Steam first (the appid the game's files name, else a store
* search on its title whose result carries the same name), then SteamGridDB when a key is
* set. Each lookup runs 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
val sgdbKey = SteamGridDb.key(context)
@@ -236,17 +201,12 @@ object AddedGameArt {
return changed
}
/**
* The game's Steam app, the one record its Windows components use too ([SteamMatch]): what its
* files name, else a store search on its title ([search]) whose result has the same name.
*/
internal fun steamMatch(context: Context, game: AddedGames.Game, search: (String) -> Int?): SteamMatch.Match {
val match = SteamMatch.resolve(context, game.folder.path, game.exe, game.name, legacy = File(cacheDir(context, game), "steam-appid"), search = search)
match.appId?.let { Log.i(TAG, "${game.name}: Steam app $it (${match.certainty.name.lowercase()})") }
return match
}
/** What [marker] remembers (an id, or "none" for a week), else [find]'s answer written to it. */
private fun remembered(marker: File, find: () -> String?): String? {
if (marker.isFile) {
val value = marker.readText().trim()
@@ -262,11 +222,6 @@ object AddedGameArt {
private val EDITION = Regex("(?i)\\b(complete|definitive|legendary|goty|game of the year|deluxe|ultimate|remastered)( edition)?\\b")
/**
* How well a result's name [got] matches the game's [name]: 3 the same, 2 the same once
* edition words are dropped, 1 one starts with the other; 0 no match. Nothing is taken for
* being the first result.
*/
internal fun nameMatch(name: String, got: String): Int {
val want = normalize(name)
val wantShort = normalize(name.replace(EDITION, " ").trim().ifEmpty { name })
@@ -280,13 +235,11 @@ object AddedGameArt {
}
}
/** The id of the store result whose name matches [name] best, or null when none does. */
internal fun pickStoreResult(name: String, items: List<Pair<String, String>>): String? =
items.map { (id, got) -> id to nameMatch(name, got) }
.filter { it.second > 0 && it.first.isNotEmpty() }
.maxByOrNull { it.second }?.first
/** The Steam appid whose store name matches [name], or null for no match. */
private fun search(name: String): String? {
val term = name.replace(EDITION, " ").trim().ifEmpty { name }
val json = get(STORE_SEARCH + URLEncoder.encode(term, "UTF-8"))?.toString(Charsets.UTF_8) ?: return null
@@ -309,10 +262,6 @@ object AddedGameArt {
return got
}
/**
* Newer Steam games keep their art under hashed paths (store_item_assets/steam/apps/<id>/<hash>/…),
* where the fixed CDN names above 404. The store's item API names those paths; once per appid.
*/
private fun steamAssetUrl(id: String, remote: String): String? {
val assets = steamAssets.getOrPut(id) {
runCatching {
@@ -336,11 +285,6 @@ object AddedGameArt {
private val steamAssets = java.util.concurrent.ConcurrentHashMap<String, Map<String, String>>()
/**
* When nothing else gave a cover (or header), one made from the exe's icon: the icon centred on
* its own colour, darkened toward the bottom, so the game still has a face in the list and in
* Steam. Made once per game; real art found later takes over because it is looked at first.
*/
private fun exeArt(context: Context, game: AddedGames.Game, cover: Boolean): File? {
val cache = cacheDir(context, game)
val out = File(cache, if (cover) "p-exe.png" else "header-exe.png")
@@ -5,27 +5,16 @@ import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.stores.SteamLiveShortcuts
import java.io.File
/**
* The game editor's writes for an added game, Steam's non-Steam Properties in the app: name,
* target, Start in, launch options and art. Each goes through the same shortcut - the listing the
* shortcuts writer reads, and the running client - on the appid the game already has, so an edit
* never makes a second shortcut. Each call is quick (the game alone, [AddedGames.single]); the
* client and the listing follow on [AddedGamesPublisher], in order. Call off the main thread.
*/
object AddedGameEdits {
/** The added game in [folder] as it stands now, or null when it is not listed. */
fun game(context: Context, folder: String): AddedGames.Game? = AddedGames.single(context, folder)
/** The client told ([live]), then the listing rewritten, on [AddedGamesPublisher]. */
private fun publish(context: Context, live: () -> Unit) = AddedGamesPublisher.later(context, live)
/** [name] as the game's name; "" goes back to the name found by itself. */
fun setName(context: Context, folder: String, name: String): AddedGames.Game? {
SessionPrefs.setAddedGameName(context, folder, name)
return apply(context, folder)
}
/** [exe] as the game's target; false when the session cannot see it. */
fun setExe(context: Context, folder: String, exe: File): Boolean {
if (!exe.isFile || AddedGames.guestPath(context, exe) == null) return false
SessionPrefs.setAddedGameExe(context, folder, exe.path)
@@ -33,7 +22,6 @@ object AddedGameEdits {
return true
}
/** [dir] (a host folder) as the game's Start in; "" = the exe's own folder. False when the session cannot see it. */
fun setStartIn(context: Context, folder: String, dir: String): Boolean {
val guest = if (dir.isBlank()) "" else AddedGames.guestPath(context, File(dir.trim())) ?: return false
SessionPrefs.setAddedGameStartIn(context, folder, guest)
@@ -46,7 +34,6 @@ object AddedGameEdits {
return apply(context, folder)
}
/** [slot] set to [option], then handed to the shortcut. False when the image could not be had. */
fun setArt(context: Context, folder: String, slot: AddedGameArt.Slot, option: AddedGameArt.Option): Boolean {
val game = game(context, folder) ?: return false
if (!AddedGameArt.choose(context, game, slot, option)) return false
@@ -54,7 +41,6 @@ object AddedGameEdits {
return true
}
/** [slot] back to automatic, then handed to the shortcut. */
fun resetArt(context: Context, folder: String, slot: AddedGameArt.Slot) {
val game = game(context, folder) ?: return
AddedGameArt.reset(context, game, slot)
@@ -11,7 +11,6 @@ import com.droiddeck.launcher.stores.StoreInstallRoot
import java.io.File
import java.util.zip.CRC32
/** Windows game folders shared with the Steam session. */
object AddedGames {
private const val TAG = "AddedGames"
private const val LIBRARY = "/mnt/droiddeck-sd"
@@ -19,38 +18,23 @@ object AddedGames {
class Game(
val folder: File, val name: String,
/** The game's own .exe: what the icon is read from and what the settings page lists. */
val exe: File,
/** The guest path the shortcut runs: [exe], or a store install's launcher .bat in front of it. */
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>,
val steamAppId: Int? = null,
/** Where the game came from: a store's id, or [Library.ADDED] for a folder the user added. */
val source: String = Library.ADDED,
/** The store's own id for the game, from its sidecar; null for a plain added folder. */
val storeId: String? = null,
/** The exe is the picker's guess and nothing clearly won ([GameExePicker.Ranking.uncertain]). */
val exeUncertain: Boolean = false,
/** Steam's launch options for the shortcut; "" for none. */
val launchOptions: String = "",
/** Added from the Games tab (an entry of its own), not found in a Games folder. */
val single: Boolean = false,
) {
fun folderName(): String = folder.name
}
/** A Games folder an earlier build had, and where the session sees it. */
class Root(val host: File, val guest: String)
/**
* The Games folders earlier builds had, bound into the session at the guest paths they had
* then (/root/Games/<name>), so the games in them (entries now, [GamesFolderMigration]) keep
* their paths and shortcuts. Nothing adds one any more.
*/
fun roots(context: Context): List<Root> {
GamesFolderMigration.run(context)
return SessionPrefs.gameFolderBinds(context).map { (host, guest) -> Root(File(host), guest) }
@@ -61,14 +45,10 @@ object AddedGames {
"|.*installer.*|.*uninstall.*|.*updater?.*|.*config(ur.*)?|.*settings.*|.*editor.*|.*server.*|.*benchmark.*|.*helper.*|.*eac.*|.*easyanticheat.*|.*battleye.*)\\.exe$",
)
/** Under here the chosen Games folders are bound inside the session, one each. */
const val GUEST_DIR = "/root/Games"
/** Where a host path appears inside the session, or null when the session cannot see it. */
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
@@ -77,26 +57,19 @@ object AddedGames {
SessionPrefs.romsDir(context).takeIf { it.isNotEmpty() }?.let { roms ->
if (path.startsWith("$roms/")) return "/root/ROMs/" + path.removePrefix("$roms/")
}
// A store root on a card has a bind of its own, before the library rule: the same folder
// keeps the same guest path (and appid) whether or not that card is also the Steam library.
StoreInstallRoot.externalGuestPath(context, host)?.let { return it }
GameStorage.effective(context)?.let { lib ->
if (path.startsWith("${lib.path}/")) return "$LIBRARY/" + path.removePrefix("${lib.path}/")
}
// Inside the runtime's own tree (store installs on internal storage live at
// root/Games/Stores): the tree is the session's / and needs no bind.
val runtime = LinuxRuntime.rootDir(context).absolutePath
if (path.startsWith("$runtime/")) return "/" + path.removePrefix("$runtime/")
// Internal storage, bound at /root/Storage in every session: an exe picked anywhere on it.
val storage = android.os.Environment.getExternalStorageDirectory().absolutePath
if (path.startsWith("$storage/")) return "/root/Storage/" + path.removePrefix("$storage/")
return null
}
/** The .exe files a game folder offers, best first ([GameExePicker]); declared Store exes lead. */
fun candidates(folder: File): List<File> = rank(folder).exes
/** [GameExePicker]'s ranking, with a Store-declared executable taking precedence when present. */
fun rank(folder: File): GameExePicker.Ranking {
val key = "${folder.path}|${folder.lastModified()}"
val now = System.currentTimeMillis()
@@ -115,20 +88,11 @@ object AddedGames {
return result
}
/** A folder's ranking for a minute, so one add (rank, then the game built from it) walks it once. */
private val ranked = java.util.concurrent.ConcurrentHashMap<String, Pair<Long, GameExePicker.Ranking>>()
private const val RANK_FRESH_MS = 60_000L
/**
* Names identified from an exe (Steam manifest, GOG info, version resource), by the exe's path,
* size and time and its game folder's time (a GOG info file dropped in changes the latter).
*/
private val identified = java.util.concurrent.ConcurrentHashMap<String, String>()
/**
* The game's own title for [exe] when the disk names one ([GameIdentifier]: a Steam manifest,
* a GOG info file, the exe's version resource), else null (the folder name stands).
*/
internal fun identifiedName(folder: File, exe: File): String? {
val key = "${exe.path}|${exe.length()}|${exe.lastModified()}|${folder.lastModified()}"
identified[key]?.let { return it.ifEmpty { null } }
@@ -141,13 +105,6 @@ object AddedGames {
return name
}
/**
* The exe's version resource often spells the title the way a programmer typed it ("Insane2")
* while the folder has the real spacing ("Insane 2"). When both spell the same letters and
* digits, the one with more word breaks wins; a tie keeps mixed case over all one case
* ("DiRT 3" over "dirt 3"), else the exe's spelling. Different titles keep the exe's.
*/
/** "Watch_Dogs" → "Watch Dogs": an underscore in a version-resource title is a programmer's space. */
internal fun underscoresToSpaces(name: String): String =
name.replace('_', ' ').replace(Regex("\\s+"), " ").trim().ifEmpty { name }
@@ -163,7 +120,6 @@ object AddedGames {
else -> peName
}
}
/** The executables MicrosoftGame.config or appxmanifest.xml declares that exist inside [folder]. */
internal fun declaredExes(folder: File): List<File> {
val names = DECLARED.flatMap { (file, pattern) ->
runCatching { pattern.findAll(File(folder, file).readText()).map { it.groupValues[1] }.toList() }.getOrDefault(emptyList())
@@ -195,30 +151,20 @@ object AddedGames {
val steamInstalls = steamInstallDirs(dir)
for (folder in dir.listFiles { f -> f.isDirectory }?.sortedBy { it.name.lowercase() } ?: emptyList()) {
if (folder.name.lowercase() in steamInstalls || folder.name.equals("steamapps", ignoreCase = true)) continue
// Removed from the list by the user (the folder stays on disk); restored from the settings page.
if (folder.path in removed) continue
// The store install root sits inside the Games storage; its games are scanned below, per store.
if (folder.name == "Games" && StoreInstallRoot.roots(context).any { it.absolutePath == folder.absolutePath }) continue
scanGame(context, folder, out)
}
}
// Games added as one picked exe (the Games tab's +), by that exe's folder.
for (entry in AddedExes.list(context)) {
val folder = File(entry.folder)
if (folder.path in removed || !folder.isDirectory) continue
scanGame(context, folder, out, single = entry)
}
// Games the Stores section installed: one folder each under <root>/<Store>/, with a sidecar.
// An unfinished one (sidecar still `installing`, or none at all) is neither a game nor Custom.
for (folder in StoreInstallRoot.gameFolders(context)) if (StoreInstallRoot.isFinished(folder)) scanGame(context, folder, out)
return out.distinctBy { it.folder.canonicalPath }
}
/**
* The game in [folderPath] alone, built by the same rules as [scan] (store sidecar, an entry
* from the Games tab, the chosen exe, the edits) without walking every other game: what the
* editor needs for one game. Null when that folder is not a game, or was removed.
*/
fun single(context: Context, folderPath: String): Game? {
val folder = File(folderPath)
if (!folder.isDirectory || folderPath in SessionPrefs.removedAddedGames(context)) return null
@@ -227,12 +173,6 @@ object AddedGames {
return out.firstOrNull()
}
/**
* Stops listing the added game in [folder] at once: marked removed and dropped from the
* library cache; the running client loses its shortcut ([appId], else the one stored for the
* folder) and the listing is rewritten afterwards ([AddedGamesPublisher]). Nothing on disk is
* deleted. Quick; call off the main thread (preferences and a small file).
*/
fun remove(context: Context, folder: File, appId: Long? = null, name: String = folder.name) {
val app = context.applicationContext
val started = android.os.SystemClock.elapsedRealtime()
@@ -243,13 +183,10 @@ object AddedGames {
AddedGamesPublisher.later(app) { if (id != null) com.droiddeck.launcher.stores.SteamLiveShortcuts.remove(app, id) }
}
/** What [addExe] did with a picked exe. */
sealed class AddResult {
/** A new game, or the existing one the exe already is, or the listed game whose exe it now is. */
class Added(val game: Game) : AddResult()
class Existing(val game: Game) : AddResult()
class Switched(val game: Game) : AddResult()
/** The session cannot see the exe's path. */
object Unreachable : AddResult()
object NotFound : AddResult()
}
@@ -258,11 +195,6 @@ object AddedGames {
private fun inside(path: String, folder: String) = path.startsWith(folder.trimEnd('/') + "/")
/**
* The game folder [exe] belongs to, without a scan: an entry from the Games tab (Games folders
* of earlier builds included), a removed game, a store install, or the first-level folder under
* the Steam library that holds it. Null when it is in none.
*/
private fun ownerFolder(context: Context, exe: File): File? {
GamesFolderMigration.run(context)
val path = canonical(exe)
@@ -270,7 +202,6 @@ object AddedGames {
AddedExes.list(context).map { File(it.folder) }.firstOrNull(::holds)?.let { return it }
SessionPrefs.removedAddedGames(context).map { File(it) }.firstOrNull(::holds)?.let { return it }
StoreInstallRoot.gameFolders(context).firstOrNull(::holds)?.let { return it }
// Games folders of earlier builds are entries now, found above.
val dirs = listOfNotNull(
GameStorage.effective(context)?.let { File(it.path, "steamapps/common") },
GameStorage.effective(context)?.let { File(it.path) },
@@ -284,12 +215,6 @@ object AddedGames {
return null
}
/**
* Adds the game [exe] is: the game itself when it is listed already, that game's exe switched
* when [exe] sits in a listed (or removed) game's folder, else a new game for [exe]'s folder.
* Only that one game is read; Steam (the running client, then the listing) follows on
* [AddedGamesPublisher]. Nothing is added when the session cannot see the path.
*/
fun addExe(context: Context, exe: File): AddResult {
val app = context.applicationContext
if (!exe.isFile) return AddResult.NotFound
@@ -309,15 +234,8 @@ object AddedGames {
return if (owner == null) AddResult.Added(game) else AddResult.Switched(game)
}
/** What [addFolder] did: the games it added, and how many of the folder's games were listed already. */
class FolderResult(val added: List<Game>, val already: Int)
/**
* "Add all games in this folder": every subfolder of [dir] with an .exe becomes a game with
* [GameExePicker]'s best one (marked uncertain where nothing clearly won), as an entry of its
* own, not a Games folder. A subfolder that is, holds or sits in a listed game counts as
* already there; a removed one comes back. Steam follows once, on [AddedGamesPublisher]. Blocking.
*/
fun addFolder(context: Context, dir: File, onGame: (Game) -> Unit = {}, onChecking: (String?) -> Unit = {}): FolderResult {
val app = context.applicationContext
val removed = SessionPrefs.removedAddedGames(app).toSet()
@@ -343,11 +261,6 @@ object AddedGames {
return FolderResult(added, already)
}
/**
* The game folders already listed, without building any game: the first-level folders of the
* Steam library (as [scan] walks them), the Games tab's entries (Games folders of earlier builds
* included) and the store installs. Canonical paths; removed games are left out.
*/
private fun listedFolders(context: Context, removed: Set<String>): List<String> {
val out = ArrayList<String>()
GamesFolderMigration.run(context)
@@ -367,11 +280,6 @@ object AddedGames {
return out
}
/**
* The folders under a library's steamapps/common that a manifest beside it already claims.
* Steam lists those itself, so a shortcut would only add a non-Steam copy of the game. Steam
* may lowercase installdir on Android's case-insensitive storage, so names compare lowercased.
*/
internal fun steamInstallDirs(dir: File): Set<String> {
val steamapps = dir.parentFile?.takeIf { dir.name == "common" && it.name == "steamapps" } ?: return emptySet()
return steamapps.listFiles { f -> f.isFile && f.name.startsWith("appmanifest_") && f.name.endsWith(".acf") }
@@ -385,33 +293,24 @@ object AddedGames {
private val INSTALL_DIR = Regex("\"installdir\"\\s*\"([^\"]*)\"", RegexOption.IGNORE_CASE)
/** [single]: the entry a game added from the Games tab has; its exe stands in when no other is chosen and the user picked it. */
private fun scanGame(context: Context, folder: File, out: MutableList<Game>, single: AddedExes.Entry? = null) {
run {
// A store install carries a sidecar; every one of them is a shortcut.
val sidecar = StoreGameSidecar.read(folder)
val ranking = rank(folder)
val candidates = ranking.exes
val picked = SessionPrefs.addedGameExe(context, folder.path)
val chosen = picked.takeIf { it.isNotEmpty() }?.let { File(it) }?.takeIf { it.isFile }
?: single?.takeIf { it.picked }?.let { File(it.exe) }?.takeIf { it.isFile }
// A store install says which exe it is; the folder's guess only when that file is gone.
val found = chosen ?: sidecar?.exeFile(folder)?.takeIf { it.isFile } ?: candidates.firstOrNull() ?: return
// The store's launcher .bat stands in front of the exe when the game needs arguments or
// environment; it is what the shortcut runs. Dropped when the user picked another exe.
val launch = if (chosen == null) sidecar?.launcherFile(folder)?.takeIf { it.isFile } ?: found else found
val foundGuest = guestPath(context, launch)
if (foundGuest == null) { Log.w(TAG, "${folder.name}: the session cannot see ${launch.path}"); return }
// A store install's title; else the title the disk gives (the shortcut's appid is kept
// per folder from its first scan, so a name found later does not move it); else the folder.
val autoName = sidecar?.title ?: identifiedName(folder, found) ?: folder.name
// Keyed by the pre-rename path so shortcut ids, and the prefixes and saves under them, stay put.
val crc = CRC32().apply { update(("\"${foundGuest.replaceFirst(Regex("^$LIBRARY/"), "$LEGACY_LIBRARY/")}\"" + autoName).toByteArray()) }.value
val appId = SessionPrefs.addedGameAppId(context, folder.path, crc or 0x80000000L)
val config = accountConfig(File(LinuxRuntime.rootDir(context), "root/.local/share/Steam"))
val record = config?.let { shortcutRecord(it, appId) }
val rev = record?.optInt("rev", 0) ?: 0
// Name, Start in and launch options edited in Steam's own Properties become the app's.
if (sidecar == null && record != null) adoptSteamEdits(context, folder, record)
val name = SessionPrefs.addedGameName(context, folder.path).takeIf { sidecar == null && it.isNotEmpty() } ?: autoName
val adopted = guestPath(context, folder)
@@ -460,12 +359,6 @@ object AddedGames {
private fun unquote(value: String?): String = value.orEmpty().trim().trim('"')
/**
* What the user changed in Steam's Properties since the app last wrote the shortcut ([record]:
* what the app asked for, and what Steam had): a new name, launch options, or a Start in other
* than the exe's folder, taken over as the app's own. Each Steam value is taken once, so an app
* edit made after it is not undone before the shortcut is written again.
*/
internal fun adoptSteamEdits(context: Context, folder: File, record: JSONObject) {
val app = record.optJSONObject("app") ?: return
val steam = record.optJSONObject("steam") ?: return
@@ -489,7 +382,6 @@ object AddedGames {
}
}
/** 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("[")
@@ -500,8 +392,6 @@ object AddedGames {
.append(",\"dir\":").append(quote(g.guestDir)).append(",\"appid\":").append(g.appId)
.append(",\"seen\":").append(SessionPrefs.addedGameExeSeen(context, g.folder.path))
if (g.launchOptions.isNotEmpty()) json.append(",\"launch\":").append(quote(g.launchOptions))
// 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 } } }
@@ -5,23 +5,15 @@ import android.util.Log
import androidx.annotation.VisibleForTesting
import java.util.concurrent.Executors
/**
* The slow part of an added-game change, off the caller's path and in order: the running client
* told ([later]'s work), then the listing the shortcuts writer reads at the next session start and
* the library cache, both from one scan ([republish]). An add, an edit or a removal shows at once;
* this follows.
*/
object AddedGamesPublisher {
private const val TAG = "AddedGamesPublisher"
/** Tests publish at once, to read the listing right after a change. */
@VisibleForTesting
@Volatile
internal var now = false
private val worker = Executors.newSingleThreadExecutor { r -> Thread(r, "added-games-publish") }
/** [live] (a DevTools call or nothing), then [republish], on the worker. */
fun later(context: Context, live: () -> Unit = {}) {
val app = context.applicationContext
val work = Runnable {
@@ -31,7 +23,6 @@ object AddedGamesPublisher {
if (now) work.run() else worker.execute(work)
}
/** The listing and the library cache from one scan of the added games. Blocking. */
fun republish(context: Context) {
val games = AddedGames.scan(context)
AddedGames.writeListing(context, games)
@@ -16,29 +16,12 @@ import org.json.JSONObject
import java.io.File
import java.util.concurrent.PriorityBlockingQueue
/**
* Turns on, per game, the Windows components its source's list names ([WinCompSources]). Only the
* findings marked auto are turned on, only the ones that install here, and never one the user
* switched off: the user's switches are kept apart ([WinComponents.Selection.user]) and win.
*
* All the work is done by one background thread (low priority, so are the runtime helpers it
* starts), one job at a time from one queue: working out a game's list (kept, so a page opens on
* it) and downloading a component (each once, whichever games want it). The queue waits while a
* session runs; jobs nobody asked for (the start-up sweep, a game being launched) also wait on
* battery saver, a warm device or a metered network. Nothing here runs on the caller's thread.
*/
object AutoComponents {
private const val TAG = "AutoComponents"
/** The key a game's picks are kept under: the appid its prefix is named after. */
fun appKey(game: Library.SteamGame): String? =
if (game.library == Library.ADDED) Integer.toUnsignedString(game.appId) else game.appId.takeIf { it > 0 }?.toString()
/**
* What turns on by itself for [findings], given [catalog] and what is [installed]: the catalog
* name each auto finding installs as, with its reason. A component that needs a Windows
* installer, or is not in the catalog, stays out (the editor lists it as a suggestion).
*/
fun autoPicks(findings: List<WinCompSources.Finding>, catalog: Map<String, WinComponents.Component>): Map<String, WinComponents.AutoReason> {
val out = LinkedHashMap<String, WinComponents.AutoReason>()
for (f in findings) {
@@ -51,30 +34,22 @@ object AutoComponents {
return out
}
// ---- seams for tests ----
@VisibleForTesting internal var catalogOf: (Context, Boolean) -> List<WinComponents.Component>? =
{ c, network -> if (network) WinComponents.fetch(c) else WinComponents.cached(c) }
@VisibleForTesting internal var installedOf: (Context) -> Set<String> = { WinComponents.installedIds(it).toSet() }
@VisibleForTesting internal var installer: (Context, WinComponents.Component, Map<String, WinComponents.Component>, (WinComponents.Progress) -> Unit) -> String? =
{ c, comp, all, progress -> WinComponents.install(c, comp, all, progress) }
@VisibleForTesting internal var sessionRunning: () -> Boolean = { SessionState.running }
/** Battery saver, a warm device or a metered network: no work nobody asked for. */
@VisibleForTesting internal var unfavourable: (Context) -> Boolean = { c -> constrained(c) }
/** A usable network: a download waits for one. */
@VisibleForTesting internal var online: (Context) -> Boolean = { c -> isOnline(c) }
/** Tests run the queue on the caller's thread ([drain]) instead of the worker. */
@VisibleForTesting @Volatile internal var runNow = false
/** Bumped whenever a game's list or automatic components change, so an open page reads them again. */
val changes = MutableStateFlow(0)
/** The components downloading for an automatic pick right now, with their progress. */
val downloading = MutableStateFlow<Map<String, WinComponents.Progress>>(emptyMap())
/** Games (by [appKey]) whose list is queued or being worked out: a page waits on it. */
val pendingGames = MutableStateFlow<Set<String>>(emptySet())
/** Components queued for an automatic pick, not yet downloaded. */
val pendingComponents = MutableStateFlow<Set<String>>(emptySet())
private fun mark(job: Job, on: Boolean) {
@@ -84,10 +59,8 @@ object AutoComponents {
flow.value = if (on) flow.value + id else flow.value - id
}
/** One piece of work: a game's list ([game]) or one component's download ([component]). [asked]: the user is waiting on it. */
internal class Job(
val game: Library.SteamGame?, val component: String?, val asked: Boolean, val seq: Long, val pics: List<Int>? = null,
/** For a game Steam installed during the running session: may run in it, unless a game is running. */
val inSession: Boolean = false,
) {
val key get() = when {
@@ -95,24 +68,17 @@ object AutoComponents {
component != null -> "c:$component"
else -> "g:" + (game?.let { appKey(it) } ?: "")
}
/** Needs the network: a download, or Steam asked anonymously. */
val online get() = component != null || pics != null
}
private val seq = java.util.concurrent.atomic.AtomicLong()
/** What the user asked for first, then in the order queued. */
private val jobs = PriorityBlockingQueue<Job>(16, compareByDescending<Job> { it.asked }.thenBy { it.seq })
@Volatile private var draining = false
private val queuedKeys = java.util.Collections.synchronizedSet(HashSet<String>())
/** The games waiting on a component's download, to turn it on for when it lands. */
private val waiting = HashMap<String, MutableList<Library.SteamGame>>()
@Volatile private var worker: Thread? = null
private const val PAUSE_MS = 15_000L
/**
* [game]'s list worked out again on the worker, and its components queued: [asked] when the
* user is waiting (its page is open, or they installed or added it).
*/
fun queueGame(context: Context, game: Library.SteamGame, asked: Boolean) {
if (appKey(game) == null) return
enqueue(context, Job(game, null, asked, seq.incrementAndGet()))
@@ -121,10 +87,8 @@ object AutoComponents {
private fun queueDownload(context: Context, id: String, asked: Boolean, inSession: Boolean = false) =
enqueue(context, Job(null, id, asked, seq.incrementAndGet(), inSession = inSession))
/** Adds [job] unless the same one is queued (a game or a component, once each). */
private fun enqueue(context: Context, job: Job) {
if (!queuedKeys.add(job.key)) {
// Asked for now: ahead of what nobody asked for, so the open page does not wait behind the sweep.
if (job.asked && jobs.removeIf { it.key == job.key && !it.asked }) jobs.add(job)
if (runNow && !draining) drain(context)
return
@@ -135,12 +99,10 @@ object AutoComponents {
if (runNow) { if (!draining) drain(context) } else ensureWorker(context.applicationContext)
}
/** Whether [job] has to wait: always while a session runs; one nobody asked for also when it is unfavourable. */
internal fun mustWait(context: Context, job: Job): Boolean =
if (job.inSession && sessionRunning()) gameRunning() || (job.online && !online(context))
else sessionRunning() || (job.online && !online(context)) || (!job.asked && unfavourable(context))
/** A game is running in the session (Steam's reaper, or Proton waiting on its game). */
@VisibleForTesting internal var gameRunning: () -> Boolean = { gameProcessRunning() }
private fun gameProcessRunning(): Boolean = File("/proc").listFiles()?.any { p ->
@@ -148,17 +110,11 @@ object AutoComponents {
?.let { it.contains("SteamLaunch AppId=") || it.contains("proton waitforexitandrun") } == true
} == true
/**
* A game Steam installed during the running session: its list worked out and its components
* readied in the session (one job, low priority), so a launch right after finds them; it
* waits while a game runs. All other work stays paused until the session ends.
*/
fun queueInSession(context: Context, game: Library.SteamGame) {
if (appKey(game) == null) return
enqueue(context, Job(game, null, true, seq.incrementAndGet(), inSession = true))
}
/** Runs the queued jobs on this thread until the queue is empty or the next one has to wait. Tests. */
@VisibleForTesting
internal fun drain(context: Context) {
draining = true
@@ -173,7 +129,6 @@ object AutoComponents {
}
}
/** The first job in order that may run now, taken off the queue; null when none may. */
private fun next(context: Context): Job? = synchronized(jobs) {
val job = jobs.sortedWith(order).firstOrNull { !mustWait(context, it) } ?: return null
jobs.remove(job)
@@ -190,8 +145,6 @@ object AutoComponents {
worker = Thread({
android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND)
while (true) {
// Something queued, then the first that may run (one for a game installed in the
// session goes ahead of paused work); else a look again in a while.
try { jobs.put(jobs.take()) } catch (e: InterruptedException) { return@Thread }
val job = next(app)
if (job == null) {
@@ -219,21 +172,14 @@ object AutoComponents {
}
}
/**
* [game]'s list (worked out again only when what it is read from changed), its automatic
* components that are downloaded turned on, and the rest queued for download.
*/
private fun apply(context: Context, game: Library.SteamGame, asked: Boolean, inSession: Boolean = false) {
val key = appKey(game) ?: return
val folder = game.gameFiles
if (game.library == Library.ADDED && game.source == Library.ADDED && folder != null && SteamMatch.get(context, folder.path) == null) {
AddedGames.single(context, folder.path)?.let { SteamMatch.resolve(context, folder.path, it.exe, it.name) }
}
// A GOG or Epic game installed before its sidecar kept the store's list: read it once from the store.
val store = com.droiddeck.launcher.stores.Store.byId(game.source)
if (folder != null && (store == com.droiddeck.launcher.stores.Store.GOG || store == com.droiddeck.launcher.stores.Store.EPIC)) StoreListBackfill.fill(context, folder)
// Its Steam app, when the client never saw it: Steam asked anonymously now if the user is
// waiting on this game (a pass over every game asks for all of them in one go, [sweep]).
if (asked && online(context)) steamAppOf(context, game)?.let { SteamAppInfo.lookup(context, listOf(it)) }
val findings = findings(context, game)
val catalog = (catalogOf(context, false) ?: catalogOf(context, true))?.associateBy { it.name } ?: return
@@ -249,7 +195,6 @@ object AutoComponents {
queueDownload(context, id, asked, inSession)
missing.add(id)
}
// In a session the launch waits a little for these (droiddeck-wincomponents reads the list).
if (inSession) Pending.set(context, key, missing)
val before = WinComponents.selection(context, key).auto
if (before.keys != kept.keys) {
@@ -259,7 +204,6 @@ object AutoComponents {
changes.value = changes.value + 1
}
/** One component downloaded and installed, then turned on for every game waiting on it. */
private fun download(context: Context, id: String, asked: Boolean, inSession: Boolean = false) {
val catalog = catalogOf(context, true)?.associateBy { it.name } ?: run { Pending.drop(context, id); return }
if (id !in installedOf(context)) {
@@ -279,10 +223,6 @@ object AutoComponents {
Pending.drop(context, id)
}
/**
* The components still being readied for games installed in the session, where the launch
* reads them (~/.config/droiddeck/wincomponents-pending.json in the runtime).
*/
internal object Pending {
private fun file(context: Context) = File(com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(context), "root/.config/droiddeck/wincomponents-pending.json")
@@ -315,11 +255,9 @@ object AutoComponents {
}
}
// ---- the list, kept per game ----
private const val FINDINGS = "wincomp-findings.json"
/** What the list is read from, by modification time: a change means it is worked out again. */
internal fun signature(context: Context, game: Library.SteamGame): String {
val folder = game.gameFiles
val parts = listOfNotNull(
@@ -334,7 +272,6 @@ object AutoComponents {
return parts.joinToString("|")
}
/** [game]'s list: the one kept when nothing it is read from changed, else worked out again and kept. Worker only. */
internal fun findings(context: Context, game: Library.SteamGame): List<WinCompSources.Finding> {
val key = appKey(game) ?: return emptyList()
val sig = signature(context, game)
@@ -345,7 +282,6 @@ object AutoComponents {
return fresh
}
/** The list kept for [appKey], without working anything out; null before the first time. */
fun cachedFindings(context: Context, appKey: String): List<WinCompSources.Finding>? =
readFindings(context).optJSONObject(appKey)?.let { decode(it.optJSONArray("findings")) }
@@ -374,34 +310,21 @@ object AutoComponents {
WinCompSources.Finding(o.optString("component").takeIf { it.isNotEmpty() }, o.optString("original"), origin, o.optBoolean("auto"), args)
}
// ---- when ----
/** Before a launch from DroidDeck: nothing but a queued look (it waits for the session to end). */
fun beforeLaunch(context: Context, game: Library.SteamGame) = queueGame(context, game, asked = false)
/** After an install or an add: the user did it, so it does not wait on a metered network. */
fun refreshLater(context: Context, game: Library.SteamGame) = queueGame(context, game, asked = true)
/**
* Every game, whatever its source, at app start and after each session (Steam installs its
* games without a word to DroidDeck; older GOG and Epic installs get their list read once):
* only queued, one game at a time, behind anything asked for, under the same conditions. A
* game whose files did not change costs a look at their times.
*/
fun sweep(context: Context, games: List<Library.SteamGame>) {
// First every Steam app these games are that the client never saw, asked of Steam in one
// connection; then each game's list.
val apps = games.mapNotNull { steamAppOf(context, it) }.distinct()
if (apps.isNotEmpty() && SteamAppInfo.needLookup(context, apps).isNotEmpty()) enqueue(context, Job(null, null, false, seq.incrementAndGet(), pics = apps))
games.forEach { queueGame(context, it, asked = false) }
}
/** The Steam app whose list a game takes: a Steam game's own, or an added game's match. */
private fun steamAppOf(context: Context, game: Library.SteamGame): Int? =
if (game.library != Library.ADDED) game.appId.takeIf { it > 0 }
else game.gameFiles?.let { SteamMatch.get(context, it.path) }?.appId
/** The default network is there and validated (reaches the internet). */
fun isOnline(context: Context): Boolean {
val cm = context.getSystemService(ConnectivityManager::class.java) ?: return false
val caps = cm.getNetworkCapabilities(cm.activeNetwork ?: return false) ?: return false
@@ -409,7 +332,6 @@ object AutoComponents {
caps.hasCapability(android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED)
}
/** Battery saver, thermal status moderate or worse, or a metered network. */
private fun constrained(context: Context): Boolean {
val power = context.getSystemService(PowerManager::class.java)
if (power?.isPowerSaveMode == true) return true
@@ -11,27 +11,12 @@ import java.net.HttpURLConnection
import java.net.URL
import java.net.URLEncoder
/**
* Box art for the emulators' games, found and kept on the device: the front end shows a disc image
* with nothing but its emulator's logo otherwise.
*
* In order: the name of the file against RetroArch's thumbnail collection for the system
* (libretro-thumbnails, named after the standard disc-dump names - "Need for Speed - Underground 2
* (USA)"), first exactly and then loosely (tags dropped, the same region preferred) against the
* collection's list of names; then the disc's own ID, read from the image - PS2 serials against
* xlenore/ps2-covers (what PCSX2 and ARMSX2 download from), GameCube/Wii IDs against GameTDB (what
* Dolphin uses). A PS3 disc image gives its own PS3_GAME/ICON0.PNG first: the libretro PS3
* collection is small. A cover is downloaded once into files/covers; a game none of them has is not
* asked about again for a few days.
*/
object CoverArt {
private const val TAG = "CoverArt"
private const val MISS_RETRY_MS = 3L * 24 * 3600 * 1000
private const val INDEX_TTL_MS = 14L * 24 * 3600 * 1000
/** Downloads in one pass, so a first visit to a big library does not hold the network for long. */
private const val MAX_PER_PASS = 40
/** The emulator's systems in libretro-thumbnails, in the order they are tried. */
private val collections = mapOf(
"rpcs3" to listOf("Sony_-_PlayStation_3"),
"armsx2" to listOf("Sony_-_PlayStation_2"),
@@ -44,14 +29,12 @@ object CoverArt {
private fun root(context: Context) = File(context.filesDir, "covers")
/** The file name, as the cover is kept under: a game keeps its art when its folder moves. */
private fun keyOf(rom: Library.Rom): String =
rom.hostPath.name.replace(Regex("[^A-Za-z0-9._() -]"), "_").take(150)
private fun coverFile(context: Context, rom: Library.Rom) = File(root(context), "${rom.emulatorId}/${keyOf(rom)}.img")
private fun missFile(context: Context, rom: Library.Rom) = File(root(context), "${rom.emulatorId}/${keyOf(rom)}.miss")
/** A cover already on the device for this game, or null. */
fun cached(context: Context, rom: Library.Rom): File? = coverFile(context, rom).takeIf { it.isFile && it.length() > 0 }
private fun wanted(context: Context, rom: Library.Rom): Boolean {
@@ -60,10 +43,6 @@ object CoverArt {
return !(miss.isFile && System.currentTimeMillis() - miss.lastModified() < MISS_RETRY_MS)
}
/**
* Looks for covers for the games that have none, on the calling (background) thread. True when
* at least one was found, so the caller rebuilds the list to show it.
*/
fun fetchMissing(context: Context, roms: List<Library.Rom>): Boolean {
var found = false
var tries = 0
@@ -71,7 +50,6 @@ object CoverArt {
if (!wanted(context, rom)) continue
if (++tries > MAX_PER_PASS) break
val target = coverFile(context, rom)
// A PS3 disc carries its own cover (PS3_GAME/ICON0.PNG, not encrypted): no download.
if (rom.emulatorId == "rpcs3" && try { copyPs3Icon(rom.hostPath, target) } catch (e: Exception) { false }) {
Log.i(TAG, "${rom.name}: ICON0.PNG from the disc")
missFile(context, rom).delete()
@@ -93,13 +71,10 @@ object CoverArt {
private fun findUrl(context: Context, rom: Library.Rom): String? {
val name = rom.hostPath.nameWithoutExtension.removeSuffix(".dec")
for (collection in collections.getValue(rom.emulatorId)) {
// Exactly the dump name first: no listing needed.
val exact = thumbnailUrl(collection, name)
if (exists(exact)) return exact
// Then loosely, against the collection's names.
nearest(name, names(context, collection))?.let { return thumbnailUrl(collection, it) }
}
// The disc's own ID.
return when (rom.emulatorId) {
"armsx2" -> ps2Serial(rom.hostPath)?.let { "https://raw.githubusercontent.com/xlenore/ps2-covers/main/covers/default/$it.jpg" }
"dolphin" -> nintendoDiscId(rom.hostPath)?.let { id ->
@@ -110,18 +85,15 @@ object CoverArt {
}?.takeIf { exists(it) }
}
/** libretro-thumbnails replaces these in a title's file name. */
private fun thumbName(title: String) = title.replace(Regex("[&*/:`<>?\\\\|\"]"), "_")
private fun thumbnailUrl(collection: String, title: String) =
"https://raw.githubusercontent.com/libretro-thumbnails/$collection/master/Named_Boxarts/" +
URLEncoder.encode("${thumbName(title)}.png", "UTF-8").replace("+", "%20")
// ---- loose matching ------------------------------------------------------------------------
private fun tags(name: String): List<String> = Regex("[(\\[]([^)\\]]*)[)\\]]").findAll(name).map { it.groupValues[1].lowercase() }.toList()
/** A title without its tags, articles and punctuation: "Legend of Zelda, The (USA)" = "legend of zelda". */
private fun base(name: String): String = name
.replace(Regex("\\s*[(\\[][^)\\]]*[)\\]]"), " ")
.lowercase()
@@ -139,7 +111,6 @@ object CoverArt {
return same.firstOrNull { region in tags(it) } ?: same.firstOrNull { "usa" in tags(it) } ?: same.first()
}
/** The titles in a collection's Named_Boxarts (no extension), kept for a fortnight. */
private fun names(context: Context, collection: String): List<String> {
val cache = File(root(context), "index-$collection.txt")
if (cache.isFile && System.currentTimeMillis() - cache.lastModified() < INDEX_TTL_MS) return cache.readLines()
@@ -161,12 +132,7 @@ object CoverArt {
private fun cachedOr(cache: File): List<String> = if (cache.isFile) cache.readLines() else emptyList()
// ---- disc IDs ------------------------------------------------------------------------------
/**
* A file's bytes from an ISO 9660 image by path ("PS3_GAME/ICON0.PNG"), or null. Primary volume
* names only (upper case, ";1" suffix), which is what PS2 and PS3 discs use.
*/
private fun isoFile(file: File, path: String, maxSize: Int): ByteArray? {
if (!file.name.endsWith(".iso", ignoreCase = true)) return null
RandomAccessFile(file, "r").use { f ->
@@ -208,14 +174,12 @@ object CoverArt {
return if (bounds.outWidth > 0 && tmp.renameTo(target)) true else { tmp.delete(); false }
}
/** "SLUS-21065" from a PS2 .iso's SYSTEM.CNF (BOOT2 = cdrom0:\SLUS_210.65;1), or null. */
private fun ps2Serial(file: File): String? {
val cnf = String(isoFile(file, "SYSTEM.CNF", 4096) ?: return null, Charsets.US_ASCII)
val m = Regex("BOOT2\\s*=\\s*cdrom0:\\\\?([A-Z]{4})_(\\d{3})\\.(\\d{2})").find(cnf) ?: return null
return "${m.groupValues[1]}-${m.groupValues[2]}${m.groupValues[3]}"
}
/** The six-character ID of a GameCube/Wii disc image (.iso/.gcm, or .wbfs), or null. */
private fun nintendoDiscId(file: File): String? {
val offset = when (file.extension.lowercase()) { "iso", "gcm" -> 0L; "wbfs" -> 0x200L; else -> return null }
RandomAccessFile(file, "r").use { f ->
@@ -225,7 +189,6 @@ object CoverArt {
}
}
// ---- network -------------------------------------------------------------------------------
private fun open(url: String, method: String = "GET"): HttpURLConnection =
(URL(url).openConnection() as HttpURLConnection).apply {
@@ -245,7 +208,6 @@ object CoverArt {
if (c.responseCode != 200) { c.disconnect(); null } else c.inputStream.bufferedReader().use { it.readText() }
} catch (e: Exception) { Log.w(TAG, "$url: $e"); null }
/** Saves the image at [url] to [target] if it really is an image. */
private fun download(url: String, target: File): Boolean = try {
val c = open(url)
if (c.responseCode != 200) { c.disconnect(); false } else {
@@ -3,49 +3,25 @@ package com.droiddeck.launcher.frontend
import java.io.File
import java.util.Locale
/**
* Best-effort detection of the Windows redistributables a game bundles, by scanning its install
* folder for the redist installers Steam/Epic/GOG ship (`_CommonRedist/`, `_Redist/`,
* `Redistributables/`, loose `vcredist_x64.exe`, …) and mapping them to entries in our component
* catalog (WinComponents, Bannerlator's components.json `name` keys). The result drives the
* Recommended part of a game's Windows components; the user still switches each one on.
* Bannerlator's detector, unchanged but for this note and its package.
*
* Wine-aware: keeps the redists that actually matter under Wine/DXVK (VC++ runtimes, .NET, PhysX,
* OpenAL, XACT, XNA, GFWL) and SKIPS the ones DXVK/VKD3D already provide (DX12 Agility SDK) or that
* aren't our components (anti-cheat, Rockstar/Social-Club/launcher setups). Never throws; returns an
* empty list on anything unexpected. Pure filesystem — no network, no Android deps (unit-testable).
*/
object DependencyDetector {
/** How a recommendation was found — drives the UI's "recommended vs optional" split. */
enum class Kind {
/** The game bundles the redist installer (in _CommonRedist etc.) — meant to be installed. */
BUNDLED,
/** A runtime DLL the game ships loose — usually already works from the game folder; install
* only if the game misbehaves. */
SHIPPED,
/** Steam installs it with the game from Steamworks Shared ([SteamRedists]). */
STEAM,
}
/** A recommended component: the catalog [componentName] to install, a display [label], the on-disk
* redist that triggered it ([reason]), and [kind] (bundled installer vs shipped DLL). */
data class Recommendation(val componentName: String, val label: String, val reason: String, val kind: Kind = Kind.BUNDLED)
private const val MAX_DEPTH = 5
private const val MAX_ENTRIES = 8000 // cost guard against giant game trees
private const val MAX_ENTRIES = 8000
/** A loose VC++ installer with no year in its path — resolved to "latest" only if no specific
* vcredistYYYY was found anywhere (else it's just a duplicate of the versioned one). */
private const val VCREDIST_LOOSE = "__vcredist_loose"
/** Directory names that are redist containers worth descending into. */
private val REDIST_DIR_RE = Regex(
"""(?i)^(_?commonredist|_?redist(ributables)?|__?installer|vcredist|vc_redist|directx|direct_x|physx|openal|dotnet(fx)?|\.net|xna|xact|redist|support)$"""
)
/** Skip whole subtrees that are never our components. */
private val SKIP_DIR_RE = Regex("""(?i)^(d3d12.*|.*agility.*|dxvk|vkd3d|battleye|easyanticheat|eac|anticheat)$""")
private val YEAR_TO_VCREDIST = mapOf(
@@ -70,7 +46,6 @@ object DependencyDetector {
"dotnetcoredesktop8" to ".NET Desktop 8",
)
/** Preferred install order (runtimes others may depend on first). */
private val INSTALL_ORDER = listOf(
"vcredist2005", "vcredist2008", "vcredist2010", "vcredist2012", "vcredist2013",
"vcredist2015", "vcredist2019", "vcredist2022",
@@ -79,13 +54,6 @@ object DependencyDetector {
"d3dx9", "d3dx11", "xact", "xact_x64", "xna31", "xna40", "physx", "oalinst", "XLiveRedist",
)
/**
* Detect from the .exe the user picked, resolving the game root first: walk up from the exe's
* folder (bounded) to the nearest ancestor that holds a redist container (`_CommonRedist`, …) at
* its top level, and scan from there — so a nested exe (`…/Game/bin/x.exe`) still finds a root-level
* `_CommonRedist`, without over-reaching into a shared `steamapps/common` (which has no redist
* container of its own). Falls back to scanning the exe's own folder.
*/
fun detectForExe(exeFile: File): List<Recommendation> {
val start = exeFile.absoluteFile.parentFile ?: return emptyList()
var d: File? = start
@@ -101,19 +69,14 @@ object DependencyDetector {
return detect(start)
}
/**
* Scan [gameDir] and return the recommended components, de-duplicated (first reason wins), in a
* stable install-friendly order. Empty when nothing is detected or [gameDir] isn't a directory.
*/
fun detect(gameDir: File): List<Recommendation> {
if (!gameDir.isDirectory) return emptyList()
val hits = LinkedHashMap<String, Recommendation>() // componentName -> first recommendation
val hits = LinkedHashMap<String, Recommendation>()
var visited = 0
fun consider(f: File, isDir: Boolean, insideRedist: Boolean) {
val name = f.name.lowercase(Locale.US)
val path = f.path.replace('\\', '/').lowercase(Locale.US)
// Bundled = in a redist container or an installer (exe/msi/cab); shipped = a loose runtime DLL.
val kind = if (insideRedist || isDir || name.endsWith(".exe") || name.endsWith(".msi") || name.endsWith(".cab"))
Kind.BUNDLED else Kind.SHIPPED
for (comp in classify(path, name, isDir)) {
@@ -121,7 +84,7 @@ object DependencyDetector {
if (existing == null) {
hits[comp] = Recommendation(comp, LABELS[comp] ?: comp, relativeReason(gameDir, f), kind)
} else if (existing.kind == Kind.SHIPPED && kind == Kind.BUNDLED) {
hits[comp] = existing.copy(kind = Kind.BUNDLED) // a bundled installer outranks a shipped DLL
hits[comp] = existing.copy(kind = Kind.BUNDLED)
}
}
}
@@ -134,17 +97,11 @@ object DependencyDetector {
val lower = f.name.lowercase(Locale.US)
if (f.isDirectory) {
if (SKIP_DIR_RE.matches(lower)) continue
// Unity's <Game>_Data/Managed holds the game's own Mono assemblies, not a .NET
// Framework to install.
if (lower == "managed" && dir.name.endsWith("_Data", ignoreCase = true)) continue
val isRedistDir = insideRedist || REDIST_DIR_RE.matches(lower)
if (isRedistDir) consider(f, isDir = true, insideRedist = true)
// Aggressive coverage: descend redist containers fully, and otherwise sweep the game
// tree a few levels deep so runtime libraries the game ships (in bin/, etc.) are seen.
if (isRedistDir || depth < 3) walk(f, depth + 1, isRedistDir)
} else {
// Classify installers + runtime libraries (.dll/.exe/.msi) anywhere in the scanned
// tree; other files are ignored. Recommendations are advisory, so cast a wide net.
val ext = lower.substringAfterLast('.', "")
if (insideRedist || ext == "dll" || ext == "exe" || ext == "msi") consider(f, isDir = false, insideRedist = insideRedist)
}
@@ -160,20 +117,13 @@ object DependencyDetector {
}
}
/**
* The catalog components one installer stands for, by its path ("_CommonRedist/vcredist/2015/
* vc_redist.x64.exe", "DXSETUP.exe"): what a store's install list names. A VC++ installer
* with no year is the latest; empty for one that is none of ours.
*/
fun componentsFor(path: String): List<String> {
val p = path.replace('\\', '/').lowercase(Locale.US)
return classify(p, p.substringAfterLast('/'), isDir = false).map { if (it == VCREDIST_LOOSE) "vcredist2022" else it }
}
/** The name the catalog component [name] goes by, for a reason line. */
fun label(name: String): String = LABELS[name] ?: name
/** A loose VC++ installer resolves to the latest 14.x only if no specific vcredistYYYY was found. */
private fun resolveLooseVcredist(hits: LinkedHashMap<String, Recommendation>) {
val loose = hits.remove(VCREDIST_LOOSE) ?: return
val hasSpecific = hits.keys.any { it in YEAR_TO_VCREDIST.values }
@@ -186,52 +136,38 @@ object DependencyDetector {
return if (p.startsWith("$g/")) p.substring(g.length + 1) else f.name
}
/**
* Map a redist file/dir (its full lowercased [path], leaf [name], and whether it [isDir]) to
* catalog component name(s). Empty for things we deliberately skip.
*/
private fun classify(path: String, name: String, isDir: Boolean): List<String> {
// Hard skips first — DX12 is provided by DXVK/VKD3D; these aren't our components.
if (path.contains("d3d12") || path.contains("agility") ||
path.contains("battleye") || path.contains("anticheat") || path.contains("easyanticheat") ||
name.contains("socialclub") || name.contains("social-club") ||
name.contains("rockstar") || name == "setup.exe"
) return emptyList()
// Visual C++ runtimes — most important. Year comes from the path context.
if (path.contains("vcredist") || path.contains("vc_redist") || name.startsWith("vcredist") || name.startsWith("vc_redist")) {
val year = YEAR_TO_VCREDIST.keys.firstOrNull { path.contains(it) }
return when {
year != null -> listOf(YEAR_TO_VCREDIST.getValue(year))
isDir -> emptyList() // bare "vcredist" container — wait for the year subfolder / installer
else -> listOf(VCREDIST_LOOSE) // loose installer, no year → resolved post-walk
isDir -> emptyList()
else -> listOf(VCREDIST_LOOSE)
}
}
// VC++ runtime DLL the game ships (msvcp140.dll → 2015-2022, msvcp120.dll → 2013, …).
VCRUNTIME_DLL.entries.firstOrNull { name.startsWith(it.key) }?.let { return listOf(it.value) }
if (path.contains("openal") || name.startsWith("oalinst") || name == "openal32.dll" || name == "wrap_oal.dll") return listOf("oalinst")
if (path.contains("physx") || name.startsWith("physx")) return listOf("physx")
if (path.contains("xact") || name.startsWith("xactengine") || name.startsWith("x3daudio")) return listOf("xact", "xact_x64")
// Games for Windows Live — the redist folder, OR a GFWL library the game ships (xlive.dll,
// Codemasters' dbxLive32/64, gfwl*): GFWL titles need XLiveRedist to run even when they don't
// bundle the redist itself.
if (path.contains("xliveredist") || name.contains("xlive") || name.startsWith("gfwl") || name.startsWith("dbxlive")) {
return listOf("XLiveRedist")
}
if (path.contains("xna")) return listOf(if (path.contains("3.1") || path.contains("3_1") || path.contains("v31")) "xna31" else "xna40")
// .NET — Framework and Core/Desktop runtimes.
if (path.contains("dotnet") || path.contains(".net") || name.startsWith("ndp") || name.startsWith("dotnetfx") || name.contains("windowsdesktop-runtime")) {
val comp = dotnetComponent("$path $name")
return when {
comp != null -> listOf(comp)
isDir -> emptyList() // bare ".NET" container — wait for the versioned installer
else -> listOf("dotnet48") // unlabeled .NET Framework installer file → sensible default
isDir -> emptyList()
else -> listOf("dotnet48")
}
}
// DirectX 11 helper DLLs the game ships (d3dx11_43.dll).
if (D3DX11_RE.matches(name)) return listOf("d3dx11")
// DirectX 9 helper DLLs / d3dcompiler / June-2010 DX redist (DXVK provides core d3d9 but NOT
// these helper DLLs).
if (name.startsWith("dxsetup") || name.startsWith("dxwebsetup") ||
D3DX9_RE.matches(name) || D3DCOMPILER_RE.matches(name) ||
(path.contains("directx") && name.endsWith(".exe"))
@@ -239,7 +175,6 @@ object DependencyDetector {
return emptyList()
}
/** Runtime DLL prefix → the VC++ redistributable that provides it (checked with startsWith). */
private val VCRUNTIME_DLL = linkedMapOf(
"vcruntime140" to "vcredist2022", "msvcp140" to "vcredist2022", "msvcr140" to "vcredist2022", "concrt140" to "vcredist2022",
"msvcp120" to "vcredist2013", "msvcr120" to "vcredist2013",
@@ -252,7 +187,6 @@ object DependencyDetector {
private val D3DX11_RE = Regex("""d3dx11_\d+\.dll""")
private val D3DCOMPILER_RE = Regex("""d3dcompiler_\d+\.dll""")
/** Resolve a .NET component from installer/path text, or null when no version is discernible. */
private fun dotnetComponent(s: String): String? = when {
s.contains("desktop-runtime-8") || Regex("""\b8\.\d""").containsMatchIn(s) -> "dotnetcoredesktop8"
s.contains("desktop-runtime-7") || Regex("""\b7\.\d""").containsMatchIn(s) -> "dotnetcoredesktop7"
@@ -264,6 +198,6 @@ object DependencyDetector {
s.contains("dotnetfx45") || s.contains("ndp45") || s.contains("4.5") -> "dotnet45"
s.contains("dotnetfx40") || s.contains("ndp40") || s.contains("4.0") -> "dotnet40"
s.contains("dotnetfx35") || s.contains("3.5") -> "dotnet35"
else -> null // no version signal (e.g. a bare "DotNet" container dir)
else -> null
}
}
@@ -2,26 +2,15 @@ package com.droiddeck.launcher.frontend
import java.io.File
/**
* Which `.exe` in a game folder is the game. A real install holds installers, crash handlers,
* anti-cheat stubs and launchers beside the game, and the game itself may sit several levels down
* (`Game/Binaries/Win64/Game-Win64-Shipping.exe`), so candidates are collected with a bounded walk
* and ranked rather than guessed by position.
*/
object GameExePicker {
/** How far below a game folder to look: Unreal puts the game three down, repacks deeper. */
const val MAX_DEPTH = 5
/** Folders and .exe files looked at per game before the walk stops, so a huge game stays quick. */
const val WALK_BUDGET = 400
/** Below this the pick is marked uncertain rather than trusted silently. */
const val CONFIDENT_SCORE = 60
/** The best and the runner-up this close together: nothing clearly won. */
const val AMBIGUOUS_MARGIN = 15
/** Folders that never hold the game itself. */
private val SKIP_DIRS = setOf(
"_commonredist", "commonredist", "redist", "redistributable", "redistributables",
"directx", "dotnet", "dotnetfx", "vcredist", "vc_redist", "prerequisites", "prereq",
@@ -32,7 +21,6 @@ object GameExePicker {
private val SKIP_DIR_PREFIX = listOf("dotnet", "vcredist", "$")
private val SKIP_PATHS = listOf("engine/extras", "engine/binaries/thirdparty")
/** Exe names that are never the game. */
private val JUNK_EXE_RE = Regex(
"""(?i)^(unins\w*|setup|install\w*|vc_?redist.*|vcredist.*|dxsetup|dxwebsetup|directx.*|""" +
"""oalinst|openal.*|dotnetfx.*|ndp\d.*|unitycrashhandler\d*|crashreport\w*|crashpad\w*|""" +
@@ -41,10 +29,8 @@ object GameExePicker {
"""activation\w*|register\w*|readme|report\w*|.*_debug|.*-debug)$""",
)
/** A folder's exes best first, with their scores, and whether the first clearly won. */
class Ranking(val exes: List<File>, val scores: List<Int>, val uncertain: Boolean)
/** Ranks the .exe files under [folder]; [keep] drops names the caller never offers. */
fun rank(folder: File, keep: (File) -> Boolean = { true }): Ranking {
val scored = collect(folder).filter { keep(it.first) }.map { (exe, depth) -> exe to score(exe, folder, depth) }
.sortedWith(compareByDescending<Pair<File, Int>> { it.second }.thenBy { it.first.path.lowercase() })
@@ -54,11 +40,6 @@ object GameExePicker {
return Ranking(scored.map { it.first }, scored.map { it.second }, uncertain)
}
/**
* Every plausible exe under [folder] with its depth (0 = in the folder itself): up to
* [MAX_DEPTH] folders down, nearest levels first, at most [WALK_BUDGET] entries, never through a
* symlink, past folders that never hold the game.
*/
private fun collect(folder: File): List<Pair<File, Int>> {
val found = ArrayList<Pair<File, Int>>()
var visited = 0
@@ -86,31 +67,23 @@ object GameExePicker {
return found
}
/**
* How likely [exe] is to be the game in [folder]. Relative only: the numbers rank candidates
* against each other and decide whether anything won clearly enough to trust.
*/
internal fun score(exe: File, folder: File, depth: Int): Int {
var score = 0
val base = exe.nameWithoutExtension
val exeKey = key(base)
val folderKey = key(folder.name)
// The exe named after its folder is the single strongest signal.
if (exeKey.isNotEmpty() && folderKey.isNotEmpty()) {
when {
exeKey == folderKey -> score += 100
folderKey.contains(exeKey) || exeKey.contains(folderKey) -> score += 60
}
}
// Unreal ships as <Game>-Win64-Shipping.exe under Binaries/Win64.
if (base.endsWith("-Win64-Shipping", true) || base.endsWith("-Win32-Shipping", true)) score += 70
val path = exe.absolutePath.lowercase()
if (path.contains("/binaries/win64") || path.contains("/binaries/win32")) score += 30
if (path.contains("/bin/") || path.contains("/bin64/")) score += 10
// A launcher is a real entry point, so it stays a candidate, just not the preferred one.
if (GameIdentifier.isLauncherExeName(base)) score -= 40
if (GameIdentifier.isJunkPeName(base)) score -= 30
// Shallower is more likely the entry point; big binaries beat small helpers.
score -= depth * 8
score += (exe.length() / (8L * 1024 * 1024)).toInt().coerceAtMost(30)
return score
@@ -125,6 +98,5 @@ object GameExePicker {
private fun isLink(f: File): Boolean = runCatching { java.nio.file.Files.isSymbolicLink(f.toPath()) }.getOrDefault(false)
/** Comparison key: letters and digits only, so "GTA IV" and "gta-iv" match. */
private fun key(s: String) = s.lowercase().filter { it.isLetterOrDigit() }
}
@@ -10,7 +10,6 @@ import java.io.File
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
/** Runs while DroidDeck's process is alive, including downloads in a background Steam session. */
object GameFileSync {
private val worker = Executors.newSingleThreadScheduledExecutor { task -> Thread(task, "game-file-sync").apply { isDaemon = true } }
private fun prefs(context: Context) = context.getSharedPreferences("game_files", Context.MODE_PRIVATE)
@@ -39,7 +38,6 @@ object GameFileSync {
@Synchronized private fun sync(context: Context, folder: File) {
check(LinuxRuntime.isInstalled(context)) { context.getString(R.string.game_sync_err_runtime) }
// A disconnected library must not be interpreted as a mass uninstall.
check(File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/steamapps").isDirectory) { context.getString(R.string.game_sync_err_steam_library) }
val storage = GameStorage.effective(context)
val storageSetting = SessionPrefs.gameStorage(context)
@@ -11,14 +11,12 @@ import org.json.JSONObject
import java.io.File
import java.io.InputStream
/** Small, portable launch files for frontends that scan ROM folders. No guest paths or commands. */
object GameFiles {
const val EXTENSION = "steam"
private const val MAX_BYTES = 128
private const val INVENTORY = ".droiddeck-sync.json"
private const val FORMAT = "droiddeck-game-files-v1"
/** Called on a worker: content providers and shared storage may block. */
fun readIntent(context: Context, request: Intent): String? = runCatching {
if (request.action != Intent.ACTION_VIEW) return null
val uri = request.data ?: return null
@@ -36,7 +34,6 @@ object GameFiles {
}.getOrNull()
fun read(stream: InputStream): String? {
// An untrusted URI must not make us buffer an arbitrary ROM or parse a command.
val bytes = ByteArray(MAX_BYTES + 1)
var count = 0
while (count < bytes.size) {
@@ -84,7 +81,6 @@ object GameFiles {
} else target
}
/** Cocoon matches icons in its data folder's images directory. Never replace custom art. */
private fun exportArt(context: Context, folder: File, game: Library.SteamGame) {
val art = listOfNotNull(game.icon, game.art).firstOrNull {
it.isFile && it.extension.lowercase() in listOf("jpg", "jpeg", "png", "webp")
@@ -100,7 +96,6 @@ object GameFiles {
if (!target.exists()) AtomicFile(target).writeBytes(art.readBytes())
}
/** Only remove files in our inventory whose content is still exactly what we wrote. */
@Synchronized fun sync(context: Context, folder: File, games: List<Library.SteamGame>) {
require(folder.isDirectory) { context.getString(R.string.gfiles_folder_unavailable) }
val inventory = child(context, folder, INVENTORY)
@@ -119,21 +114,17 @@ object GameFiles {
else exportTarget(context, folder, game, name)
val text = contents(game.gameIdString)
val existed = target.exists()
// Keep an edited export without letting it block the rest of the library sync.
val owned = inventoryOwns(context, folder, previous, target, game.gameIdString)
val file = if (owned && target.exists() &&
!matches(target, text)) target else exportNamed(context, folder, game, target.name)
if (!existed || owned) next.put(file.name, game.gameIdString)
file
}
// Write new exports before pruning; a failed write must not remove old launch files.
for (name in previous.keys()) {
val id = previous.getString(name)
if (!next.has(name) && name.endsWith(".$EXTENSION") && GameLaunchLink.validId(id)) {
val file = child(context, folder, name)
if (matches(file, contents(id))) {
// Android shared storage is often case insensitive. A case-only rename may
// still resolve to the live export, which must not be pruned as an old file.
val retained = exports.any { java.nio.file.Files.isSameFile(it.toPath(), file.toPath()) }
if (!retained) check(file.delete()) { context.getString(R.string.gfiles_remove_failed, name) }
}
@@ -2,65 +2,35 @@ package com.droiddeck.launcher.frontend
import java.io.File
/**
* Best-effort identification of a game from its on-disk footprint, given its .exe: a Steam appId
* and/or a display name, so an added game is not just named after its folder or exe. Pure
* filesystem and PE parsing, no network, never throws; it reports only what the disk tells.
*
* Signal chain (appId preferred; best name chosen across all hits):
* 1. steam_appid.txt → appId (Goldberg-style installs)
* 2. ColdClientLoader / emu ini → appId (AppId= key)
* 3. appmanifest_<id>.acf → appId + name (real Steam install under steamapps/)
* 4. goggame-<id>.info → name (+ gogId) (GOG installs)
* 5. PE VS_VERSIONINFO → name (ProductName / FileDescription)
* 6. cleaned folder / exe name → name (weak fallback)
*/
object GameIdentifier {
/** How far up the directory tree to look for marker files (games nest deep, e.g. Game/Binaries/Win64/x.exe). */
private const val MAX_PARENT_DEPTH = 6
enum class Source { STEAM_APPID_TXT, STEAM_MANIFEST_ACF, STEAM_EMU_INI, GOG_INFO, PE_VERSION, FILENAME, NONE }
enum class Confidence { HIGH, MEDIUM, LOW }
/**
* @param appId Steam appId if one was found on disk, else null.
* @param gogId GOG product id if a goggame info file was found, else null.
* @param name Best display name found locally; may be null when only an appId was
* found (caller resolves the name from the appId over the network).
* @param source Which signal produced the primary identity.
*/
data class GameIdentity(
val appId: Int? = null,
val gogId: String? = null,
val name: String? = null,
val source: Source = Source.NONE,
val confidence: Confidence = Confidence.LOW,
/** Which signal gave [name]: [Source.FILENAME] means only a cleaned folder or exe name. */
val nameSource: Source = Source.NONE,
) {
val hasStrongId: Boolean get() = appId != null
}
/** Identify the game owning [exeFile]. Never throws; returns an empty identity if nothing matched. */
fun identify(exeFile: File): GameIdentity {
val dirs = ancestorDirs(exeFile)
// Steam appId from a bare steam_appid.txt (in the exe dir, a steam_settings/ subdir, or an ancestor).
val steamAppId = dirs.firstNotNullOfOrNull { readSteamAppIdTxt(it) }
// AppId= out of a ColdClientLoader.ini / steam_emu.ini next to the game.
val emuAppId = dirs.firstNotNullOfOrNull { readEmuIniAppId(it) }
// Real Steam install: appmanifest_<id>.acf up under steamapps/ — carries both appId and name.
val acf = resolveSteamManifest(exeFile, dirs)
// GOG: goggame-<id>.info JSON with the real title.
val gog = dirs.firstNotNullOfOrNull { readGogInfo(it) }
// PE ProductName / FileDescription — but not when it merely names a launcher/loader
// ("Rockstar Games Launcher Redirector", "GSE", …), which must not become the game name.
val peName = PeVersionInfo.bestName(PeVersionInfo.read(exeFile))?.takeUnless { isJunkPeName(it) }
val appId = acf?.appId ?: steamAppId ?: emuAppId
// Best name, most-trustworthy first.
val nameHit: Pair<String, Source>? = when {
acf?.name != null -> acf.name to Source.STEAM_MANIFEST_ACF
gog?.name != null -> gog.name to Source.GOG_INFO
@@ -68,7 +38,6 @@ object GameIdentifier {
else -> cleanedFallbackName(exeFile)?.let { it to Source.FILENAME }
}
// Primary source = whatever gave us the appId (strongest), else the name source.
val primary: Source = when {
acf?.appId != null -> Source.STEAM_MANIFEST_ACF
steamAppId != null -> Source.STEAM_APPID_TXT
@@ -93,27 +62,19 @@ object GameIdentifier {
)
}
/**
* Make an identified title readable and filesystem-safe (a Steam shortcut's name also names
* files): "DARK SOULS: REMASTERED" becomes "DARK SOULS - REMASTERED". Strips trademark marks,
* turns title punctuation into safe equivalents, and collapses whitespace.
*/
fun normalizeName(raw: String): String {
var s = raw
s = s.replace("™", "").replace("®", "").replace("©", "")
s = s.replace(Regex("""(?i)\(\s*(tm|r|c)\s*\)"""), "") // "(TM)" / "(R)" / "(C)"
s = s.replace(":", " - ") // colon → dash separator (safe + readable)
s = s.replace(Regex("""[\\/]"""), " ") // path separators → space
s = s.replace(Regex("""["*?<>|]"""), "") // other illegal chars → drop
// Drop trailing generic descriptors a PE FileDescription tacks on ("DiRT 3 Executable" → "DiRT 3").
s = s.replace(Regex("""(?i)\(\s*(tm|r|c)\s*\)"""), "")
s = s.replace(":", " - ")
s = s.replace(Regex("""[\\/]"""), " ")
s = s.replace(Regex("""["*?<>|]"""), "")
s = s.replace(Regex("""(?i)[ \-]+(executable|application|launcher|redistributable|installer|setup)$"""), "")
s = s.replace(Regex("""\s+"""), " ").trim() // collapse whitespace
return s.trim(' ', '-').trim() // tidy stray leading/trailing dashes
s = s.replace(Regex("""\s+"""), " ").trim()
return s.trim(' ', '-').trim()
}
// ── directory walk ──
/** The exe's directory plus its ancestors, nearest-first, bounded by [MAX_PARENT_DEPTH]. */
private fun ancestorDirs(exeFile: File): List<File> {
val out = ArrayList<File>(MAX_PARENT_DEPTH + 1)
var d: File? = exeFile.absoluteFile.parentFile
@@ -126,12 +87,9 @@ object GameIdentifier {
return out
}
// ── signal readers (all best-effort; return null on anything unexpected) ──
/** steam_appid.txt directly in [dir] or in a steam_settings/ subdir. */
private fun readSteamAppIdTxt(dir: File): Int? {
for (candidate in arrayOf(File(dir, "steam_appid.txt"), File(dir, "steam_settings/steam_appid.txt"))) {
// Strip a leading UTF-8 BOM (trim() doesn't) before reading the digits.
val id = readSmallTextFile(candidate)?.removePrefix("\uFEFF")?.trim()
?.takeWhile { it.isDigit() }?.toIntOrNull()
if (id != null && id > 0) return id
@@ -139,12 +97,6 @@ object GameIdentifier {
return null
}
/**
* First `AppId=<n>` in a crack/emu config .ini next to the game (ColdClientLoader, steam_emu,
* flt, hlm, …). Known names are tried first, then any other `.ini` in the dir — only crack
* configs carry an `AppId=` key, game settings .ini files (settings.ini, graphics.ini) don't,
* so the broad scan is safe.
*/
private fun readEmuIniAppId(dir: File): Int? {
val re = Regex("""(?im)^\s*appid\s*=\s*(\d+)""")
val named = arrayOf(
@@ -166,13 +118,6 @@ object GameIdentifier {
private data class Acf(val appId: Int?, val name: String?)
/**
* Resolve the Steam appmanifest for this game: find the `common` ancestor on the exe's
* path, read the sibling `steamapps/appmanifest_*.acf`, and match by installdir == the
* game folder under common. No match, no manifest: a folder in steamapps/common that no
* manifest claims is exactly the kind added games list, and the library's one other game is
* not its name.
*/
private fun resolveSteamManifest(exeFile: File, dirs: List<File>): Acf? {
val commonIdx = dirs.indexOfFirst { it.name.equals("common", ignoreCase = true) }
if (commonIdx < 0) return null
@@ -183,7 +128,6 @@ object GameIdentifier {
} ?: return null
if (manifests.isEmpty()) return null
// The game's install folder is the child of `common` on our descent path.
val gameFolder = if (commonIdx > 0) dirs[commonIdx - 1].name else null
val match = manifests.firstOrNull { m ->
@@ -200,7 +144,6 @@ object GameIdentifier {
private data class Gog(val id: String?, val name: String?)
/** goggame-<id>.info JSON: pull `name` (and the id from the filename). */
private fun readGogInfo(dir: File): Gog? {
val files = dir.listFiles { f ->
f.isFile && f.name.startsWith("goggame-") && f.name.endsWith(".info")
@@ -214,75 +157,42 @@ object GameIdentifier {
return null
}
// ── filename fallback ──
private val REPACK_TOKENS = setOf(
"fitgirl", "dodi", "codex", "plaza", "skidrow", "rune", "empress", "flt", "tenoke",
"reloaded", "elamigos", "razor1911", "hoodlum", "gog", "repack", "multi", "goldberg",
// repack/site tags that show up in folder names
"ankergames", "steamrip", "onlinefix", "online-fix", "gload", "fitgirlrepacks",
)
private const val EXE_NOISE_WORDS =
"""win64|win32|shipping|wingdk|client|launcher|game|x64|x86|64bit|32bit"""
/**
* Does this exe basename look like engine/arch boilerplate rather than a title? Deliberately
* UNANCHORED — "GameConTest" is boilerplate-ish wherever the giveaway sits, and the answer
* decides whether we trust the folder name instead of the exe name.
*/
private val EXE_NOISE_RE = Regex("""(?i)[-_. ]*(?:$EXE_NOISE_WORDS)""")
/**
* Trailing noise to strip off a title. ANCHORED to the end and allowed to repeat, because these
* words are only junk as a suffix: "Witcher3-Win64-Shipping" -> "Witcher3", while
* "Game of Thrones" and "Client Simulator" must survive intact.
*
* Kept separate from [EXE_NOISE_RE] on purpose. One regex used to serve both jobs, so
* anchoring it to fix stripping ALSO narrowed the boilerplate test — and a game in
* "Game Controller Test/GameConTest.exe" stopped preferring its folder and became "GameConTest".
*/
private val EXE_SUFFIX_RE = Regex("""(?i)(?:[-_. ]*(?:$EXE_NOISE_WORDS))+$""")
private val VERSION_TOKEN_RE = Regex("""(?i)\b(v?\d+([._]\d+)+|build[-_ ]?\d+|update[-_ ]?\d+)\b""")
/**
* True when an exe basename is a launcher/loader rather than the game — its parent folder is the
* better title. Catches "PlayGTAV"/"Play - GTA IV"/"LaunchGame"/"MyLauncher"/"GSE" but NOT a real
* title that merely starts with those letters ("PlayerUnknown"). A "play|launch|start|run" prefix
* counts only when it's a whole token — followed by a separator or a camelCase uppercase boundary,
* not another lowercase letter (checked case-sensitively, so it survives the case-insensitive JUNK
* matching used elsewhere).
*/
/** True when an exe basename looks like a launcher/loader rather than the game itself. */
fun isLauncherExeName(base: String): Boolean {
val lower = base.lowercase()
if (lower == "gse" || lower.endsWith("launcher") || lower.endsWith("redirector")) return true
for (p in arrayOf("play", "launch", "start", "run")) {
if (!lower.startsWith(p)) continue
val rest = base.substring(p.length)
if (rest.isEmpty()) return true // exactly "Play"
if (rest.isEmpty()) return true
val c = rest[0]
if (!c.isLetterOrDigit() || c.isUpperCase()) return true // "Play - GTA IV" / camelCase "PlayGTAV"
// lowercase continuation ("Player…") → part of a longer word, not a launcher
if (!c.isLetterOrDigit() || c.isUpperCase()) return true
}
return false
}
/** A PE ProductName/FileDescription that describes a launcher/loader, not the game — reject it so it
* doesn't become the shortcut name (e.g. "Rockstar Games Launcher Redirector", "GSE", "Steam"). */
private val JUNK_NAME_RE = Regex(
"""(?i)^(gse|steam|steam client|goldberg.*|launcher|game|play|start|setup|.* launcher.*|.*launcher redirector|.* redirector|rockstar games launcher.*|epic games launcher|smartsteamemu|coldclient.*|steamemu.*)$"""
)
/** True when a PE name is a launcher/loader label rather than a real game title. */
fun isJunkPeName(name: String): Boolean {
val n = name.trim()
return n.isEmpty() || JUNK_NAME_RE.matches(n)
}
/**
* Prefer the game's install-folder name (usually the real title) over the exe basename when the
* exe is a UE-style shipping binary OR a launcher/loader; then strip repack/suffix noise.
*/
private fun cleanedFallbackName(exeFile: File): String? {
val exeBase = exeFile.nameWithoutExtension
val preferFolder = EXE_NOISE_RE.containsMatchIn(exeBase) ||
@@ -293,14 +203,12 @@ object GameIdentifier {
return cleanName(raw)
}
/** Strip bracketed tags, repack-group names, engine/arch suffixes and version tokens; tidy separators. */
private fun cleanName(raw: String): String? {
var s = raw
s = s.replace(Regex("""[\[(][^\])]*[\])]"""), " ") // (…) […]
s = s.replace(Regex("""[\[(][^\])]*[\])]"""), " ")
s = VERSION_TOKEN_RE.replace(s, " ")
s = EXE_SUFFIX_RE.replace(s, " ")
s = s.replace(Regex("""[._]+"""), " ")
// Drop standalone repack-group words.
s = s.split(Regex("""[\s-]+"""))
.filter { it.isNotBlank() && it.lowercase() !in REPACK_TOKENS }
.joinToString(" ")
@@ -308,20 +216,16 @@ object GameIdentifier {
return s.ifBlank { null }
}
// ── tiny text/format helpers (regex-based → no Android/org.json dependency, unit-testable) ──
/** Read a small text file (guards against accidentally slurping a huge file). */
private fun readSmallTextFile(f: File, maxBytes: Long = 1L * 1024 * 1024): String? = try {
if (f.isFile && f.length() in 1..maxBytes) f.readText(Charsets.UTF_8) else null
} catch (_: Throwable) {
null
}
/** Value of a Valve KeyValues (.acf/.vdf) `"key" "value"` pair, first match, case-insensitive key. */
private fun vdfValue(text: String, key: String): String? =
Regex(""""${Regex.escape(key)}"\s*"([^"]*)"""", RegexOption.IGNORE_CASE).find(text)?.groupValues?.getOrNull(1)?.trim()
/** Value of a JSON `"key": "value"` pair, first match. Sufficient for the flat goggame .info files. */
private fun jsonStringValue(text: String, key: String): String? =
Regex(""""${Regex.escape(key)}"\s*:\s*"([^"\\]*(?:\\.[^"\\]*)*)"""").find(text)
?.groupValues?.getOrNull(1)?.replace("\\\"", "\"")?.replace("\\\\", "\\")?.trim()
@@ -1,6 +1,5 @@
package com.droiddeck.launcher.frontend
/** External callers can select a game, never a guest path or arbitrary Steam command. */
object GameLaunchLink {
private val idPattern = Regex("[1-9][0-9]{0,19}")
private val linkPattern = Regex("droiddeck://game/([1-9][0-9]{0,19})")
@@ -42,7 +42,6 @@ object GameShortcuts {
if (!requested) Toast.makeText(activity, R.string.game_shortcut_unsupported, Toast.LENGTH_LONG).show()
}
/** Standard shortcut picker result, understood by launchers that import Android shortcuts. */
fun result(activity: Activity, game: Library.SteamGame): Intent =
activity.getSystemService(ShortcutManager::class.java).createShortcutResultIntent(info(activity, game))
}
@@ -8,15 +8,6 @@ import com.droiddeck.launcher.stores.StoreInstallRoot
import java.io.File
import java.util.zip.CRC32
/**
* Games folders (the roots earlier builds let the user add in Steam settings) become what the
* Games tab's "Add all games in this folder" makes: one entry per game ([AddedExes]). Everything
* a game had is keyed by its own folder and stays as it was - the chosen exe, the shortcut appid,
* the name, Start in, launch options, art choices, a removal. The roots stay bound into the
* session at the same guest paths ([SessionPrefs.gameFolderBinds]), so every exe keeps its path
* inside the session and every Steam shortcut its target; they are no longer Steam libraries.
* Runs whenever saved roots remain (so twice is the same as once) and clears them after.
*/
object GamesFolderMigration {
private const val TAG = "GamesFolderMigration"
@@ -26,7 +17,6 @@ object GamesFolderMigration {
if (dirs.isEmpty()) return
val roots = legacyRoots(SessionPrefs.gameFolderBinds(context).map { it.first } + dirs)
.filter { root -> root.host.path in dirs }
// The binds first: a game's guest path (and with it the shortcut's appid) depends on them.
SessionPrefs.setGameFolderBinds(context, SessionPrefs.gameFolderBinds(context) + roots.map { it.host.path to it.guest })
val removed = SessionPrefs.removedAddedGames(context).toSet()
val entries = AddedExes.list(context).map { it.folder }.toMutableSet()
@@ -50,10 +40,6 @@ object GamesFolderMigration {
SessionPrefs.setGamesFoldersMigrated(context)
}
/**
* The guest paths earlier builds gave Games folders: /root/Games/<folder name>, with a short
* hash of the host path when two share a name. Kept exactly, so nothing moves in the session.
*/
internal fun legacyRoots(paths: List<String>): List<AddedGames.Root> {
val hosts = paths.distinct().map { File(it) }
val names = hosts.groupingBy { it.name.lowercase() }.eachCount()
@@ -8,42 +8,24 @@ import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.session.SecondaryLibrary
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. */
/**
* [art] is the portrait capsule; [hero] the wide banner Steam shows above a game's page, when
* the client has cached one. [lastPlayed] is Steam's own "LastPlayed" (unix seconds), 0 = never.
*/
class SteamGame(
val appId: Int, val name: String, val art: File?, val library: String, val gameId: Long = appId.toLong(),
val hero: File? = null, val lastPlayed: Long = 0L,
val gameFiles: File? = null, val protonPrefix: File? = null,
val icon: File? = null,
/** Where the game came from: [SOURCE_STEAM], a store's id (gog, epic, amazon) or [ADDED] for a folder the user added. */
val source: String = SOURCE_STEAM,
/** The store's own id for a store install; null otherwise. */
val storeId: String? = null,
) {
/** Decimal form used by Steam links and Android shortcuts, including unsigned shortcut ids. */
val gameIdString: String get() = java.lang.Long.toUnsignedString(gameId)
/** Key used by per-game environment and Windows-component profiles. */
val profileKey: String get() = if (library == ADDED) java.lang.Integer.toUnsignedString(appId) else appId.toString()
}
/** The [SteamGame.library] of a game added to the library rather than installed by Steam, and the [SteamGame.source] of a plain added folder. */
const val ADDED = "added"
/** The [SteamGame.source] of a title Steam itself installed. */
const val SOURCE_STEAM = "steam"
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 shown name of [system] when it is words rather than a platform name, else 0. */
val systemRes: Int get() = if (id == "retroarch") R.string.content_system_many else 0
/** The emulator's own icon, bundled (the runtime keeps them as theme SVGs the app cannot draw). */
val iconRes: Int get() = when (id) {
"rpcs3" -> R.drawable.emu_rpcs3; "armsx2" -> R.drawable.emu_pcsx2; "dolphin" -> R.drawable.emu_dolphin
"duckstation" -> R.drawable.emu_duckstation; "melonds" -> R.drawable.emu_melonds; "cemu" -> R.drawable.emu_cemu
@@ -51,34 +33,33 @@ object Library {
}
}
/** The client's own tools and runtimes live in steamapps beside the games; they are not titles. */
private val NOT_GAMES = setOf(
858280, // Proton 3.7
961940, // Proton 3.16
993090, // Lossless Scaling
1054830, // Proton 4.2
1070560, // Steam Linux Runtime 1.0
1113280, // Proton 4.11
1245040, // Proton 5.0
1391110, // Steam Linux Runtime 2.0
1420170, // Proton 5.13
1493710, // Proton Experimental
1580130, // Proton 6.3
1628350, // Steam Linux Runtime 3.0
1887720, // Proton 7
2180100, // Proton Hotfix
228980, // Steamworks Common Redistributables
2348590, // Proton 8
2805730, // Proton 9
3029110, // Lepton
3127680, // FEX
3658110, // Proton 10
4183110, // Steam Linux Runtime 4.0
4185400, // Steam Linux Runtime 4.0 for ARM64
4427310, // Proton Experimental for ARM64
4628710, // Proton 11 / Proton Next
4628740, // Proton 11 for ARM64
4690330, // Legacy Steam Runtime
858280,
961940,
993090,
1054830,
1070560,
1113280,
1245040,
1391110,
1420170,
1493710,
1580130,
1628350,
1887720,
2180100,
228980,
2348590,
2805730,
3029110,
3127680,
3658110,
4183110,
4185400,
4427310,
4628710,
4628740,
4690330,
)
private val STEAM_CAPSULES = listOf("library_capsule.jpg", "library_600x900.jpg")
private val STEAM_HEROES = listOf("library_hero.jpg")
@@ -88,7 +69,6 @@ object Library {
private val LAST_PLAYED = Regex("^\\s*\"LastPlayed\"\\s*\"(\\d+)\"", RegexOption.MULTILINE)
private val INSTALL_DIR = Regex("^\\s*\"installdir\"\\s*\"([^\"]*)\"", RegexOption.MULTILINE)
/** Steam's library roots visible to this launcher: its private default plus the selected library. */
private fun steamLibraries(context: Context): List<Pair<File, String>> {
val root = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam")
return listOfNotNull(
@@ -97,7 +77,6 @@ object Library {
) + GameStorage.gamesFolderLibraries(context).map { it.host to it.label }
}
/** Proton keeps each game's prefix below compatdata/<appid>/pfx in a Steam library. */
fun protonPrefix(
context: Context, appId: Long, preferredLibrary: File? = null,
libraries: List<File> = steamLibraries(context).map { it.first },
@@ -130,14 +109,10 @@ object Library {
val text = try { manifest.readText() } catch (e: Exception) { if (strictRead) throw e; 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 art = steamCacheImage(cache, appId, STEAM_CAPSULES)
val hero = steamCacheImage(cache, appId, STEAM_HEROES)
val lastPlayed = LAST_PLAYED.find(text)?.groupValues?.get(1)?.toLongOrNull() ?: 0L
// App manifests are Valve KeyValues (VDF) files. installdir is one folder
// below steamapps/common; only expose it when the directory exists and the
// manifest value cannot escape that directory.
val installDir = INSTALL_DIR.find(text)?.groupValues?.get(1)?.trim()
?.takeIf { it.isNotEmpty() && it != "." && it != ".." && '/' !in it && '\\' !in it }
val gameFiles = installDir?.let { File(steamapps, "common/$it").takeIf(File::isDirectory) }
@@ -153,14 +128,11 @@ object Library {
return out.values.toList()
}
/** The same installed-game inventory used for links, shortcuts and file exports. */
/** [added]: the added games when the caller has just scanned them, so they are not scanned again. */
fun launchableGames(context: Context, strictRead: Boolean = false, added: List<AddedGames.Game>? = null): List<SteamGame> {
val roots = steamLibraries(context).map { it.first }
return (steamGames(context, strictRead) + (added ?: AddedGames.scan(context)).map { g -> addedGame(context, g, roots) }).distinctBy { it.gameId }
}
/** One added game as the Games tab lists it; [roots] the Steam libraries, for its Proton prefix. */
fun addedGame(context: Context, g: AddedGames.Game, roots: List<File> = steamLibraries(context).map { it.first }): SteamGame =
AddedGameArt.resolve(context, g).let { art ->
SteamGame(
@@ -172,7 +144,6 @@ object Library {
)
}
/** Steam stores current library art inside hash-named folders under the app's cache dir. */
private fun steamCacheImage(cache: File, appId: Int, names: List<String>): File? {
val appDir = File(cache, appId.toString())
val dirs = listOf(appDir) + appDir.listFiles()
@@ -182,12 +153,9 @@ object Library {
.firstOrNull { it.isFile && it.length() > 0L }
}
/** [atPanel]: frames cheap enough to draw at the panel's own size (see [drawsAtPanel]). */
private class Spec(val id: String, val name: String, val system: String, val program: String, val folders: List<String>, val exts: Set<String>, val atPanel: Boolean = false)
private val specs = listOf(
Spec("rpcs3", "RPCS3", "PS3", "/opt/appimages/rpcs3.AppImage", listOf("ps3"), setOf("iso")),
// PS2: ARMSX2, the PCSX2 fork with ARM64 recompilers. Upstream PCSX2 interprets the PS2's
// CPUs on ARM64 (NFS Underground 2: 17 fps against ARMSX2's full 60), so it is not offered.
Spec("armsx2", "ARMSX2", "PS2", "/opt/appimages/armsx2.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")),
@@ -196,73 +164,46 @@ object Library {
Spec("ppsspp", "PPSSPP", "PSP", "/usr/bin/PPSSPPSDL", listOf("psp"), setOf("iso", "cso", "pbp", "chd")),
Spec("retroarch", "RetroArch", "many systems", "/usr/bin/retroarch", emptyList(), emptySet()),
)
/**
* A dump's file name as a title: its tags - (USA), (En,Fr,Es,Pt), [!], (v1.01) - identify the
* file and are dropped for reading ("Tomb Raider (USA) (En,Fr,Es,Pt)" -> "Tomb Raider"). The
* file keeps them, and the cover lookup still uses them.
*/
private fun displayTitle(name: String): String =
name.replace(Regex("\\s*[(\\[][^)\\]]*[)\\]]"), "").trim().ifEmpty { name }
/** Every system folder name the specs claim, so a loose-file scan of the root skips them. */
private val systemFolders: Set<String> by lazy { specs.flatMap { it.folders }.toSet() }
private val installedIds = mapOf(
"rpcs3" to "rpcs3", "armsx2" to "armsx2", "dolphin" to "dolphin", "duckstation" to "duckstation",
"melonds" to "melonds", "cemu" to "cemu", "ppsspp" to "emulators", "retroarch" to "emulators",
)
/** The emulator's name for a program path from the rail ("ARMSX2"), or null. */
fun nameForProgram(program: String?): String? =
if (program == com.droiddeck.launcher.runtime.FlatpakManager.LAUNCHER || program == com.droiddeck.launcher.runtime.AppImageManager.LAUNCHER ||
program == com.droiddeck.launcher.runtime.UserApps.SCRIPT_LAUNCHER) {
com.droiddeck.launcher.session.SessionState.programArgs.firstOrNull()?.let { flatpakNames[it] ?: it.substringAfterLast('.') }
} else specs.firstOrNull { it.program == program }?.name
/** Added apps' names by Flatpak id or directory, as launched: the session only knows that. */
val flatpakNames = java.util.concurrent.ConcurrentHashMap<String, String>()
/**
* Whether a program from the rail runs at the panel's own resolution rather than the session's
* 720p default. melonDS draws two 256x192 screens on the CPU: the panel's size costs it
* nothing, and 720p scaled up to the panel blurs the sharp pixels its screen layout is set
* up for (droiddeck-pad-defaults).
*/
fun drawsAtPanel(program: String?): Boolean = specs.any { it.program == program && it.atPanel }
/** 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, and up to three folders
// inside them - a dump usually comes as a folder named for the game with the image
// inside it, and people sort those into folders of their own (ps2/games/<game>/).
// The root itself only one deep, for a file left loose there.
val systemDirs = romsRoot.listFiles { f -> f.isDirectory && f.name.lowercase() in spec.folders }.orEmpty().toList()
val dirs = LinkedHashSet<File>()
// A BIOS folder holds the console's firmware, not games (psx/bios/SCPH1001.BIN).
for (top in systemDirs) top.walkTopDown().maxDepth(3).onEnter { it.name.lowercase() !in firmwareFolders }
.filter { it.isDirectory }.forEach { dirs.add(it) }
dirs.add(romsRoot)
// ...and not into another system's folder: a PS3 .iso in ps3/ is not a PS2 game.
romsRoot.listFiles { f -> f.isDirectory && f.name.lowercase() !in systemFolders }?.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(displayTitle(dir.name), dir, "/root/ROMs/$rel", spec.id,
// The dump carries its own art, as an installed package does.
art = File(dir, "PS3_GAME/ICON0.PNG").takeIf { it.isFile }))
continue
}
val files = dir.listFiles()?.sortedBy { it.name.lowercase() }.orEmpty()
// A disc sheet (.cue, .gdi) names its track files and a playlist (.m3u) its
// discs: the sheet is the game, what it names is part of it. A .bin beside a
// .cue of the same name is a track even when the sheet can't be read.
val parts = files.filter { it.isFile && it.extension.lowercase() in sheetExts }.flatMap(::sheetParts).toSet()
files.forEach { f ->
val ext = f.extension.lowercase()
@@ -275,7 +216,6 @@ object Library {
}
}
if (spec.id == "rpcs3") games.addAll(rpcs3Installed(context))
// A cover found for the game before (CoverArt) where it has no art of its own.
val withArt = games.map { g -> if (g.art != null) g else CoverArt.cached(context, g)?.let { Rom(g.name, g.hostPath, g.guestPath, g.emulatorId, it) } ?: g }
Emulator(spec.id, spec.name, spec.system, spec.program, installedPackage(installedIds.getValue(spec.id)), withArt)
}
@@ -284,27 +224,19 @@ object Library {
private val firmwareFolders = setOf("bios", "firmware")
private val sheetExts = setOf("cue", "gdi", "m3u")
/** The file names (lower case) a .cue, .gdi or .m3u refers to, from its own folder. */
private fun sheetParts(sheet: File): List<String> = runCatching {
if (sheet.length() > 64 * 1024) return emptyList()
sheet.readLines().mapNotNull { line ->
val t = line.trim()
when (sheet.extension.lowercase()) {
// FILE "Tekken 3 (USA) (Track 1).bin" BINARY
"cue" -> Regex("^FILE\\s+\"([^\"]+)\"", RegexOption.IGNORE_CASE).find(t)?.groupValues?.get(1)
?: Regex("^FILE\\s+(\\S+)", RegexOption.IGNORE_CASE).find(t)?.groupValues?.get(1)
// 1 0 4 2352 "track01.bin" 0 / 1 0 4 2352 track01.bin 0
"gdi" -> Regex("\"([^\"]+)\"").find(t)?.groupValues?.get(1) ?: t.split(Regex("\\s+")).getOrNull(4)
else -> t.takeIf { it.isNotEmpty() && !it.startsWith("#") }
}
}.map { File(it.replace('\\', '/')).name.lowercase() }
}.getOrDefault(emptyList())
/**
* 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 ->
@@ -312,7 +244,6 @@ object Library {
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",
@@ -320,7 +251,6 @@ object Library {
} ?: 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 {
@@ -337,7 +267,7 @@ object Library {
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)
if (fmt == 0x0204 || fmt == 0x0004) {
val start = data + dataOff
val end = minOf(b.size, start + len)
var stop = start
@@ -346,38 +276,21 @@ object Library {
}
}
} 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)
// Straight into the game in its controller-driven full-screen UI (first-time setup there
// too), and gone when the game is quit from its pause menu (guide button): -batch.
"armsx2" -> listOf("-batch", "-bigpicture", "-fullscreen", "--", guestPath)
// DuckStation shares PCSX2's flags (src/duckstation-qt/qthost.cpp): the same launch and exit.
"duckstation" -> listOf("-batch", "-bigpicture", "-fullscreen", "--", guestPath)
// Dolphin: full screen, drawn inside its own main window, without its "stop the emulation?"
// question; no warning boxes either, which wait for a click a controller cannot give
// (they still go to Dolphin's log). The guide button is Dolphin's Toggle Fullscreen hotkey
// (droiddeck-pad-defaults), which shows Dolphin's window and its settings - so no -b, which
// hides that window; closing Dolphin ends the session. Under gamescope Dolphin does not
// always see its window as focused, and by default both its hotkeys and the game's
// controller then stop: HotkeysRequireFocus off, BackgroundInput on. -C sets a Dolphin.ini
// value for this run only, so Dolphin started from the desktop keeps its own settings.
"dolphin" -> listOf(
"-C", "Dolphin.Display.Fullscreen=True", "-C", "Dolphin.Display.RenderToMain=True",
"-C", "Dolphin.Interface.ConfirmStop=False", "-C", "Dolphin.Interface.UsePanicHandlers=False",
"-C", "Dolphin.General.HotkeysRequireFocus=False", "-C", "Dolphin.Input.BackgroundInput=True",
"-e", guestPath,
)
// Full screen (LaunchSettings.cpp -f); the settings seed keeps the Getting Started
// dialog away (droiddeck-pad-defaults).
"cemu" -> listOf("-f", "-g", guestPath)
// Full screen (CLI.cpp --fullscreen); the guide button leaves it for melonDS's menus and
// comes back (HK_FullscreenToggle, droiddeck-pad-defaults).
"melonds" -> listOf("-f", guestPath)
else -> listOf(guestPath)
}
@@ -6,11 +6,6 @@ import org.json.JSONArray
import org.json.JSONObject
import java.io.File
/**
* The last game list the front end showed, kept in the app's files so the next start draws the
* Steam wall on its first frame. Building the list reads every manifest and walks the added-games
* folders, which can take a second or more; the fresh list replaces this one when it is ready.
*/
object LibraryCache {
private const val TAG = "LibraryCache"
private fun file(context: Context) = File(context.filesDir, "library-cache.json")
@@ -3,27 +3,11 @@ package com.droiddeck.launcher.frontend
import java.io.File
import java.io.RandomAccessFile
/**
* Reads the StringFileInfo strings (ProductName, FileDescription, …) out of the
* VS_VERSION_INFO resource embedded in a Windows PE executable (.exe).
*
* Walks the PE resource directory to the first RT_VERSION resource — the same
* navigation [com.droiddeck.launcher.files.PeIconExtractor] uses for icons — then parses the alignment-heavy
* VS_VERSIONINFO → StringFileInfo → StringTable → String tree by hand.
*
* Everything is best-effort: any malformed / oversized / unsupported input returns
* null (or an empty map). No allocation beyond the single resource blob.
*/
object PeVersionInfo {
private const val RT_VERSION = 16
private const val MAX_RES_SECTION = 64 * 1024 * 1024 // don't slurp absurd resource sections
private const val MAX_RES_SECTION = 64 * 1024 * 1024
/**
* Returns the StringFileInfo key→value map (e.g. `"ProductName" -> "Palworld"`),
* or null if the file has no readable version resource. Keys are the raw
* VS_VERSIONINFO names; look up [productName]/[fileDescription] for the common ones.
*/
fun read(file: File): Map<String, String>? = try {
RandomAccessFile(file, "r").use { raf ->
val blob = versionResourceBytes(raf) ?: return@use null
@@ -33,13 +17,6 @@ object PeVersionInfo {
null
}
/**
* Best display name from a version map. ProductName is usually the cleanest title, but is
* sometimes an internal abbreviation (e.g. God of War ships ProductName "GoW" while
* FileDescription is "God of War"). When ProductName is a single spaceless token and
* FileDescription is a normal multi-word title, prefer FileDescription. Trimmed; null if
* neither is meaningful.
*/
fun bestName(map: Map<String, String>?): String? {
if (map == null) return null
val product = map["ProductName"]?.trim()?.takeIf { it.isNotEmpty() }
@@ -52,15 +29,14 @@ object PeVersionInfo {
return product ?: desc
}
// ── locate the RT_VERSION resource blob (mirrors PeIconExtractor's navigation) ──
private fun versionResourceBytes(raf: RandomAccessFile): ByteArray? {
val dos = read(raf, 0, 0x40) ?: return null
if (u8(dos, 0) != 0x4D || u8(dos, 1) != 0x5A) return null // "MZ"
if (u8(dos, 0) != 0x4D || u8(dos, 1) != 0x5A) return null
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"
if (u8(coff, 0) != 0x50 || u8(coff, 1) != 0x45 || u8(coff, 2) != 0 || u8(coff, 3) != 0) return null
val numSections = u16(coff, 6)
val sizeOpt = u16(coff, 20)
if (numSections <= 0 || numSections > 96 || sizeOpt <= 0) return null
@@ -68,8 +44,8 @@ object PeVersionInfo {
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
val ddOff = if (magic == 0x20B) 112 else 96
val resDirEntry = ddOff + 2 * 8
if (resDirEntry + 8 > opt.size) return null
val resRVA = u32(opt, resDirEntry).toInt()
val resSize = u32(opt, resDirEntry + 4).toInt()
@@ -105,7 +81,6 @@ object PeVersionInfo {
return dataEntryBytes(res, verData, secVA)
}
/** 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)
@@ -123,7 +98,6 @@ object PeVersionInfo {
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
@@ -137,7 +111,6 @@ object PeVersionInfo {
}
}
/** 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()
@@ -147,17 +120,11 @@ object PeVersionInfo {
return res.copyOfRange(start, start + size)
}
// ── VS_VERSIONINFO tree parse ──
//
// Every node is: WORD wLength, WORD wValueLength, WORD wType, WCHAR szKey[],
// then (32-bit aligned) an optional Value, then (32-bit aligned) child nodes.
// We only care about: VS_VERSIONINFO → StringFileInfo → StringTable → String.
private fun parseStringFileInfo(b: ByteArray): Map<String, String> {
val out = LinkedHashMap<String, String>()
if (b.size < 6) return out
val rootLen = minOf(u16(b, 0), b.size)
// VS_VERSION_INFO header: skip szKey "VS_VERSION_INFO" then the FIXEDFILEINFO value.
val rootValLen = u16(b, 2)
var pos = align4(6 + (utf16zLen(b, 6) + 1) * 2)
pos = align4(pos + rootValLen)
@@ -173,7 +140,6 @@ object PeVersionInfo {
return out
}
/** Iterate the StringTable children inside a StringFileInfo block [start, end). */
private fun parseTables(b: ByteArray, start: Int, end: Int, out: MutableMap<String, String>) {
var p = align4(start + 6 + (utf16zLen(b, start + 6) + 1) * 2)
while (p + 6 <= end) {
@@ -185,7 +151,6 @@ object PeVersionInfo {
}
}
/** Iterate the String children inside a StringTable block [start, end). */
private fun parseStrings(b: ByteArray, start: Int, end: Int, out: MutableMap<String, String>) {
var q = align4(start + 6 + (utf16zLen(b, start + 6) + 1) * 2)
while (q + 6 <= end) {
@@ -202,11 +167,9 @@ object PeVersionInfo {
}
}
// ── little-endian / UTF-16 readers ──
private fun align4(x: Int): Int = (x + 3) and 3.inv()
/** Number of UTF-16 code units before the null terminator starting at [off]. */
private fun utf16zLen(b: ByteArray, off: Int): Int {
var i = off
while (i + 1 < b.size) {
@@ -216,7 +179,6 @@ object PeVersionInfo {
return (i - off) / 2
}
/** Read a null-terminated UTF-16LE string starting at [off], not reading past [limit]. */
private fun utf16z(b: ByteArray, off: Int, limit: Int = b.size): String {
val sb = StringBuilder()
var i = off
@@ -3,18 +3,9 @@ package com.droiddeck.launcher.frontend
import org.json.JSONObject
import java.io.File
/**
* Which catalog components a game's prefix already has from elsewhere - a real installer, the game,
* the user - so the list can say so instead of recommending them again. Bannerlator's detector,
* on DroidDeck's compatdata/<id>: only markers absent from a fresh Proton prefix count (OpenAL32,
* Mono, PhysX, Games for Windows Live); msvcp140, d3dx9 and the like ship with Proton and cannot
* tell. Files DroidDeck put there itself (droiddeck-wincomponents' state) are not counted.
* Pure filesystem reads; never throws.
*/
object PrefixInstalledDetector {
private const val STATE = ".droiddeck-wincomponents.json"
/** Detector names (oalinst, mono, physx, XLiveRedist) present in [compat]/pfx. */
fun detect(compat: File?): Set<String> = try {
val pfx = compat?.let { File(it, "pfx") }
if (pfx == null || !pfx.isDirectory) emptySet() else {
@@ -38,7 +29,6 @@ object PrefixInstalledDetector {
emptySet()
}
/** Windows names ignore case; the prefix's folder may spell them either way. */
private fun fileIgnoringCase(pfx: File, rel: String): Boolean {
val target = File(pfx, rel)
return target.parentFile?.listFiles()?.any { it.isFile && it.name.equals(target.name, ignoreCase = true) } == true
@@ -7,17 +7,10 @@ import com.droiddeck.launcher.session.GameStorage
import com.droiddeck.launcher.session.SessionState
import java.io.File
/**
* A Steam game whose download finishes during a session, noticed by its appmanifest (a new one,
* or StateFlags turning to 4, fully installed) with a light look every five seconds while the
* session runs, and handed to [AutoComponents] as a single job that may run in the session, so its
* Windows components are in place when the user plays it right after the download.
*/
object SessionInstalls {
private const val TAG = "SessionInstalls"
private const val POLL_MS = 5_000L
/** One appmanifest as read: the app, its name and folder, whether it is fully installed. */
class Manifest(val appId: Int, val name: String, val installDir: String, val installed: Boolean, val steamapps: File)
private val APPID = Regex("\"appid\"\\s*\"(\\d+)\"", RegexOption.IGNORE_CASE)
@@ -32,16 +25,11 @@ object SessionInstalls {
STATE.find(text)?.groupValues?.get(1)?.toIntOrNull() == 4, file.parentFile!!)
}.getOrNull()
/** The libraries the session's client installs to, as host folders. */
internal fun steamappsDirs(context: Context): List<File> = listOfNotNull(
File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/steamapps"),
GameStorage.effective(context)?.let { File(it.path, "steamapps") },
).filter { it.isDirectory }
/**
* Keeps what the libraries hold between looks: a manifest re-read only when its time changed.
* [poll] returns the apps that became fully installed since the last look (none on the first).
*/
internal class Watch(private val dirs: () -> List<File>) {
private val seen = HashMap<String, Pair<Long, Manifest?>>()
private var first = true
@@ -60,22 +48,16 @@ object SessionInstalls {
}
}
/** A finished install as the Games tab would list it. */
internal fun gameOf(m: Manifest): Library.SteamGame =
Library.SteamGame(m.appId, m.name.ifEmpty { m.appId.toString() }, null, m.steamapps.parentFile?.path ?: "steam",
gameFiles = File(m.steamapps, "common/${m.installDir}"), source = Library.SOURCE_STEAM)
/**
* Looks every five seconds while the session runs, on a thread of its own at background
* priority; each finished install becomes one job for its Windows components.
*/
fun watch(context: Context) {
val app = context.applicationContext
Thread({
android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND)
val watch = Watch { steamappsDirs(app) }
try {
// The session is still starting when this is called: up to two minutes for it.
var waited = 0L
while (!SessionState.running && waited < 120_000L) { Thread.sleep(POLL_MS); waited += POLL_MS }
watch.poll()
@@ -12,25 +12,16 @@ import java.io.RandomAccessFile
import java.nio.ByteBuffer
import java.nio.ByteOrder
/**
* Steam's own data for an app, from the client in the runtime: its app-info cache
* (Steam/appcache/appinfo.vdf, the PICS data the client keeps for every app it has seen). What is
* read is which Steamworks Shared depots (the VC++, DirectX... redistributables of app 228980) the
* app's depots point at, and its name. Kept per appid in the app's files, so it works offline; an
* app the client has not seen is looked for again after a week.
*/
object SteamAppInfo {
private const val TAG = "SteamAppInfo"
private const val CACHE = "steam-appinfo.json"
private const val RETRY_AFTER_MS = 7L * 24 * 3600 * 1000
/** The Steamworks Shared app the redistributable depots belong to. */
const val SHARED_APP = "228980"
class Info(val name: String, val sharedDepots: List<String>)
fun appinfoFile(context: Context) = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/appcache/appinfo.vdf")
/** The shared depots for [appId]: from the cache, else the client's app-info file; null when unknown. */
@Synchronized
fun info(context: Context, appId: Int, appinfo: File = appinfoFile(context)): Info? {
val cacheFile = AtomicFile(File(context.filesDir, CACHE))
@@ -40,13 +31,10 @@ object SteamAppInfo {
val known = cache.optJSONObject(appId.toString())
known?.let { o ->
if (!o.optBoolean("miss")) return Info(o.optString("name"), o.optJSONArray("depots").strings())
// A miss is read again when the client has written its cache since (the user may have
// looked at the app in Steam), else a week later.
if (now - o.optLong("at") < RETRY_AFTER_MS && o.optLong("mtime") == mtime) return null
}
val read = runCatching { read(appinfo, appId) }.onFailure { Log.w(TAG, "appinfo: ${it.javaClass.simpleName}") }.getOrNull()
val entry = JSONObject().put("at", now).put("mtime", mtime)
// When Steam was last asked anonymously ([lookup]), kept across re-reads of the file.
known?.optLong("picsAt")?.takeIf { it > 0 }?.let { entry.put("picsAt", it) }
if (read == null) entry.put("miss", true) else entry.put("name", read.name).put("depots", JSONArray(read.sharedDepots))
cache.put(appId.toString(), entry)
@@ -55,14 +43,9 @@ object SteamAppInfo {
return read
}
/** Steam asked anonymously ([SteamPics]); a test stands in for it. */
@androidx.annotation.VisibleForTesting
internal var pics: (List<Int>) -> Map<Int, Info?>? = { SteamPics.lookup(it) }
/**
* Of [appIds], those neither the client's cache (appinfo.vdf, read first: free) nor an earlier
* answer has, and that Steam was not asked about anonymously in the past week.
*/
fun needLookup(context: Context, appIds: List<Int>): List<Int> {
val wanted = appIds.distinct().filter { it > 0 && info(context, it) == null }
if (wanted.isEmpty()) return emptyList()
@@ -71,11 +54,6 @@ object SteamAppInfo {
return wanted.filter { now - (cache.optJSONObject(it.toString())?.optLong("picsAt") ?: 0L) >= RETRY_AFTER_MS }
}
/**
* [appIds] the client never saw, asked of Steam anonymously in one connection ([SteamPics], in
* batches) and every answer kept like the client's: an app's depots and name, or a miss tried
* again in a week. False when nothing needed asking or Steam could not be reached. Blocking.
*/
@Synchronized
fun lookup(context: Context, appIds: List<Int>): Boolean {
val need = needLookup(context, appIds)
@@ -96,7 +74,6 @@ object SteamAppInfo {
return true
}
/** What is kept for [appId]: "hit", "miss" or "none" (part of a game's list fingerprint). */
fun state(context: Context, appId: Int): String = cache(context).optJSONObject(appId.toString())?.let { if (it.optBoolean("miss")) "miss" else "hit" } ?: "none"
private fun cache(context: Context): JSONObject =
@@ -104,10 +81,6 @@ object SteamAppInfo {
private fun JSONArray?.strings(): List<String> = if (this == null) emptyList() else (0 until length()).map { optString(it) }
/**
* [appId]'s entry in an appinfo.vdf (versions 27, 28 and 29, the last with its keys in a string
* table), or null when the file does not have it.
*/
internal fun read(file: File, appId: Int): Info? {
if (!file.isFile) return null
RandomAccessFile(file, "r").use { raf ->
@@ -181,7 +154,6 @@ object SteamAppInfo {
return String(bytes, Charsets.UTF_8)
}
/** One binary key-value map, to its end marker; keys by name, or by index into [strings]. */
private fun readMap(b: ByteBuffer, strings: List<String>?): Map<String, Any> {
val out = LinkedHashMap<String, Any>()
while (b.hasRemaining()) {
@@ -11,15 +11,6 @@ import java.net.HttpURLConnection
import java.net.URL
import java.net.URLEncoder
/**
* SteamGridDB, the art source after Steam's store: a game by its Steam appid, else by a search
* whose result must carry the same name, then its best-rated grids, heroes, logos and icons.
*
* The API key: the user's own (Steam settings › Games), sealed with [CredentialCipher] in the
* app's files, else the one the build carries (`BuildConfig.SGDB_API_KEY`, from a CI secret), else
* none, and then this step is skipped. The key travels only in the Authorization header and is
* never logged.
*/
object SteamGridDb {
private const val TAG = "SteamGridDb"
private const val API = "https://www.steamgriddb.com/api/v2"
@@ -31,17 +22,14 @@ object SteamGridDb {
private fun keyFile(context: Context) = File(context.filesDir, "sgdb/key.json")
/** The key the build carries, or "" (a build without the secret, a fork's PR build). */
fun builtInKey(): String = runCatching {
Class.forName("com.droiddeck.launcher.BuildConfig").getField("SGDB_API_KEY").get(null) as? String
}.getOrNull().orEmpty()
/** The user's key wins, then the build's; "" when there is neither. */
fun pick(user: String, builtIn: String): String = user.trim().ifEmpty { builtIn.trim() }
fun key(context: Context): String = pick(userKey(context), builtInKey())
/** The key the user entered, or "". */
@Synchronized
fun userKey(context: Context): String {
val f = keyFile(context)
@@ -56,7 +44,6 @@ object SteamGridDb {
}
}
/** Saves the user's key sealed (plain only where the Keystore does not work); "" clears it. */
@Synchronized
fun setUserKey(context: Context, key: String) {
val f = keyFile(context)
@@ -75,7 +62,6 @@ object SteamGridDb {
if (!tmp.renameTo(f)) { f.delete(); tmp.renameTo(f) }
}
/** The SteamGridDB game id for [steamAppId], else for a search on [name] that returns the same name; null when neither. */
fun gameId(key: String, steamAppId: Int?, name: String): Int? {
if (steamAppId != null) {
json(key, "$API/games/steam/$steamAppId")?.optJSONObject("data")?.optInt("id")?.takeIf { it > 0 }?.let { return it }
@@ -85,16 +71,11 @@ object SteamGridDb {
return match(name, (0 until results.length()).map { results.getJSONObject(it) }.map { it.optInt("id") to it.optString("name") })
}
/** The id of the first result whose name matches [name] ([AddedGameArt.nameMatch]); no blind first pick. */
internal fun match(name: String, results: List<Pair<Int, String>>): Int? =
results.map { (id, got) -> id to AddedGameArt.nameMatch(name, got) }
.filter { it.second > 0 && it.first > 0 }
.maxByOrNull { it.second }?.first
/**
* Fetches what is missing into [cache] under the names Steam's art uses there (p.jpg,
* header.jpg, hero.jpg, logo.png) and the icon as icon-sgdb.png. True when anything arrived.
*/
fun download(key: String, id: Int, cache: File): Boolean {
var got = false
for ((path, local) in listOf(
@@ -116,7 +97,6 @@ object SteamGridDb {
return got
}
/** The best-scored [limit] images for [slot] of game [id], as (thumbnail, full image) URLs. */
fun images(key: String, id: Int, slot: AddedGameArt.Slot, limit: Int): List<Pair<String, String>> {
val path = when (slot) {
AddedGameArt.Slot.COVER -> "grids/game/$id?dimensions=600x900&$QUERY"
@@ -128,20 +108,17 @@ object SteamGridDb {
return ranked(items, pngOnly = slot == AddedGameArt.Slot.LOGO || slot == AddedGameArt.Slot.ICON).take(limit)
}
/** [items] best-scored first, as (thumbnail, full image) URLs; for a .png slot only PNGs. */
internal fun ranked(items: JSONArray, pngOnly: Boolean): List<Pair<String, String>> =
(0 until items.length()).map { items.getJSONObject(it) }
.filter { it.optString("url").startsWith("https://") && (!pngOnly || it.optString("mime") == "image/png" || it.optString("url").endsWith(".png", true)) }
.sortedByDescending { it.optInt("score", 0) }
.map { (it.optString("thumb").takeIf { t -> t.startsWith("https://") } ?: it.optString("url")) to it.optString("url") }
/** The highest-scored image's URL; for a .png slot only a PNG. */
internal fun best(items: JSONArray, pngOnly: Boolean): String? =
(0 until items.length()).map { items.getJSONObject(it) }
.filter { it.optString("url").startsWith("https://") && (!pngOnly || it.optString("mime") == "image/png" || it.optString("url").endsWith(".png", true)) }
.maxByOrNull { it.optInt("score", 0) }?.optString("url")
/** A GET with the key in its Authorization header; the body as JSON, or null. Logs the path only. */
private fun json(key: String, url: String): JSONObject? {
val c = URL(url).openConnection() as HttpURLConnection
c.connectTimeout = 10_000
@@ -5,20 +5,9 @@ import android.util.AtomicFile
import org.json.JSONObject
import java.io.File
/**
* Which Steam app a game added in DroidDeck is, kept once per game (by its folder) and used by
* everything that asks: its art ([AddedGameArt]) and its Windows components ([WinCompSources]),
* so the two never disagree.
*
* [Certainty.FILES]: the game's own files name the appid (steam_appid.txt, also under
* steam_settings/ or a parent folder; an emulator ini; Steam's appmanifest) - certain.
* [Certainty.NAME]: Steam's store search returned a game of the same name - a guess.
* [Certainty.NONE]: neither; a miss is tried again after a week.
*/
object SteamMatch {
enum class Certainty { FILES, NAME, NONE }
/** [source]: what gave the appid (GameIdentifier's source, or "store search"). */
class Match(val appId: Int?, val certainty: Certainty, val source: String, val checkedAt: Long)
private const val FILE = "steam-matches.json"
@@ -50,12 +39,6 @@ object SteamMatch {
try { out.write(json.toString().toByteArray()); atomic.finishWrite(out) } catch (e: Exception) { atomic.failWrite(out) }
}
/**
* The match for the game in [key] (its folder), [exe] its exe and [name] its title: its files
* first, always read again; else the one kept (a name match stays, a miss for a week); else
* [legacy], an appid an earlier build's art lookup kept; else [search] on the name, when given.
* Blocking ([search] asks the network).
*/
fun resolve(context: Context, key: String, exe: File, name: String, legacy: File? = null, search: ((String) -> Int?)? = null): Match {
val now = System.currentTimeMillis()
val identity = runCatching { GameIdentifier.identify(exe) }.getOrNull()
@@ -18,18 +18,9 @@ import java.util.zip.GZIPInputStream
import javax.net.ssl.SSLSocket
import javax.net.ssl.SSLSocketFactory
/**
* Steam's own app info (PICS) for apps the client in the runtime has never seen, asked of Steam
* anonymously: a connection to one of Steam's connection managers (the list from Steam's public
* ISteamDirectory/GetCMListForConnect, the WebSocket transport Steam's web clients use), an
* anonymous logon - no account, nothing of the user's Steam sign-in - a request for the apps'
* access tokens and then their product info, the app KeyValues read for their Steamworks Shared
* depots and name, and the connection closed. What steamcmd's anonymous `app_info_print` sees.
*/
object SteamPics {
private const val TAG = "SteamPics"
private const val CM_LIST = "https://api.steampowered.com/ISteamDirectory/GetCMListForConnect/v1/?cellid=0&format=json"
/** At most this many apps per request. */
const val BATCH = 25
private const val PROTO = 0x80000000.toInt()
private const val EMSG_MULTI = 1
@@ -41,13 +32,8 @@ object SteamPics {
private const val EMSG_INFO_REQUEST = 8903
private const val EMSG_INFO_RESPONSE = 8904
private const val PROTOCOL_VERSION = 65580
/** An anonymous user's SteamID: universe Public, account type AnonUser, instance 0. */
private const val ANON_STEAMID = (1L shl 56) or (10L shl 52)
/**
* [appIds]' info, one connection for all of them in batches of [BATCH]: each known app's
* info, null for an app Steam does not know. Null when Steam could not be reached. Blocking.
*/
fun lookup(appIds: List<Int>): Map<Int, SteamAppInfo.Info?>? {
if (appIds.isEmpty()) return emptyMap()
val host = runCatching { cmHost() }.getOrNull() ?: return null
@@ -56,7 +42,6 @@ object SteamPics {
ws.send(message(EMSG_LOGON, header(ANON_STEAMID, 0), Proto().varint(1, PROTOCOL_VERSION.toLong()).varint(7, 16).string(6, "english").bytes()))
var steamId = 0L
var session = 0
// The logon's answer (other messages before it are passed over).
loop@ while (true) for ((emsg, hdr, body) in messages(ws.receive() ?: return null)) if (emsg == EMSG_LOGON_RESPONSE) {
val h = fields(hdr); val b = fields(body)
if ((b[1]?.firstOrNull() as? Long ?: 0L) != 1L) { Log.w(TAG, "anonymous logon refused: ${b[1]}"); return null }
@@ -99,10 +84,8 @@ object SteamPics {
}
}
/** [appIds] in requests of at most [BATCH], each once. */
fun batches(appIds: List<Int>): List<List<Int>> = appIds.distinct().chunked(BATCH)
/** A connection manager for the WebSocket transport, least loaded first as Steam lists them. */
private fun cmHost(): String? {
val c = URL(CM_LIST).openConnection() as HttpURLConnection
c.connectTimeout = 10_000; c.readTimeout = 10_000
@@ -112,11 +95,9 @@ object SteamPics {
.firstOrNull { it.optString("type") == "websockets" }?.optString("endpoint")?.substringBefore(':')
}
// ---- the product info answer ----
class InfoResponse(val apps: Map<Int, SteamAppInfo.Info>, val unknown: List<Int>, val pending: Boolean)
/** A CMsgClientPICSProductInfoResponse: each app's KeyValues read, the unknown ones, whether more follows. */
@VisibleForTesting
internal fun parseInfoResponse(body: ByteArray): InfoResponse {
val f = fields(body)
@@ -132,17 +113,14 @@ object SteamPics {
return InfoResponse(apps, unknown, (f[6]?.firstOrNull() as? Long ?: 0L) != 0L)
}
/** An app's KeyValues text ("appinfo" { "common" {...} "depots" {...} }) to its name and shared depots. */
@VisibleForTesting
internal fun infoFromKeyValues(text: String): SteamAppInfo.Info? {
// The buffer ends in a NUL, kept or not by whoever handed it over.
val tree = runCatching { KeyValues(text.trimEnd('\u0000', ' ', '\n', '\r', '\t')).read() }.getOrNull() ?: return null
@Suppress("UNCHECKED_CAST")
val app = tree["appinfo"] as? Map<String, Any> ?: return null
return SteamAppInfo.infoOf(app)
}
/** Valve's text KeyValues: quoted keys and values, nested braces. */
private class KeyValues(private val s: String) {
private var i = 0
fun read(): Map<String, Any> = map(top = true)
@@ -182,7 +160,6 @@ object SteamPics {
}
}
// ---- messages ----
private fun header(steamId: Long, session: Int) = Proto().fixed64(1, steamId).varint(2, session.toLong()).bytes()
@@ -190,7 +167,6 @@ object SteamPics {
ByteBuffer.allocate(8 + header.size + body.size).order(ByteOrder.LITTLE_ENDIAN)
.putInt(emsg or PROTO).putInt(header.size).put(header).put(body).array()
/** One message off the wire as (emsg, header, body); a Multi unpacked (gunzipped when it says so) into the ones inside. */
@VisibleForTesting
internal fun messages(data: ByteArray): List<Triple<Int, ByteArray, ByteArray>> {
if (data.size < 8) return emptyList()
@@ -217,9 +193,7 @@ object SteamPics {
return out
}
// ---- protobuf, the little needed ----
/** Writes protobuf fields. */
@VisibleForTesting
internal class Proto {
private val out = ByteArrayOutputStream()
@@ -231,7 +205,6 @@ object SteamPics {
fun bytes(): ByteArray = out.toByteArray()
}
/** Reads protobuf fields: number to values (Long for varint and fixed, ByteArray for length-delimited). */
@VisibleForTesting
internal fun fields(b: ByteArray): Map<Int, List<Any>> {
val out = HashMap<Int, MutableList<Any>>()
@@ -258,16 +231,13 @@ object SteamPics {
return out
}
// ---- WebSocket over TLS, binary frames ----
private class Wss(host: String, timeoutMs: Int) : AutoCloseable {
// Made with the host name, so it goes out as SNI.
private val socket: SSLSocket = (SSLSocketFactory.getDefault().createSocket(host, 443) as SSLSocket).apply { soTimeout = timeoutMs }
private val out: OutputStream
private val input: DataInputStream
init {
// Host name checked against the certificate, as HTTPS does.
socket.sslParameters = socket.sslParameters.apply { endpointIdentificationAlgorithm = "HTTPS" }
socket.startHandshake()
out = socket.outputStream
@@ -305,7 +275,6 @@ object SteamPics {
out.write(frame.toByteArray()); out.flush()
}
/** The next binary message (fragments joined); null on close. */
fun receive(): ByteArray? {
val message = ByteArrayOutputStream()
while (true) {
@@ -2,14 +2,7 @@ package com.droiddeck.launcher.frontend
import java.io.File
/**
* What Steam itself installs alongside a game: the Steamworks Shared redistributables (app 228980)
* listed under "SharedDepots" in the game's appmanifest. Those live in Steamworks Shared rather than
* the game's folder, so the folder scan ([DependencyDetector]) cannot see them; this reads Steam's
* list instead. Depots are matched to Bannerlator's catalog names; unknown ones are left out.
*/
object SteamRedists {
/** Steamworks Shared depot -> (catalog component, what Steam calls it). 2015-2019 runtimes are one family. */
val DEPOTS = linkedMapOf(
"228981" to ("vcredist2005_dll" to "VC++ 2005"),
"228982" to ("vcredist2008_dll" to "VC++ 2008"),
@@ -25,7 +18,6 @@ object SteamRedists {
private val BLOCK = Regex("\"SharedDepots\"\\s*\\{([^}]*)\\}", RegexOption.IGNORE_CASE)
private val ENTRY = Regex("\"(\\d+)\"\\s+\"\\d+\"")
/** The game's appmanifest beside its install folder (steamapps/common/<dir> -> steamapps/). */
fun manifest(gameDir: File?, appId: Int): File? {
val steamapps = gameDir?.parentFile?.parentFile ?: return null
return File(steamapps, "appmanifest_$appId.acf").takeIf { it.isFile }
@@ -14,47 +14,28 @@ import com.droiddeck.launcher.stores.gog.GogDownloadManager
import org.json.JSONObject
import java.io.File
/**
* For a GOG or Epic game installed before its sidecar kept the store's list (GOG's build
* `dependencies`, Epic's manifest prerequisite): the list read once from the store's build
* manifest with the saved sign-in - the manifest alone, never a game file - and kept in the sidecar
* the way an install keeps it. Runs on the components' worker ([AutoComponents]). Without a
* sign-in or a network it is skipped quietly and tried again a week later.
*/
object StoreListBackfill {
private const val TAG = "StoreListBackfill"
private const val FILE = "store-list-backfill.json"
private const val RETRY_AFTER_MS = 7L * 24 * 3600 * 1000
/** The store's list for the game in a sidecar: GOG's dependency ids, or Epic's prerequisite {name, path}; null when it could not be had. */
fun interface Fetcher {
fun fetch(context: Context, sidecar: StoreGameSidecar): Map<String, String>?
}
/** The store itself, with the saved sign-in. */
internal val storeFetcher = Fetcher { context, sidecar -> fromStore(context, sidecar) }
@VisibleForTesting internal var fetcher: Fetcher = storeFetcher
/** Whether [sidecar] was written before the list was kept. */
/**
* Whether [sidecar] has no list read whole: written before the list was kept, or by a build
* that could have written an empty one for a manifest it did not read right.
*/
fun needs(sidecar: StoreGameSidecar): Boolean =
(sidecar.store == Store.GOG || sidecar.store == Store.EPIC) && WinCompSources.LIST_READ !in sidecar.extra
/**
* The list for the game in [folder], fetched and kept when its sidecar lacks one and it was not
* tried in the past week. True when the sidecar changed. Blocking (network).
*/
@Synchronized
fun fill(context: Context, folder: File): Boolean {
val sidecar = StoreGameSidecar.read(folder)?.takeIf { it.isInstalled && needs(it) } ?: return false
val tries = runCatching { JSONObject(AtomicFile(File(context.filesDir, FILE)).readFully().toString(Charsets.UTF_8)) }.getOrDefault(JSONObject())
val now = System.currentTimeMillis()
if (now - tries.optLong(folder.path, 0L) < RETRY_AFTER_MS) return false
// Offline is no try: it waits for a network rather than a week.
if (!AutoComponents.online(context)) return false
val list = runCatching { fetcher.fetch(context, sidecar) }.getOrNull()
if (list == null) {
@@ -65,7 +46,6 @@ object StoreListBackfill {
Log.i(TAG, "${sidecar.title}: the ${sidecar.store.label} list could not be had; again in a week")
return false
}
// Read fresh and written whole, as an install writes it: only the list is added.
val current = StoreGameSidecar.read(folder) ?: return false
current.copy(extra = current.extra + list + (WinCompSources.LIST_READ to "1")).write(folder)
Log.i(TAG, "backfill: ${sidecar.title} " + when (sidecar.store) {
@@ -7,35 +7,11 @@ import org.json.JSONObject
import java.io.File
import java.util.Locale
/**
* Which Windows components a game needs, from the list its source keeps - the source badge decides
* which list is trusted:
*
* - **Steam**: the Steamworks Shared redistributables Steam installs with the game (its
* appmanifest's SharedDepots, else the client's app info) - turned on by themselves.
* - **GOG**: the build manifest's `dependencies`, kept in the sidecar at install - on by themselves.
* - **Epic Games**: the manifest's prerequisite (usually UE4/UE5's prerequisite setup: VC++ and the
* DirectX June 2010 runtime), kept in the sidecar at install - on by themselves.
* - **Amazon Games**: fuel.json's PostInstall installers - on by themselves.
* - **Custom** whose files name a Steam appid ([SteamMatch], certain): Steam's list for that app -
* on by themselves. Matched by name only: the same list as Recommended. No match: the folder scan
* ([DependencyDetector]) as Recommended.
*
* Every store entry is mapped to catalog names here, in one place; one that maps to nothing is a
* suggestion under its own name. The folder scan is offered as Recommended for every game.
*/
object WinCompSources {
/** Whose list a finding came from; the reason line says it. */
enum class Origin { STEAM, GOG, EPIC, AMAZON, STEAM_NAME, FOLDER }
/**
* One thing a list names: [component] the catalog name it maps to (null: none, a suggestion),
* [original] what the list called it, [auto] whether it is turned on by itself, [args] what
* the reason line names (Steam: the label, the game, the appid).
*/
data class Finding(val component: String?, val original: String, val origin: Origin, val auto: Boolean, val args: List<String> = emptyList())
// ---- mapping tables: a store's names -> catalog components ----
private val VC_YEAR = mapOf(
"2005" to "vcredist2005", "2008" to "vcredist2008", "2010" to "vcredist2010", "2012" to "vcredist2012",
@@ -47,10 +23,6 @@ object WinCompSources {
"472" to "dotnet472", "48" to "dotnet48", "481" to "dotnet48",
)
/**
* A GOG dependency id ("MSVC2017_x64", "DirectX", "DOTNET48", "PhysX", "OpenAL", "XNA4") to its
* components; empty for one that is none of ours (ISI scripts, GOG's own helpers).
*/
fun gog(id: String): List<String> {
val key = id.uppercase(Locale.US).replace(Regex("[^A-Z0-9]"), "")
Regex("""^(?:MSVC|VCREDIST|VC)(\d{4})""").find(key)?.let { m -> return listOfNotNull(VC_YEAR[m.groupValues[1]]) }
@@ -67,40 +39,30 @@ object WinCompSources {
}
}
/** Unreal's prerequisite setup (UE4PrereqSetup_x64.exe, UEPrereqSetup_x64.exe): VC++ 2015-2022 and DirectX June 2010. */
private val UE_PREREQ = Regex("""(?i)ue\d?prereqsetup""")
/** An Epic prerequisite ([path] the installer it runs, [name] what it is called) to its components. */
fun epic(path: String, name: String): List<String> = when {
UE_PREREQ.containsMatchIn(path) || name.contains("UE4 Prerequisites", true) || name.contains("UE5 Prerequisites", true) ||
name.contains("Unreal Engine Prerequisites", true) -> listOf("vcredist2022", "d3dx9")
else -> DependencyDetector.componentsFor(path).ifEmpty { if (path.isEmpty()) gog(name) else emptyList() }
}
/** An installer a store runs after an install (Amazon's PostInstall "Command") to its components. */
fun installer(path: String): List<String> = if (UE_PREREQ.containsMatchIn(path)) listOf("vcredist2022", "d3dx9") else DependencyDetector.componentsFor(path)
/** Steamworks Shared depot ids to (component, Steam's label). */
fun steamDepots(ids: List<String>): List<Pair<String, String>> = ids.mapNotNull { SteamRedists.DEPOTS[it] }.distinctBy { it.first }
// ---- what each store left at install ----
/** Sidecar keys the store installs fill. */
const val GOG_DEPENDENCIES = "dependencies"
const val EPIC_PREREQ_PATH = "prereqPath"
const val EPIC_PREREQ_NAME = "prereqName"
/** Set beside the list when it was read whole (an empty list then means the store lists none). */
const val LIST_READ = "listRead"
/** fuel.json's PostInstall commands. */
fun amazonPostInstall(folder: File): List<String> = runCatching {
val arr = JSONObject(File(folder, "fuel.json").readText()).optJSONArray("PostInstall") ?: return emptyList()
(0 until arr.length()).mapNotNull { arr.optJSONObject(it)?.optString("Command")?.takeIf { c -> c.isNotEmpty() } }
}.getOrDefault(emptyList())
// ---- per game ----
/** Steam's list for [appId]: the local appmanifest's SharedDepots, else the client's app info. */
fun steamList(context: Context, gameDir: File?, appId: Int, gameName: String, auto: Boolean): List<Finding> {
val local = SteamRedists.detect(gameDir, appId)
val pairs = if (local.isNotEmpty()) local.map { it.componentName to it.label }
@@ -110,7 +72,6 @@ object WinCompSources {
}
}
/** Everything known for [game], blocking (files; the client's app info; no network). */
fun forGame(context: Context, game: Library.SteamGame): List<Finding> {
val folder = game.gameFiles
val out = ArrayList<Finding>()
@@ -141,8 +102,6 @@ object WinCompSources {
}
else -> {}
}
// A game added in DroidDeck (Custom, or a store's) that is a Steam app: Steam's list for it,
// on by itself when its files say so, else only recommended.
if (game.library == Library.ADDED && folder != null) SteamMatch.get(context, folder.path)?.let { match ->
val id = match.appId ?: return@let
when (match.certainty) {
@@ -151,7 +110,6 @@ object WinCompSources {
else -> {}
}
}
// The folder scan, for every game: what it bundles, as Recommended.
folder?.let { DependencyDetector.detect(it) }?.forEach { rec ->
out += Finding(rec.componentName, rec.reason, Origin.FOLDER, false, listOf(rec.reason, rec.kind.name))
}
@@ -4,20 +4,6 @@ import com.droiddeck.launcher.wayland.WaylandCompositor
import org.json.JSONObject
import kotlin.math.sqrt
/**
* Cardboard mode: the compositor draws the session as two lens-distorted eye views side by side
* (waylandcomp/src/cardboard.c), for a phone or handheld dropped into a Google Cardboard-style
* viewer. Units are the menu's own:
*
* - [ipdMm] distance between the eyes, millimetres
* - [screenWidthDm] the virtual screen's width, decimetres (40 = 4 m)
* - [screenDistanceDm] how far away it hangs, decimetres (30 = 3 m)
* - [viewer] a [Viewer] id: the lens it is drawn for
*
* [source] SCREEN shows the frame as a flat virtual screen, world-locked by the rotation sensor
* when [headTracking] is on (3DoF), with real stereo depth from the IPD. SBS takes a frame that is
* already a left/right pair (SteamVR, SBS 3D games and video) and only adds the lens.
*/
data class Cardboard(
val enabled: Boolean = false,
val source: Int = SOURCE_SCREEN,
@@ -29,12 +15,6 @@ data class Cardboard(
) {
val lens: Viewer get() = Viewer.byId(viewer)
/**
* Hands the settings to the compositor. [panelWidthMm] x [panelHeightMm] is the physical size of
* the panel the eyes are drawn on (0 = unknown). The width decides how far each lens centre sits
* from its viewport's centre, so the two pictures line up with the viewer's lenses; the height,
* seen through the lens from its focal distance, is the field of view the distortion works in.
*/
fun push(panelWidthMm: Float, panelHeightMm: Float) {
val l = lens
WaylandCompositor.nativeSetCardboard(enabled, source, ipdMm / 1000f, screenDistanceDm / 10f,
@@ -45,18 +25,10 @@ data class Cardboard(
.put("enabled", enabled).put("source", source).put("viewer", viewer).put("ipdMm", ipdMm)
.put("screenWidthDm", screenWidthDm).put("screenDistanceDm", screenDistanceDm).put("headTracking", headTracking)
/**
* A lens the eyes can be drawn for: its distortion (Cardboard viewer profile coefficients, in
* tangent units at the panel), how far it sits from the panel, and how far apart the two are.
* [fallbackFovDeg] is the eye's field of view when the panel's size is unknown, or with no lens.
*/
enum class Viewer(val id: String, val k1: Float, val k2: Float, val screenToLensMm: Float,
val lensSeparationMm: Float, val chroma: Float, val fallbackFovDeg: Float) {
/** Google Cardboard (2015): the common plastic and cardboard viewers. */
CARDBOARD_V2("cardboard2", 0.34f, 0.55f, 39.3f, 63.9f, 0.006f, 90f),
/** The original 2014 Cardboard: narrower, gentler lenses. */
CARDBOARD_V1("cardboard1", 0.441f, 0.156f, 42f, 60f, 0.004f, 80f),
/** No lens: side-by-side 3D glasses, a 3D TV, or just looking at the stereo pair. */
NONE("none", 0f, 0f, 0f, 0f, 0f, 60f);
companion object {
@@ -80,21 +52,12 @@ data class Cardboard(
headTracking = json.optBoolean("headTracking", true),
)
/**
* One eye's vertical field of view on the panel side of the lens: half the panel's height
* seen from the lens's focal distance. The lens then spreads it wider (the distortion).
*/
fun fovDeg(viewer: Viewer, panelHeightMm: Float): Float {
if (panelHeightMm <= 0f || viewer.screenToLensMm <= 0f) return viewer.fallbackFovDeg
val half = Math.toDegrees(kotlin.math.atan((panelHeightMm / 2f / viewer.screenToLensMm).toDouble())).toFloat()
return (2f * half).coerceIn(30f, 140f)
}
/**
* The lens centre's inset towards the nose, as a fraction of one eye viewport's width. Each
* eye gets half the panel, so its viewport centre is a quarter of the panel from the middle;
* the lens centre is half the lens separation from it. 0 when either is unknown.
*/
fun lensInset(panelWidthMm: Float, lensSeparationMm: Float): Float {
if (panelWidthMm <= 0f || lensSeparationMm <= 0f) return 0f
val inset = (panelWidthMm / 4f - lensSeparationMm / 2f) / (panelWidthMm / 2f)
@@ -103,15 +66,9 @@ data class Cardboard(
}
}
/**
* Head pose maths for Cardboard mode, kept free of Android types so it is unit-tested on the JVM.
* Matrices are row-major 3x3 FloatArrays. "World" is Android's sensor world (x east, y north,
* z up); "screen" axes are x right, y up, z out of the panel towards the viewer's eyes.
*/
object HeadPose {
val IDENTITY = floatArrayOf(1f, 0f, 0f, 0f, 1f, 0f, 0f, 0f, 1f)
/** Unit quaternion (x, y, z, w) -> rotation matrix: what SensorManager.getRotationMatrixFromVector gives. */
fun fromQuaternion(x: Float, y: Float, z: Float, w: Float): FloatArray {
val n = sqrt(x * x + y * y + z * z + w * w).takeIf { it > 1e-6f } ?: 1f
val qx = x / n; val qy = y / n; val qz = z / n; val qw = w / n
@@ -122,57 +79,33 @@ object HeadPose {
)
}
/** The rotation vector sensor's values -> (x, y, z, w), computing w when the sensor leaves it out. */
fun quaternionFromRotationVector(v: FloatArray): FloatArray {
val x = v[0]; val y = v[1]; val z = v[2]
val w = if (v.size >= 4) v[3] else sqrt((1f - x * x - y * y - z * z).coerceAtLeast(0f))
return floatArrayOf(x, y, z, w)
}
/**
* Device -> screen axes for a Display rotation (Surface.ROTATION_* as 0..3): the returned matrix
* maps screen to world, given the device's own device -> world matrix. The same transform as
* input/PadMotion's and SensorManager.remapCoordinateSystem's (ROTATION_90 = AXIS_Y, AXIS_MINUS_X:
* the device's x is the screen's y, its y the screen's -x).
*/
fun toScreen(deviceToWorld: FloatArray, rotation: Int): FloatArray {
// Columns of A: where each screen axis points in device coordinates.
val a = when (rotation and 3) {
1 -> floatArrayOf(0f, 1f, 0f, -1f, 0f, 0f, 0f, 0f, 1f) // screen x = -device y, y = device x
2 -> floatArrayOf(-1f, 0f, 0f, 0f, -1f, 0f, 0f, 0f, 1f) // screen x = -device x, y = -device y
3 -> floatArrayOf(0f, -1f, 0f, 1f, 0f, 0f, 0f, 0f, 1f) // screen x = device y, y = -device x
1 -> floatArrayOf(0f, 1f, 0f, -1f, 0f, 0f, 0f, 0f, 1f)
2 -> floatArrayOf(-1f, 0f, 0f, 0f, -1f, 0f, 0f, 0f, 1f)
3 -> floatArrayOf(0f, -1f, 0f, 1f, 0f, 0f, 0f, 0f, 1f)
else -> IDENTITY
}
return multiply(deviceToWorld, a)
}
/** sin(60 degrees): a view further from level than this is "held flat" for recentring. */
private const val FLAT_SIN = 0.866f
/**
* What a recentre locks to. The pose the compositor gets is basis^T * screenToWorld * tilt:
* - [basis]: a level frame (columns right, up, back in world) facing the recentred heading. Every
* rotation is measured in it, so turning about the real vertical always pans the view;
* - [tilt]: the device's own tilt at the recentre, taken out so that pose starts straight ahead.
* Identity when the device was held upright: the horizon then stays the true one.
*/
class Reference(val basis: FloatArray, val tilt: FloatArray)
/**
* Recentre on the current orientation. Held upright (the screen within 60 degrees of vertical, as
* in a viewer), only the heading resets: forward is where the screen faces. Held flat (lying back,
* or the device on a table or in the hands like a tray), forward is where the top of the screen
* points and the tilt resets too; turning at the hips still pans, tipping the device still tilts.
*/
fun recenter(screenToWorld: FloatArray): Reference {
val fz = -screenToWorld[8]
val flat = kotlin.math.abs(fz) > FLAT_SIN
// Upright: the screen's -z. Flat: the screen's +y (its top edge), which is level then.
var fx = if (flat) screenToWorld[1] else -screenToWorld[2]
var fy = if (flat) screenToWorld[4] else -screenToWorld[5]
val len = sqrt(fx * fx + fy * fy).takeIf { it > 1e-4f } ?: run { fx = 0f; fy = 1f; 1f }
fx /= len; fy /= len
// right = forward x up(0,0,1) = (fy, -fx, 0); up = (0,0,1); back = -forward.
val basis = floatArrayOf(
fy, 0f, -fx,
-fx, 0f, -fy,
@@ -182,7 +115,6 @@ object HeadPose {
return Reference(basis, tilt)
}
/** head -> recentred world: what the compositor takes. */
fun relative(ref: Reference, screenToWorld: FloatArray): FloatArray =
multiply(multiply(transpose(ref.basis), screenToWorld), ref.tilt)
@@ -193,7 +125,6 @@ object HeadPose {
fun transpose(m: FloatArray): FloatArray = floatArrayOf(m[0], m[3], m[6], m[1], m[4], m[7], m[2], m[5], m[8])
/** m * v for a 3-vector. */
fun apply(m: FloatArray, v: FloatArray): FloatArray = floatArrayOf(
m[0] * v[0] + m[1] * v[1] + m[2] * v[2],
m[3] * v[0] + m[4] * v[1] + m[5] * v[2],
@@ -9,25 +9,17 @@ import com.droiddeck.launcher.session.SessionPrefs
import java.io.File
import java.util.Locale
/**
* Everything the device info window shows about the phone's chip: SoC, GPU, CPU, memory, system,
* the phone's own Vulkan driver and the drivers DroidDeck uses. Reads files and asks Vulkan once
* ([VulkanInfo]), so [collect] belongs off the main thread. Values the phone does not give are
* left out rather than guessed.
*/
object DeviceInfo {
class Section(val title: String, val rows: List<Pair<String, String>>)
fun collect(context: Context): List<Section> {
val vk = VulkanInfo.query()
// After Vulkan has been asked, detection can use its name too.
val gpu = GpuInfo.detect()
return listOf(
chip(), gpu(gpu), cpu(), memory(context), system(), vulkan(context, vk), drivers(context, gpu),
).filter { it.rows.isNotEmpty() }
}
/** The whole window as plain text, for a bug report. */
fun text(sections: List<Section>): String = buildString {
append("DroidDeck device info\n")
for (s in sections) {
@@ -78,7 +70,6 @@ object DeviceInfo {
private fun cpu() = Section("CPU", buildList<Pair<String, String>> {
add("Cores", Runtime.getRuntime().availableProcessors().toString())
// Each cpufreq policy is one cluster: the cores it covers and their speed range.
val policies = File("/sys/devices/system/cpu/cpufreq").listFiles { f -> f.name.matches(Regex("policy\\d+")) }
?.sortedBy { it.name.removePrefix("policy").toInt() }.orEmpty()
for (p in policies) {
@@ -94,7 +85,6 @@ object DeviceInfo {
private fun ghz(khz: Long) = String.format(Locale.US, "%.2f GHz", khz / 1e6)
/** The GPU's slowest and fastest step: KGSL's list, else a devfreq GPU node (Mali and others). */
private fun gpuRange(): String? {
fun mhz(hz: Long) = "${hz / 1_000_000} MHz"
val kgsl = read("/sys/class/kgsl/kgsl-3d0/gpu_available_frequencies")
@@ -134,7 +124,6 @@ object DeviceInfo {
add("API version", vk["api"])
add("Loader version", vk["loader"])
add("Driver", listOfNotNull(vk["driver_name"], vk["driver_version"]).joinToString(" "))
// Qualcomm's build string starts with its own label ("Driver Build: 43c70540de, ...").
add("Driver build", vk["driver_info"]?.replace(Regex("(?i)^driver build:\\s*"), ""))
add("Conformance", vk["conformance"])
add("Vendor / device id", listOfNotNull(vk["vendor_id"], vk["device_id"]).joinToString(" / "))
@@ -144,7 +133,6 @@ object DeviceInfo {
val features = listOf("geometry_shader" to "Geometry shaders", "tessellation_shader" to "Tessellation", "texture_bc" to "BC textures")
for ((key, label) in features) add(label, vk[key])
for ((key, value) in vk) if (key.startsWith("ext.")) add(key.removePrefix("ext."), value)
// What Android certifies the phone for.
val pm = context.packageManager
val hw = pm.systemAvailableFeatures.associate { it.name to it.version }
hw[PackageManager.FEATURE_VULKAN_HARDWARE_VERSION]?.let {
@@ -11,37 +11,18 @@ import java.io.File
import java.io.IOException
import java.util.zip.ZipInputStream
/**
* An all-in-one driver package: one zip carrying both halves of a matched pair, the display
* (Android, bionic) driver in one directory and the runtime (Linux, glibc) driver in another,
* indexed by a root `manifest.json` - DroidDeck's own DD-Turnip releases (Droid-Deck/Drivers):
*
* ```
* manifest.json {"package", "version", "drivers": {"android": {"path"}, "linux": {"path"}}}
* android/ meta.json (AdrenoTools) + libvulkan_freedreno.so
* linux/ meta.json + libvulkan_freedreno.so
* ```
*
* Installing one puts each half through its own importer, with that importer's checks, and
* remembers the two as one bundle: picking either half sets both, and deleting either deletes both,
* so a bundle is always used whole. Zips of the older kind, one driver each, never reach this.
*/
object DriverBundle {
private const val TAG = "DriverBundle"
private const val PREFS = "driver_bundles"
private const val MANIFEST = "manifest.json"
/** Refuses a zip that unpacks to more than this: both halves together are about 30 MB. */
private const val MAX_BYTES = 512L shl 20
class Manifest(val name: String, val version: String, val tag: String, val androidPath: String, val linuxPath: String)
/** An installed bundle: [androidId] in TurnipDriver's list, [linuxId] in LinuxVulkanDriverManager's. */
class Bundle(val id: String, val name: String, val version: String, val androidId: String, val linuxId: String) {
/** "DD-Turnip 0.1.0". */
val label: String get() = if (version.isEmpty()) name else "$name $version"
}
/** The manifest of a bundle, or null when [json] is not one (both halves, in two directories). */
fun parseManifest(json: JSONObject): Manifest? {
val drivers = json.optJSONObject("drivers") ?: return null
val android = cleanPath(drivers.optJSONObject("android")?.optString("path").orEmpty()) ?: return null
@@ -58,7 +39,6 @@ object DriverBundle {
return p.takeIf { it.isNotEmpty() && it.split('/').none { part -> part.isEmpty() || part == "." || part == ".." } }
}
/** True when the zip at [uri] is a bundle rather than a single driver. */
fun isBundle(context: Context, uri: Uri): Boolean = try {
context.contentResolver.openInputStream(uri)?.use { input ->
ZipInputStream(input).use { zip ->
@@ -71,11 +51,6 @@ object DriverBundle {
false
}
/**
* Install both halves of the bundle at [uri]. Both or neither: a half that is refused removes
* the one already in. Throws [IllegalArgumentException] with a user-facing reason when the zip
* is not a usable bundle, [IOException] on read failures.
*/
fun install(context: Context, uri: Uri): Bundle {
val work = File(context.cacheDir, "bundle-${System.nanoTime()}")
val td = TurnipDriver(context)
@@ -153,7 +128,6 @@ object DriverBundle {
} ?: throw IOException("cannot open $uri")
}
/** Every installed bundle whose two halves are both still there. */
fun all(context: Context): List<Bundle> {
val td = TurnipDriver(context)
val lm = LinuxVulkanDriverManager(context)
@@ -167,24 +141,20 @@ object DriverBundle {
fun get(context: Context, id: String): Bundle? = all(context).firstOrNull { it.id == id }
/** The bundle [driverId] is a half of, in the runtime list when [linux], else the display list. */
fun containing(context: Context, driverId: String, linux: Boolean): Bundle? =
all(context).firstOrNull { (if (linux) it.linuxId else it.androidId) == driverId }
/** The bundle both drivers are set to right now, if they are one. */
fun active(context: Context): Bundle? {
val android = SessionPrefs.androidDriver(context)
val linux = SessionPrefs.linuxDriver(context)
return all(context).firstOrNull { it.androidId == android && it.linuxId == linux }
}
/** Set both halves as the drivers in use. */
fun select(context: Context, bundle: Bundle) {
SessionPrefs.setAndroidDriver(context, bundle.androidId)
SessionPrefs.setLinuxDriver(context, bundle.linuxId)
}
/** Delete both halves; a driver still set to either goes back to its default. */
fun remove(context: Context, bundle: Bundle) {
TurnipDriver(context).remove(bundle.androidId)
LinuxVulkanDriverManager(context).removeDriver(bundle.linuxId)
@@ -2,20 +2,6 @@ package com.droiddeck.launcher.gpu
import com.droiddeck.launcher.gpu.GpuInfo.Family
/**
* The release drivers as matched pairs: a display build (the app's compositor, bionic) and a Linux
* build (the runtime, glibc) that were made to run together. Mixing a runtime driver carrying a
* patch with a display driver that lacks it is where the hard-to-read bugs come from, so the app
* installs and selects both halves of one pair at once.
*
* - Banners-Turnip publishes each variant as a set in every release (`Turnip-<tag><variant>.zip`
* and `...-Linux.zip`), rebuilt from upstream Mesa as it moves: the pair is one variant of the
* newest release that carries both halves.
* - WinNative ships its display (`v1.x`) and Linux (`linux-v0.x`) builds as two release lines with
* their own numbers: the pair is the newest of each, of one flavour (Balanced or Performance).
* - DroidDeck's DD-Turnip ships both halves in one zip per release (DriverBundle): the pair is the
* newest bundle, and it can never be mixed.
*/
object DriverPairs {
const val BANNER = "banner"
const val BANNER_A8XX = "banner-a8xx"
@@ -24,24 +10,18 @@ object DriverPairs {
const val WN_BALANCED = "wn-b"
const val WN_PERFORMANCE = "wn-p"
const val DD_TURNIP = "dd-turnip"
/** Each DD-Turnip release is its own pair: "dd-turnip:DD-Turnip-v0.1.0". */
fun ddTurnip(tag: String) = "$DD_TURNIP:$tag"
class DriverPair(
val key: String,
/** "Banners-Turnip · Adreno 6xx/7xx", "WinNative · Balanced". */
val name: String,
/** The families the pair is built for; the list only offers it on those unless asked. */
val families: Set<Family>,
val display: TurnipReleases.Asset?,
val linux: TurnipReleases.Asset?,
/** Both halves in one zip, instead of [display] and [linux]. */
val bundle: TurnipReleases.Asset? = null,
) {
val complete: Boolean get() = bundle != null || (display != null && linux != null)
/** The zips to download for the pair: the bundle, or the two halves. */
val assets: List<TurnipReleases.Asset> get() = listOfNotNull(bundle ?: display, if (bundle == null) linux else null)
/** "r4 · 1.19 + 0.1.2": the build of each half. */
val version: String
get() = listOfNotNull(bundle?.tag, display?.tag, linux?.tag).distinct().joinToString(" + ") { it.removePrefix("linux-").removePrefix("DD-Turnip-") }
fun suits(gpu: GpuInfo) = gpu.family in families ||
@@ -65,7 +45,6 @@ object DriverPairs {
else -> key to ALL_ADRENO
}
/** Every pair the last release check found, in the order the list shows them. */
fun from(check: TurnipReleases.Check?): List<DriverPair> {
val assets = check?.assets.orEmpty().filter { it.pair.isNotEmpty() }
val order = listOf(DD_TURNIP, BANNER, BANNER_A8XX, BANNER_ONEUI, BANNER_710, WN_BALANCED, WN_PERFORMANCE)
@@ -75,9 +54,6 @@ object DriverPairs {
val (name, families) = describe(key)
val halves = assets.filter { it.pair == key }
halves.firstOrNull { it.bundle }?.let { return@map DriverPair(key, name, families, null, null, it) }
// The list keeps the newest release of each half; for Banners-Turnip the two halves
// must come from the same release, so a set missing one half in its newest release
// is offered incomplete rather than mixed with an older one.
val display = halves.firstOrNull { !it.linux }
val linux = halves.firstOrNull { it.linux }
val sameRelease = !key.startsWith(BANNER) || display?.tag == linux?.tag
@@ -85,24 +61,15 @@ object DriverPairs {
}
}
/**
* The pair Auto sets for [gpu], among the [pairs] the last release check found: the newest
* official DD-Turnip release on the Adreno 840 (840 and 840v2), WinNative Balanced on the other
* 8xx (Banners' A8xx builds still break on some first boots) and on an 840 while no DD-Turnip
* release is listed, the OneUI build for an 8 Gen 2 under One UI, the patched test builds for
* the 710/720/722, and upstream Banners-Turnip for the rest. Null when nothing fits (not Adreno).
*/
fun recommendedKey(gpu: GpuInfo, pairs: List<DriverPair>): String? = when (gpu.family) {
Family.NOT_ADRENO -> null
Family.A8XX -> if (gpu.model == 840) newestDdTurnip(pairs) ?: WN_BALANCED else WN_BALANCED
Family.A7XX_LOW -> BANNER_710
Family.A7XX -> if (gpu.oneUi8Gen2) BANNER_ONEUI else BANNER
Family.A6XX -> BANNER
// KGSL gave no model: Android 16 arrived with the 8xx, so a device that new is taken as one.
Family.ADRENO_UNKNOWN -> if (android.os.Build.VERSION.SDK_INT >= 36) WN_BALANCED else BANNER
}
/** The complete DD-Turnip pair with the highest version, or null when none is listed. */
fun newestDdTurnip(pairs: List<DriverPair>): String? = pairs
.filter { it.key.startsWith("$DD_TURNIP:") && it.complete }
.maxByOrNull { p ->
@@ -5,7 +5,6 @@ import android.util.Log;
import java.io.File;
import java.io.FileWriter;
/** Setup breadcrumbs survive failures before a session log exists. No account data. */
public final class DriverSetupLog {
private DriverSetupLog() {}
@@ -13,7 +12,7 @@ public final class DriverSetupLog {
Log.i("DriverSetup", stage);
append(context.getFilesDir(), stage);
try { append(context.getExternalFilesDir(null), stage); }
catch (Exception ignored) { /* External storage is optional. */ }
catch (Exception ignored) { }
}
private static void append(File directory, String stage) {
@@ -21,10 +20,9 @@ public final class DriverSetupLog {
try {
directory.mkdirs();
File file = new File(directory, "driver-setup.txt");
// Keep the latest run's breadcrumbs bounded across repeated attempts.
try (FileWriter out = new FileWriter(file, file.length() < 131072)) {
out.write(System.currentTimeMillis() + " " + stage + "\n");
}
} catch (Exception ignored) { /* Diagnostics must never prevent startup. */ }
} catch (Exception ignored) { }
}
}
@@ -5,34 +5,20 @@ import android.util.Log
import com.droiddeck.launcher.R
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 [Lossless]). 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
/** LSFG's adaptive targets: it generates as many frames as it takes to reach one. */
val ADAPTIVE_TARGETS = listOf(120, 90, 60)
private const val PREFS = "frame_gen"
/** A fixed [multiplier] (2..4), or for LSFG a [target] frame rate (0 = fixed). */
data class Mode(val engine: String, val multiplier: Int = 2, val target: Int = 0) {
companion object {
val OFF = Mode(ENGINE_OFF)
@@ -54,7 +40,6 @@ object FrameGen {
.putString("engine", mode.engine).putInt("multiplier", mode.multiplier).putInt("target", mode.target).apply()
}
/** "Off", "Win-FG 2×", "LSFG 3×", "LSFG Adaptive 90". */
fun label(context: Context): String = label(context, mode(context))
fun label(context: Context, mode: Mode): String = when {
@@ -64,11 +49,6 @@ object FrameGen {
else -> context.getString(R.string.frame_gen_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. Blocks while a new or updated
* Lossless.dll is prepared.
*/
fun apply(context: Context, refreshHz: Float): String? {
val mode = mode(context)
when (mode.engine) {
@@ -6,38 +6,23 @@ import com.droiddeck.launcher.R
import com.droiddeck.launcher.core.FileUtils
import java.io.File
/**
* What GPU this is, in the terms the driver lists are sorted by. KGSL names the model
* ("Adreno740v2", "Adreno825"); the family decides which Turnip builds run on it at all, and the
* support level is what the app has actually been tested on (Adreno 650, 725 and newer) - an
* Adreno 610 may start, but it is not "supported" just because it is a Qualcomm chip.
*/
data class GpuInfo(
/** "Adreno 740", or the vendor's own name when this is not an Adreno. */
val name: String,
/** The three-digit Adreno model (740, 825), or 0 when KGSL does not say. */
val model: Int,
val family: Family,
/** The SoC as a person would say it ("Snapdragon 8 Gen 2 (QCS8550)"), or "" when the phone does not say. */
val soc: String,
/** Samsung's One UI on an 8 Gen 2: its Turnip needs the OneUI build, or frames tear and flicker. */
val oneUi8Gen2: Boolean,
/** KGSL's own name for the GPU, as the kernel spells it ("Adreno740v2", "Adreno33v2"). */
val kgslName: String = "",
/** Where [model] came from: "kernel", "vulkan" or "platform", "" when unknown. */
val modelSource: String = "",
) {
enum class Family(val label: String) {
A8XX("Adreno 8xx"),
/** Adreno 710/720/722: gen 7 cores cut down enough to need their own patches. */
A7XX_LOW("Adreno 710/720/722"),
A7XX("Adreno 7xx"),
A6XX("Adreno 6xx"),
/** An Adreno whose model KGSL does not give: treated as the newest family it could be. */
ADRENO_UNKNOWN("Adreno"),
NOT_ADRENO("Not an Adreno GPU");
/** [label] in the app's language: the Adreno families are names, the rest is words. */
fun label(context: Context): String = if (this == NOT_ADRENO) context.getString(R.string.gpuinfo_not_adreno) else label
}
@@ -52,7 +37,6 @@ data class GpuInfo(
else -> Support.UNTESTED
}
/** One line for the device card and the system check, in English for the device report. */
val supportText: String
get() = when (support) {
Support.TESTED -> "Supported"
@@ -61,30 +45,23 @@ data class GpuInfo(
Support.UNSUPPORTED -> "Not supported: DroidDeck needs an Adreno (Snapdragon) GPU"
}
/** [supportText] in the app's language. */
fun supportText(context: Context): String = context.getString(when (support) {
Support.TESTED -> R.string.gpuinfo_supported
Support.UNTESTED -> if (family == Family.A7XX_LOW) R.string.gpuinfo_experimental else R.string.gpuinfo_below_tested
Support.UNSUPPORTED -> R.string.gpuinfo_unsupported
})
/** [name] for the screen: the stand-in for a GPU the device does not name is in the app's language. */
fun displayName(context: Context): String = if (name == UNNAMED) context.getString(R.string.gpu_this_gpu) else name
companion object {
/** [name] when the device names no GPU; English, as the device report shows it. */
private const val UNNAMED = "this GPU"
fun detect(): GpuInfo {
val adreno = File("/sys/class/kgsl/kgsl-3d0").exists() || File("/vendor/lib64/hw/vulkan.adreno.so").exists()
val raw = listOf("/sys/class/kgsl/kgsl-3d0/gpu_model", "/sys/class/kgsl/kgsl-3d0/gpu_chipid")
.firstNotNullOfOrNull { FileUtils.readString(File(it))?.trim()?.takeIf(String::isNotEmpty) }
// Where vendors put the chip's model, named when it is known: "Snapdragon 8 Gen 2 (QCS8550)".
val soc = if (adreno) SocNames.label() else ""
val fromKernel = raw?.let { threeDigits(it) } ?: 0
// Some kernels name the GPU without its model (AYANEO's Pocket FIT: "Adreno33v2"). The
// Vulkan driver's own name, when this process has asked it, then the platform's code
// name stand in - the GPU is the same on every phone of a platform.
val fromVulkan = if (fromKernel > 0 || !adreno) 0 else VulkanInfo.cachedOrNull()?.get("device")?.let { threeDigits(it) } ?: 0
val fromPlatform = if (fromKernel > 0 || fromVulkan > 0 || !adreno) 0 else platformModel()
val model = maxOf(fromKernel, fromVulkan, fromPlatform)
@@ -106,7 +83,6 @@ data class GpuInfo(
private fun threeDigits(text: String): Int = Regex("""(\d{3})""").find(text)?.groupValues?.get(1)?.toIntOrNull() ?: 0
/** Qualcomm platform code names whose GPU is known for certain. */
private val PLATFORMS = mapOf(
"msmnile" to 640, "kona" to 650, "lahaina" to 660, "taro" to 730, "cape" to 730,
"kalama" to 740, "pineapple" to 750, "sun" to 830,
@@ -115,7 +91,6 @@ data class GpuInfo(
internal fun platformModel(platform: String = systemProperty("ro.board.platform")): Int =
PLATFORMS[platform.lowercase()] ?: PLATFORMS[systemProperty("ro.vendor.qti.soc_name").lowercase()] ?: 0
/** android.os.SystemProperties.get, which apps may read but not call directly. */
fun systemProperty(name: String): String = try {
Class.forName("android.os.SystemProperties").getMethod("get", String::class.java).invoke(null, name) as? String ?: ""
} catch (_: Exception) {
@@ -10,15 +10,6 @@ import android.os.HandlerThread
import android.util.Log
import com.droiddeck.launcher.wayland.WaylandCompositor
/**
* 3DoF head tracking for Cardboard mode: the rotation sensor -> the compositor's head pose
* ([HeadPose] for the maths). Game rotation vector first (gyro + accelerometer: no compass jumps
* indoors, and only the heading drifts, which a recentre fixes); the plain rotation vector where a
* device has no game one. Events arrive on a thread of their own and go straight to native code,
* so the session's UI thread never sits between the sensor and the screen.
*
* [rotation] is the Display rotation (Surface.ROTATION_*) the session is drawn in.
*/
class HeadTracker(context: Context, private val rotation: () -> Int) : SensorEventListener {
private val sensors = context.getSystemService(Context.SENSOR_SERVICE) as SensorManager
private val sensor: Sensor? = sensors.getDefaultSensor(Sensor.TYPE_GAME_ROTATION_VECTOR)
@@ -28,7 +19,6 @@ class HeadTracker(context: Context, private val rotation: () -> Int) : SensorEve
@Volatile private var recenterPending = true
@Volatile private var latest: FloatArray? = null
/** Whether this device has a rotation sensor at all (no sensor = a fixed, head-locked screen). */
val available: Boolean get() = sensor != null
val sensorName: String get() = sensor?.let { "${it.name} (${if (it.type == Sensor.TYPE_GAME_ROTATION_VECTOR) "game rotation vector" else "rotation vector"})" } ?: "none"
@@ -54,7 +44,6 @@ class HeadTracker(context: Context, private val rotation: () -> Int) : SensorEve
WaylandCompositor.nativeSetCardboardPose(HeadPose.IDENTITY, false)
}
/** Make where the viewer looks now straight ahead (see HeadPose.recenter). */
fun recenter() {
recenterPending = true
latest?.let { apply(it) }
@@ -6,28 +6,8 @@ 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 =
@@ -38,7 +18,6 @@ public final class LinuxVulkanDriver {
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("");
@@ -46,10 +25,6 @@ public final class LinuxVulkanDriver {
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);
@@ -58,10 +33,6 @@ public final class LinuxVulkanDriver {
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);
@@ -22,30 +22,6 @@ 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 KDE Plasma 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/&lt;id&gt;/
* 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";
@@ -66,14 +42,12 @@ public class LinuxVulkanDriverManager {
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;
}
@@ -108,7 +82,6 @@ public class LinuxVulkanDriverManager {
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", "") : "";
@@ -118,14 +91,8 @@ public class LinuxVulkanDriverManager {
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 = newStagingDir();
boolean keep = false;
@@ -138,7 +105,6 @@ public class LinuxVulkanDriverManager {
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")) {
@@ -154,8 +120,6 @@ public class LinuxVulkanDriverManager {
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 adopt() writes an absolute one.
}
}
String id = adopt(tmpDir, soName, zipMeta, displayName);
@@ -166,7 +130,6 @@ public class LinuxVulkanDriverManager {
}
}
/** An empty directory beside the installed drivers, for a driver's files before {@link #adopt}. */
File newStagingDir() throws IOException {
File tmpDir = new File(rootDir, ".tmp-" + System.nanoTime());
FileUtils.delete(tmpDir);
@@ -174,11 +137,6 @@ public class LinuxVulkanDriverManager {
return tmpDir;
}
/**
* Check a staged driver ({@link #LIB_NAME} in {@code tmpDir}, copied from {@code soName} in
* the zip), write its manifest and meta.json, and move it in. Returns the id; the caller
* deletes {@code tmpDir} when this throws.
*/
String adopt(File tmpDir, String soName, JSONObject zipMeta, String displayName) throws IOException {
try {
if (soName == null) {
@@ -188,9 +146,6 @@ public class LinuxVulkanDriverManager {
if (!isAarch64Elf(so)) {
throw new IllegalArgumentException(context.getString(R.string.lvd_not_aarch64, soName));
}
// 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(context.getString(R.string.lvd_not_glibc, soName));
}
@@ -209,8 +164,6 @@ public class LinuxVulkanDriverManager {
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();
@@ -251,7 +204,6 @@ public class LinuxVulkanDriverManager {
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];
@@ -292,7 +244,6 @@ public class LinuxVulkanDriverManager {
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);
}
@@ -10,16 +10,6 @@ import java.io.File
import java.security.DigestOutputStream
import java.security.MessageDigest
/**
* LSFG's shader chain, from the user's own Lossless Scaling (Steam app 993090).
*
* The copy the Steam client installs, in any library it installs to, is taken by
* itself and taken again whenever the client updates it. Once the session has seen the account
* own the app, a Lossless.dll can also be imported by hand; it stays until the Steam copy changes
* or another is imported. The DLL is copied in and its shaders are built into a cache named after
* its contents, so a different DLL hands the compositor a different path and its engine reloads.
* Everything here blocks: call it off the main thread.
*/
object Lossless {
enum class Source { NONE, STEAM, IMPORT }
@@ -46,7 +36,6 @@ object Lossless {
return State(owned(context), cacheFile(context)?.isFile == true, source)
}
/** Recorded once: by the session's ownership check (a flag in the guest's home) or a Steam copy. */
fun owned(context: Context): Boolean {
if (prefs(context).getBoolean(KEY_OWNED, false)) return true
if (!ownedFlag(context).exists()) return false
@@ -56,7 +45,6 @@ object Lossless {
fun cacheFile(context: Context): File? = prefs(context).getString(KEY_ID, null)?.let { cacheFor(context, it) }
/** Takes a new or updated Steam copy and rebuilds a missing or outdated cache. A [LsfgNative] status. */
@Synchronized
fun sync(context: Context): Int {
val steam = steamDll(context)
@@ -163,7 +151,6 @@ object Lossless {
?.forEach { it.delete() }
}
/** The newest copy in any library the client installs to: its own, the card's, the Games folders. */
private fun steamDll(context: Context): File? {
val libraries = listOfNotNull(
File(LinuxRuntime.rootDir(context), "root/.local/share/Steam"),
@@ -1,16 +1,10 @@
package com.droiddeck.launcher.gpu;
/**
* The native half of LSFG's shader cache (lsfg_jni.cpp, compiled into the compositor library):
* {@code Lossless.dll} is mapped read-only and parsed as data, never loaded or executed, and its
* DXBC chain translated to SPIR-V. {@link Lossless} decides when; these calls block.
*/
final class LsfgNative {
static { System.loadLibrary("droiddeckwayland"); }
private LsfgNative() {}
// Mirrors lsfg::DllStatus.
static final int STATUS_OK = 0;
static final int STATUS_NOT_INSTALLED = 1;
static final int STATUS_UNREADABLE_FILE = 2;
@@ -19,7 +13,6 @@ final class LsfgNative {
static final int STATUS_TRANSLATION_FAILED = 5;
static final int STATUS_CACHE_UNUSABLE = 6;
// Mirrors lsfg::Variant.
static final int VARIANT_NONE = 0;
static native int nativeValidateDll(String dllPath);
@@ -6,20 +6,6 @@ import com.droiddeck.launcher.wayland.WaylandCompositor
import org.json.JSONObject
import kotlin.math.abs
/**
* The compositor's post chain (waylandcomp/src/effects_chain.c) as the session menu drives it:
* the colour grade, the sharpening, the shader toggles and terminal debanding. Units are the
* menu's own, so a value goes straight from a row into the setter it drives:
*
* - [brightness] / [contrast] -100..100, 0 = neutral
* - [gamma] 0.5..3.0, 1.0 = neutral
* - [saturation] 0..200 percent, 100 = neutral
* - [casLevel] 0..100; the pass runs only while [cas] is on
* - [debandStrength] 0..200, 100 = one LSB
*
* Applies live: the compositor picks the change up on its next frame. While any pass is on, a
* zero-copy game goes through the compositor pass instead, which costs a little GPU time.
*/
data class ScreenEffects(
val brightness: Int = 0,
val contrast: Int = 0,
@@ -35,14 +21,11 @@ data class ScreenEffects(
val crt: Boolean = false,
val ntsc: Boolean = false,
) {
/** The sharpening level the picture gets: 0 while the pass is off, whatever its level is parked at. */
val effectiveCas: Int get() = if (cas) casLevel else 0
/** Whether any pass runs, so the menu can say when the picture is untouched. */
val any: Boolean get() = brightness != 0 || contrast != 0 || abs(gamma - 1f) > 0.005f || saturation != 100 ||
effectiveCas > 0 || hdr || deband || fxaa || toon || crt || ntsc
/** Hands every pass to the compositor, with the Look's name for its log line. */
fun push(upscaler: Int) {
WaylandCompositor.nativeSetCas(cas, casLevel)
WaylandCompositor.nativeSetHdr(hdr)
@@ -77,30 +60,19 @@ data class ScreenEffects(
}
}
/**
* One Look: a named set of values for the rows that already exist on the Display page. Picking
* a Look moves those rows; each stays adjustable afterwards, and the moment one moves the Look
* row reads Custom. [scalingMode] null leaves the scaling mode alone; otherwise it is a
* SessionPrefs.upscalerChoices mode the Look switches to.
*/
data class Look(
/** The Look's id: what the row picks by and the compositor logs. */
val name: String,
val effects: ScreenEffects,
val scalingMode: Int? = null,
/** One line under the row while this Look is picked. */
val desc: String,
/** [name] and [desc] in the app's language, for the menu. */
@StringRes val label: Int,
@StringRes val descRes: Int,
)
object ScreenEffectLooks {
// Scaling modes as the compositor numbers them (WaylandCompositor.nativeSetUpscaler).
private const val SCALING_NEAREST = 2
private const val SCALING_FSR = 4
/** Index 0 is the neutral state a fresh session matches, so the row always names something. */
val LOOKS: List<Look> = listOf(
Look("Off", ScreenEffects.OFF, desc = "Nothing applied.", label = R.string.frame_gen_off, descRes = R.string.look_off_desc),
Look("Game Clarity", ScreenEffects(brightness = 2, contrast = 12, saturation = 108, cas = true, casLevel = 55),
@@ -127,11 +99,6 @@ object ScreenEffectLooks {
desc = "Toon outlines plus sharpening.", label = R.string.look_anime_edge, descRes = R.string.look_anime_edge_desc),
)
/**
* The Look the live values are, or null for Custom. A Look's sharpening is compared as the
* effective level, so a pass switched off matches a Look without one whatever its level is
* parked at; a Look with no scaling mode of its own matches under any.
*/
fun match(e: ScreenEffects, upscaler: Int): Look? = LOOKS.firstOrNull { l ->
val t = l.effects
t.brightness == e.brightness && t.contrast == e.contrast && abs(t.gamma - e.gamma) < 0.005f &&
@@ -2,14 +2,7 @@ package com.droiddeck.launcher.gpu
import android.os.Build
/**
* Which chip this is, as a person would say it. Handhelds often leave Android's SoC model blank
* (the AYANEO Pocket FIT does), so the model is looked for where vendors put it, the same order
* ClusterTune uses; then it is named from a table of models we are sure of, or from the platform
* code name as a family ("Snapdragon 8 Gen 3 family") when the model itself is a vendor variant.
*/
object SocNames {
/** Model codes whose product name is certain. */
private val MODELS = mapOf(
"SM8150" to "Snapdragon 855", "SM8250" to "Snapdragon 865", "SM8250-AC" to "Snapdragon 870",
"SM8350" to "Snapdragon 888", "SM8450" to "Snapdragon 8 Gen 1", "SM8475" to "Snapdragon 8+ Gen 1",
@@ -19,27 +12,22 @@ object SocNames {
"SM6375" to "Snapdragon 695",
)
/** Platform code names: every chip of one platform shares its CPU and GPU design. */
private val PLATFORMS = mapOf(
"msmnile" to "Snapdragon 855/860", "kona" to "Snapdragon 865/870", "lahaina" to "Snapdragon 888",
"taro" to "Snapdragon 8 Gen 1", "cape" to "Snapdragon 8+ Gen 1", "kalama" to "Snapdragon 8 Gen 2",
"pineapple" to "Snapdragon 8 Gen 3", "sun" to "Snapdragon 8 Elite",
)
/** The chip's model code ("QCS8550", "SG8350P"), or "" when the phone does not say. */
fun model(prop: (String) -> String = GpuInfo::systemProperty): String {
val sdk = if (Build.VERSION.SDK_INT >= 31) Build.SOC_MODEL.takeIf { it != Build.UNKNOWN }.orEmpty() else ""
return listOf(prop("ro.soc.model"), prop("ro.vendor.qti.soc_model"), sdk, prop("ro.fota.platform"))
.map { it.trim() }
// ro.fota.platform is often a branch name ("MSM_13.0"), not a chip.
.firstOrNull { it.isNotEmpty() && !Regex("(?i)^msm_\\d").containsMatchIn(it) }.orEmpty()
}
/** "Snapdragon 8 Gen 2", "Snapdragon 8 Gen 3 family", or null when neither the model nor the platform is known. */
fun name(model: String, platform: String = GpuInfo.systemProperty("ro.board.platform")): String? =
MODELS[model.uppercase()] ?: PLATFORMS[platform.lowercase()]?.let { "$it family" }
/** For the GPU card: "Snapdragon 8 Gen 2 (QCS8550)", the bare model, or "". */
fun label(model: String = model(), platform: String = GpuInfo.systemProperty("ro.board.platform")): String {
val name = name(model, platform)
return when {
Loaded 100 of 852 files, more files were not shown because too many files have changed in this diff. Show more