Merge branch 'main' into fix/steam-client-download

# Conflicts:
#	tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-install
#	tools/tests/test_steam_install.py
This commit is contained in:
maxjivi05 committed 2026-10-23 20:23:44 -04:00
commit 2d9d4dbeb0
155 files changed
+6161 -993

No files matched your search

@@ -28,6 +28,7 @@ class App : Application() {
if (process == "$packageName:vr_recovery" || process == "$packageName:rgb_diagnostic") return
CrashHandler.install(this)
com.droiddeck.launcher.session.QuestExperimental.initialize(this)
com.droiddeck.launcher.session.SessionPrefs.applyNtsyncDefault(this)
com.droiddeck.launcher.session.SessionPrefs.settleGpuDriverMode(this)
com.droiddeck.launcher.update.AppUpdates.init(this)
com.droiddeck.launcher.core.DownloadSource.init(this)
@@ -55,6 +55,8 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
private set
private var runtimePending by mutableStateOf(false)
private var sessionRunning by mutableStateOf(false)
var tpUbwcMode: String by mutableStateOf(SessionPrefs.TP_UBWC_AUTO)
private set
val uiMode: String get() = when (mode) {
SessionPrefs.GPU_DRIVERS_AUTO -> GPU_MODE_AUTO
@@ -73,8 +75,16 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
mode = uiMode, display = displaySlot(), runtime = runtimeSlot(),
canRestart = !sessionRunning,
checkedAt = TurnipReleases.cached(activity)?.checkedAt ?: 0L,
tpUbwcMode = tpUbwcMode.takeIf { gpu.model == 740 },
tpUbwcRestartRequired = com.droiddeck.launcher.gpu.TpUbwcHint.restartRequired(activity),
)
fun chooseTpUbwcMode(mode: String) {
if (gpu.model != 740) return
SessionPrefs.setTpUbwcMode(activity, mode)
tpUbwcMode = mode
}
private fun slotSource(chosenDefault: Boolean, defaultLabel: Int): String = activity.getString(when {
uiMode == GPU_MODE_AUTO -> R.string.gpu_src_auto
uiMode == GPU_MODE_PAIR && pairRows.any { it.active } -> R.string.gpu_src_pair
@@ -124,6 +134,7 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
var androidSelected by mutableStateOf("")
fun refreshDrivers() {
tpUbwcMode = SessionPrefs.tpUbwcMode(activity)
val lm = LinuxVulkanDriverManager(activity)
fun origin(id: String) = if (TurnipReleases.isDownloaded(activity, id)) DriverRow.DOWNLOADED else DriverRow.IMPORTED
val bundles = DriverBundle.all(activity)
@@ -120,6 +120,7 @@ class FrontEndActivity : ComponentActivity() {
private var glThread by mutableStateOf(true)
private var noGlError by mutableStateOf(true)
private var returnAfterGame by mutableStateOf(true)
private var shaderPrecache by mutableStateOf(true)
private var steamRepairQueued by mutableStateOf(false)
private var mangoapp by mutableStateOf(true)
private var steamController by mutableStateOf(SessionPrefs.CONTROLLER_DECK)
@@ -154,6 +155,7 @@ class FrontEndActivity : ComponentActivity() {
private var gpuClockPin by mutableStateOf(false)
private var prootNoSeccomp by mutableStateOf(false)
private var prootFastPath by mutableStateOf(true)
private var cursorComposite by mutableStateOf(false)
private var guestHostname by mutableStateOf(SessionPrefs.DEFAULT_GUEST_HOSTNAME)
private var phantomWarning by mutableStateOf<String?>(null)
private var phantomProcessStatus by mutableStateOf(PhantomProcessStatus.NOT_APPLICABLE)
@@ -161,7 +163,7 @@ class FrontEndActivity : ComponentActivity() {
private var directAudio by mutableStateOf(false)
private var picturePosition by mutableStateOf("center")
private var stretch16x9 by mutableStateOf(false)
private var orientation by mutableStateOf(android.content.pm.ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE)
private var orientation by mutableStateOf(android.content.pm.ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE)
private var launcherFullscreen by mutableStateOf(true)
private var downloadSource by mutableStateOf(DownloadSource.MODE_AUTO)
private var downloadMirror by mutableStateOf("")
@@ -1509,6 +1511,7 @@ class FrontEndActivity : ComponentActivity() {
onRestoreBundled = { TurnipDriver(this).restoreBundled(); drivers.refreshDrivers() },
onMode = { m -> drivers.chooseMode(m) },
onRestart = { drivers.restartApp() },
onTpUbwcMode = { drivers.chooseTpUbwcMode(it) },
),
protons = com.droiddeck.launcher.ui.ProtonsState(
rows = protons.protonRows, busyId = protons.protonBusyId, stage = protons.protonStage, percent = protons.protonPercent,
@@ -1634,6 +1637,7 @@ class FrontEndActivity : ComponentActivity() {
syncBackend = if (mode == SessionService.MODE_STEAM) SessionPrefs.syncBackendOf(fastSync, fsyncFirst, syncFallback) else null,
steamClientArch = if (mode == SessionService.MODE_STEAM) steamClientArch else null,
returnAfterGame = if (mode == SessionService.MODE_STEAM) returnAfterGame else null,
shaderPrecache = if (mode == SessionService.MODE_STEAM) shaderPrecache else null,
steamRepairQueued = steamRepairQueued,
mangoapp = mangoapp,
steamController = if (mode == SessionService.MODE_STEAM) steamController else null,
@@ -1720,9 +1724,15 @@ class FrontEndActivity : ComponentActivity() {
syncFallback = SessionPrefs.syncFallback(this)
},
onSteamRepair = { steamRepairQueued = SteamRepair.queue(this) },
onSteamClientArch = { id -> SessionPrefs.setSteamClientArch(this, id); steamClientArch = id; refresh() },
onSteamClientArch = { id ->
SessionPrefs.setSteamClientArch(this, id)
steamClientArch = id
shaderPrecache = SessionPrefs.shaderPrecache(this)
refresh()
},
onMangoapp = { on -> SessionPrefs.setMangoapp(this, on); mangoapp = on },
onReturnAfterGame = { on -> SessionPrefs.setReturnAfterGame(this, on); returnAfterGame = on },
onShaderPrecache = { on -> SessionPrefs.setShaderPrecache(this, on); shaderPrecache = on },
onSteamController = { id -> SessionPrefs.setSteamController(this, id); steamController = id },
onRunSteamAtStartup = { on ->
SessionPrefs.setRunSteamAtStartup(this, on)
@@ -1763,7 +1773,8 @@ class FrontEndActivity : ComponentActivity() {
fsyncFirst = fsyncFirst,
gamescopeRealtime = gamescopeRealtime,
gpuClockPin = gpuClockPin,
prootNoSeccomp = prootNoSeccomp, prootFastPath = prootFastPath, guestHostname = guestHostname, phantomWarning = phantomWarning,
prootNoSeccomp = prootNoSeccomp, prootFastPath = prootFastPath, cursorComposite = cursorComposite,
guestHostname = guestHostname, phantomWarning = phantomWarning,
onClientOverride = { on -> SessionPrefs.setClientCpusOverride(this, on); clientOverride = on },
onTuSysmem = { on -> SessionPrefs.setTuSysmem(this, on); tuSysmem = on },
onZinkLazy = { on -> SessionPrefs.setZinkLazy(this, on); zinkLazy = on },
@@ -1777,6 +1788,7 @@ class FrontEndActivity : ComponentActivity() {
onGpuClockPin = { on -> SessionPrefs.setGpuClockPin(this, on); gpuClockPin = on },
onProotNoSeccomp = { on -> SessionPrefs.setProotNoSeccomp(this, on); prootNoSeccomp = on },
onProotFastPath = { on -> SessionPrefs.setProotFastPath(this, on); prootFastPath = on },
onCursorComposite = { on -> SessionPrefs.setCursorComposite(this, on); cursorComposite = on },
onGuestHostname = { name -> SessionPrefs.setGuestHostname(this, name) },
onClientCore = { core, on ->
clientCores = if (on) clientCores + core else clientCores - core
@@ -1892,6 +1904,7 @@ class FrontEndActivity : ComponentActivity() {
steamRepairQueued = SteamRepair.queued(this)
mangoapp = SessionPrefs.mangoapp(this)
returnAfterGame = SessionPrefs.returnAfterGame(this)
shaderPrecache = SessionPrefs.shaderPrecache(this)
steamController = SessionPrefs.steamController(this)
runSteamAtStartup = SessionPrefs.runSteamAtStartup(this)
loadBootMovie()
@@ -1958,6 +1971,7 @@ class FrontEndActivity : ComponentActivity() {
gpuClockPin = SessionPrefs.gpuClockPin(this)
prootNoSeccomp = SessionPrefs.prootNoSeccomp(this)
prootFastPath = SessionPrefs.prootFastPath(this)
cursorComposite = SessionPrefs.cursorComposite(this)
guestHostname = SessionPrefs.guestHostname(this)
refreshPhantomStatus()
}
@@ -329,6 +329,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private var glassesSettings by mutableStateOf(Glasses.settings.value)
private var glassesScreen: GlassesScreen? = null
private var glassesOutputActive by mutableStateOf(false)
private var pausedFrame by mutableStateOf<com.droiddeck.launcher.ui.PausedFrame?>(null)
private var pausedFrameWanted = false
private var trackingRecovery by mutableStateOf<TrackingRecovery?>(null)
private var glasses3dForVr = false
private var ended = false
@@ -1013,9 +1015,20 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
SessionAchievements(inFront.game, inFront.title, onClose = ::closeAchievements)
}
com.droiddeck.launcher.ui.AchievementNotificationOverlay()
if (SessionState.suspended) SessionPausedOverlay(
// Auto and Native resume on their own as the session comes back; only a failed resume needs the button.
val autoResume = suspendPolicy == SessionPrefs.SUSPEND_AUTO || suspendPolicy == SessionPrefs.SUSPEND_NATIVE
SessionPausedOverlay(
suspended = SessionState.suspended && (!autoResume || SessionState.resumeFailed),
engaged = SessionState.resumeRequested || SessionState.resuming,
failures = SessionState.resumeFailures,
frame = pausedFrame,
title = pausedTitle(),
onResume = { SessionService.resume(this@SessionActivity) },
onFrameNeeded = ::requestPausedFrame,
onHidden = {
pausedFrame = null
pausedFrameWanted = false
},
)
if (leaving) com.droiddeck.launcher.ui.FloodSpread(
com.droiddeck.launcher.ui.LocalPalette.current.signal,
@@ -1693,7 +1706,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
com.droiddeck.launcher.gpu.DriverSetupLog.write(this, "compositor.start driver=$driverId")
CompositorHost.startOrAttach(
holder.surface, runtimeDir.path,
this, holder.surface, runtimeDir.path,
driverId?.let { turnip.driverPath(it) }, driverId?.let { turnip.libraryName(it) },
applicationInfo.nativeLibraryDir, size.first, size.second, refreshHz(), outputFpsLimit(),
)
@@ -2860,6 +2873,50 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
if (down || code !in gestureKeysDown) WaylandCompositor.nativeSendKey(code, if (down) 1 else 0)
}
// The frozen game cannot draw again, so the paused overlay shows a copy taken while the surface still holds its frame.
private fun capturePausedFrame() {
if (!SessionState.running || pipUi || isInPictureInPictureMode || glassesOutputActive) return
if (SessionState.suspended && pausedFrame != null) return
if (suspendPolicy == SessionPrefs.SUSPEND_NEVER || !::surfaceView.isInitialized) return
if (surfaceView.holder.surface?.isValid != true) return
val width = surfaceView.width
val height = surfaceView.height
if (width <= 0 || height <= 0) return
val scale = minOf(1f, PAUSED_FRAME_MAX_EDGE / maxOf(width, height).toFloat())
val bitmap = try {
android.graphics.Bitmap.createBitmap(
maxOf(1, (width * scale).toInt()), maxOf(1, (height * scale).toInt()), android.graphics.Bitmap.Config.ARGB_8888,
)
} catch (_: OutOfMemoryError) {
return
}
val surfaceAt = IntArray(2).also { surfaceView.getLocationInWindow(it) }
val overlayAt = IntArray(2).also { sessionOverlay.getLocationInWindow(it) }
val left = surfaceAt[0] - overlayAt[0]
val top = surfaceAt[1] - overlayAt[1]
val bounds = android.graphics.Rect(left, top, left + width, top + height)
try {
android.view.PixelCopy.request(surfaceView, bitmap, { result ->
if (result == android.view.PixelCopy.SUCCESS && !isDestroyed) {
pausedFrame = com.droiddeck.launcher.ui.PausedFrame(bitmap.asImageBitmap(), bounds)
pausedFrameWanted = false
} else {
bitmap.recycle()
}
}, uiHandler)
} catch (_: IllegalArgumentException) {
bitmap.recycle()
}
}
// Sessions that froze from picture-in-picture, or before onPause could copy a frame, have none; the
// compositor shows the frozen frame again once its output is back, so copy it from there.
private fun requestPausedFrame() {
if (pausedFrame != null) return
pausedFrameWanted = true
if (resumed && surfaceW > 0) capturePausedFrame()
}
private fun pipBounds(): android.graphics.Rect {
val rect = android.graphics.Rect()
if (!::surfaceView.isInitialized || !surfaceView.getGlobalVisibleRect(rect)) return rect
@@ -2990,6 +3047,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
applyFollowOrientation(resources.configuration)
if (runtimeRemovalBlocked) return
if (!SessionState.suspended) pausedFrame = null
com.droiddeck.launcher.ui.Motion.refresh(this)
refreshHomeApp()
if (intent?.action == SessionService.ACTION_RESUME) {
@@ -3015,6 +3073,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
override fun onPause() {
if (runtimeRemovalBlocked) { super.onPause(); return }
capturePausedFrame()
sessionClipboard.stop()
if (::touchscreenGestures.isInitialized) touchscreenGestures.cancel()
if (::touchpad.isInitialized) touchpad.cancel()
@@ -3253,6 +3312,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
surfaceView.visibility = if (glassesOutputActive) View.INVISIBLE else View.VISIBLE
Log.i(TAG, "compositor output attached: " +
if (glassesOutputActive) "glasses display ${glassesScreen?.display?.displayId}" else "phone")
if (pausedFrameWanted) uiHandler.postDelayed({
if (pausedFrameWanted && pausedFrame == null && resumed) capturePausedFrame()
}, PAUSED_FRAME_REDRAW_MS)
}
private fun restorePhoneOutput(screen: GlassesScreen) {
@@ -3512,6 +3574,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
const val EXTRA_STEAMVR = "steamVr"
const val EXTRA_REPAIR_RUNTIME = "repairRuntime"
private const val LEAVE_TIMEOUT_MS = 1_500L
private const val PAUSED_FRAME_MAX_EDGE = 1920f
private const val PAUSED_FRAME_REDRAW_MS = 150L
private const val TAG = "SessionActivity"
private var startedScreens = 0
private const val FEX_MISSING = "droiddeck-fex: x86 Linux programs need"
@@ -1,27 +0,0 @@
package com.droiddeck.launcher.core
import com.droiddeck.launcher.gpu.GpuInfo
import com.droiddeck.launcher.gpu.SocNames
object CpuAllocationDefaults {
data class Allocation(val client: String, val game: String)
val device: Allocation? by lazy {
forDevice(SocNames.model(), GpuInfo.systemProperty("ro.board.platform"),
CpuCores.all.associateWith(CpuCores::maxGhz))
}
fun forDevice(model: String, platform: String, frequencies: Map<Int, Double?>): Allocation? {
val chip = model.trim().uppercase().substringBefore('-')
val gen2 = chip in setOf("SM8550", "QCS8550") ||
(chip.isEmpty() && platform.trim().equals("kalama", ignoreCase = true))
if (!gen2 || frequencies.size != 8 || frequencies.keys.any { it < 0 } ||
frequencies.values.any { it == null || !it.isFinite() || it <= 0.0 }) return null
val clusters = frequencies.entries.groupBy { it.value }.toSortedMap(compareBy { it ?: 0.0 }).values.toList()
if (clusters.map { it.size } != listOf(3, 4, 1)) return null
return Allocation(
client = CpuCores.format(clusters[2].map { it.key }.toSet()),
game = CpuCores.format(clusters[1].map { it.key }.toSet()),
)
}
}
@@ -200,7 +200,12 @@ object DeviceReport {
h("Drivers")
val gpu = com.droiddeck.launcher.gpu.GpuInfo.detect()
k("GPU", "${gpu.name} · ${gpu.family.label} · ${gpu.supportText}" + if (gpu.oneUi8Gen2) " · One UI 8 Gen 2" else "")
if (gpu.model == 740) k("TP UBWC hint", com.droiddeck.launcher.gpu.TpUbwcHint.forThisDevice() ?: "driver default")
if (gpu.model == 740) {
val hint = com.droiddeck.launcher.gpu.TpUbwcHint
k("TP UBWC hint", hint.forThisDevice(context) ?: "driver default")
k("TP UBWC mode", hint.activeMode ?: SessionPrefs.TP_UBWC_AUTO)
if (hint.restartRequired(context)) k("TP UBWC pending", "${SessionPrefs.tpUbwcMode(context)} (restart required)")
}
k("Driver mode", SessionPrefs.gpuDriverMode(context) +
(com.droiddeck.launcher.gpu.DriverPairs.recommendedKey(gpu, com.droiddeck.launcher.gpu.DriverPairs.from(
com.droiddeck.launcher.gpu.TurnipReleases.cached(context)), com.droiddeck.launcher.gpu.TurnipReleases.autoPicks(context),
@@ -29,7 +29,7 @@ class FileManagerActivity : ComponentActivity() {
setContent {
DroidDeckTheme(appScale = com.droiddeck.launcher.core.AppUiPrefs.scale(this)) {
Surface(modifier = Modifier.fillMaxSize().systemBarsPadding(), color = MaterialTheme.colorScheme.background) {
FileManagerScreen(initialDir = initialDir)
FileManagerScreen(initialDir = initialDir, onExit = { finish() })
}
}
}
@@ -28,6 +28,8 @@ import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ExitToApp
import androidx.compose.material.icons.automirrored.filled.KeyboardReturn
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.ContentPaste
import androidx.compose.material.icons.filled.CreateNewFolder
@@ -90,12 +92,18 @@ import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.droiddeck.launcher.session.SessionPrefs
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File
import java.util.Date
private enum class FileManagerNavigation { EXIT, RETURN_TO_START, BACK }
internal fun canNavigateUp(currentDir: File, currentRoot: File): Boolean =
currentDir != currentRoot && currentDir.parentFile?.exists() == true
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun FileManagerScreen(
@@ -105,6 +113,7 @@ fun FileManagerScreen(
initialDir: File? = null,
pickerTitle: String? = null,
onPick: ((File) -> Unit)? = null,
onExit: (() -> Unit)? = null,
) {
val context = LocalContext.current
val scope = rememberCoroutineScope()
@@ -118,12 +127,14 @@ fun FileManagerScreen(
val pickPrefs = remember { context.getSharedPreferences("file_manager", android.content.Context.MODE_PRIVATE) }
val browsePrefs = pickPrefs
val rootDir = remember {
val rootDir = remember(initialDir) {
initialDir?.takeIf { it.isDirectory } ?: File("/storage/emulated/0")
}
val launchDir = remember(initialDir, pickMode) {
initialDir?.takeIf { !pickMode }
}
var currentDir by remember { mutableStateOf(rootDir) }
var currentRoot by remember {
val initialRoot = remember(rootDir) {
val abs = rootDir.absolutePath
val internal = "/storage/emulated/0"
val vol = when {
@@ -139,8 +150,9 @@ fun FileManagerScreen(
?: rootDir
}
}
mutableStateOf(vol)
vol
}
var currentRoot by remember { mutableStateOf(initialRoot) }
var entries by remember { mutableStateOf(listOf<File>()) }
var selectedEntry by remember { mutableStateOf<File?>(null) }
var showMenuFor by remember { mutableStateOf<File?>(null) }
@@ -151,8 +163,10 @@ fun FileManagerScreen(
var pendingConflict by remember { mutableStateOf<File?>(null) }
var conflictChoice by remember { mutableStateOf<ConflictChoice?>(null) }
var conflictApplyToAll by remember { mutableStateOf(false) }
var operationJob by remember { mutableStateOf<kotlinx.coroutines.Job?>(null) }
var cancelledJob by remember { mutableStateOf<kotlinx.coroutines.Job?>(null) }
var operationJob by remember { mutableStateOf<Job?>(null) }
var cancelledJob by remember { mutableStateOf<Job?>(null) }
var pendingNavigation by remember { mutableStateOf<FileManagerNavigation?>(null) }
var cancellingNavigation by remember { mutableStateOf(false) }
var pendingBulkDelete by remember { mutableStateOf<List<File>>(emptyList()) }
var searchQuery by remember { mutableStateOf("") }
val visibleEntries = if (searchQuery.isBlank()) entries
@@ -178,9 +192,10 @@ fun FileManagerScreen(
var showFavorites by remember { mutableStateOf(false) }
var favTick by remember { mutableIntStateOf(0) }
var listingJob by remember { mutableStateOf<kotlinx.coroutines.Job?>(null) }
var listingJob by remember { mutableStateOf<Job?>(null) }
fun loadDirectory(dir: File, resetScroll: Boolean = true) {
if (cancellingNavigation) return
currentDir = dir
if (pickMode) pickPrefs.edit().putString("lastFilePickerDir", dir.absolutePath).apply()
listingJob?.cancel()
@@ -205,25 +220,90 @@ fun FileManagerScreen(
}
fun openDrive(dir: File) {
if (cancellingNavigation) return
currentRoot = dir
loadDirectory(dir)
}
fun returnToStart() {
if (cancellingNavigation) return
val dir = launchDir ?: return
if (!dir.isDirectory) {
Toast.makeText(context, R.string.fm_start_unavailable, Toast.LENGTH_SHORT).show()
return
}
showFavorites = false
showSearch = false
searchQuery = ""
currentRoot = initialRoot
loadDirectory(dir)
}
LaunchedEffect(Unit) { loadDirectory(rootDir) }
BackHandler(enabled = showFavorites || currentDir != currentRoot) {
if (showFavorites) {
showFavorites = false
return@BackHandler
val canGoUp = currentDir != currentRoot && currentDir.parentFile?.exists() == true
fun isOperationActive() = isOperationRunning || operationJob?.isCompleted == false || cancelledJob?.isCompleted == false
val operationActive = isOperationActive()
fun navigate(action: FileManagerNavigation) {
if (cancellingNavigation) return
when (action) {
FileManagerNavigation.EXIT -> onExit?.invoke()
FileManagerNavigation.RETURN_TO_START -> returnToStart()
FileManagerNavigation.BACK -> {
if (showFavorites) showFavorites = false
else if (canNavigateUp(currentDir, currentRoot)) currentDir.parentFile?.let { loadDirectory(it) }
else onExit?.invoke()
}
}
val parent = currentDir.parentFile
if (parent != null && parent.exists()) loadDirectory(parent)
}
val canGoUp = currentDir != currentRoot && currentDir.parentFile?.exists() == true
fun goUp() {
val parent = currentDir.parentFile
if (currentDir != currentRoot && parent != null && parent.exists()) loadDirectory(parent)
fun requestNavigation(action: FileManagerNavigation) {
if (cancellingNavigation) return
if (isOperationActive()) pendingNavigation = action else navigate(action)
}
BackHandler(enabled = operationActive || cancellingNavigation || showFavorites || currentDir != currentRoot) {
requestNavigation(FileManagerNavigation.BACK)
}
if (pendingNavigation != null) {
OutlinedAlertDialog(
onDismissRequest = { pendingNavigation = null },
title = { Text(stringResource(R.string.fm_cancel_operation_title)) },
text = { Text(stringResource(R.string.fm_cancel_operation_confirmation)) },
confirmButton = {
TextButton(onClick = {
val action = pendingNavigation ?: return@TextButton
pendingNavigation = null
val job = operationJob?.takeUnless(Job::isCompleted)
?: cancelledJob?.takeUnless(Job::isCompleted)
if (job == null) {
navigate(action)
} else {
cancellingNavigation = true
cancelledJob = job
job.cancel()
scope.launch {
job.join()
if (operationJob === job) operationJob = null
if (cancelledJob === job) cancelledJob = null
pendingConflict = null
isOperationRunning = false
operationDeterminate = false
cancellingNavigation = false
if (action != FileManagerNavigation.EXIT) loadDirectory(currentDir, resetScroll = false)
navigate(action)
}
}
}) { Text(stringResource(R.string.fm_accept)) }
},
dismissButton = {
TextButton(onClick = { pendingNavigation = null }) {
Text(stringResource(R.string.fm_decline))
}
},
)
}
fun uniqueDestination(dir: File, name: String): File {
@@ -241,11 +321,14 @@ fun FileManagerScreen(
}
fun performDelete(file: File) {
scope.launch {
if (isOperationActive()) return
operationJob = scope.launch {
isOperationRunning = true
operationLabel = context.getString(R.string.fm_op_deleting)
val ok = withContext(Dispatchers.IO) { FileOps.delete(file) }
val job = coroutineContext[Job]
val ok = withContext(Dispatchers.IO) { FileOps.delete(file) { job?.isActive == false } }
isOperationRunning = false
if (operationJob === job) operationJob = null
loadDirectory(currentDir, resetScroll = false)
if (!ok) Toast.makeText(context, R.string.fm_delete_failed, Toast.LENGTH_SHORT).show()
}
@@ -260,7 +343,7 @@ fun FileManagerScreen(
fun performPaste() {
val sources = clipboardFiles
if (sources.isEmpty() || isOperationRunning || operationJob?.isActive == true || cancelledJob?.isCompleted == false) return
if (sources.isEmpty() || isOperationActive()) return
val dstDir = currentDir
val cut = isCutOperation
@@ -269,7 +352,7 @@ fun FileManagerScreen(
operationDeterminate = true
operationLabel = context.getString(if (cut) R.string.fm_op_moving else R.string.fm_op_copying)
isOperationRunning = true
val job = coroutineContext[kotlinx.coroutines.Job]
val job = coroutineContext[Job]
var applyToAll: ConflictChoice? = null
var failed = 0
@@ -322,7 +405,7 @@ fun FileManagerScreen(
isOperationRunning = false
operationDeterminate = false
operationJob = null
if (operationJob === job) operationJob = null
clipboardFiles = emptyList()
isCutOperation = false
selectionMode = false
@@ -340,32 +423,38 @@ fun FileManagerScreen(
}
fun performRename(file: File, newName: String) {
if (isOperationActive()) return
val target = File(file.parentFile, newName)
if (target.exists()) {
Toast.makeText(context, context.getString(R.string.fm_already_exists, newName), Toast.LENGTH_SHORT).show()
return
}
scope.launch {
operationJob = scope.launch {
val job = coroutineContext[Job]
isOperationRunning = true
operationLabel = context.getString(R.string.fm_op_renaming)
val ok = withContext(Dispatchers.IO) { file.renameTo(target) }
isOperationRunning = false
if (operationJob === job) operationJob = null
loadDirectory(currentDir, resetScroll = false)
if (!ok) Toast.makeText(context, R.string.fm_rename_failed, Toast.LENGTH_SHORT).show()
}
}
fun createFolder(parent: File, name: String) {
if (isOperationActive()) return
val target = File(parent, name)
if (target.exists()) {
Toast.makeText(context, context.getString(R.string.fm_already_exists, name), Toast.LENGTH_SHORT).show()
return
}
scope.launch {
operationJob = scope.launch {
val job = coroutineContext[Job]
isOperationRunning = true
operationLabel = context.getString(R.string.fm_op_creating_folder)
val ok = withContext(Dispatchers.IO) { target.mkdirs() }
isOperationRunning = false
if (operationJob === job) operationJob = null
loadDirectory(currentDir, resetScroll = false)
if (!ok) Toast.makeText(context, R.string.fm_create_folder_failed, Toast.LENGTH_SHORT).show()
}
@@ -481,18 +570,20 @@ fun FileManagerScreen(
},
confirmButton = {
TextButton(onClick = {
if (isOperationActive()) return@TextButton
pendingBulkDelete = emptyList()
selectionMode = false
selectedPaths = emptySet()
operationJob = scope.launch {
isOperationRunning = true
val job = coroutineContext[Job]
var failed = 0
victims.forEachIndexed { i, f ->
operationLabel = context.getString(R.string.fm_op_deleting_batch, i + 1, victims.size, f.name)
if (!withContext(Dispatchers.IO) { FileOps.delete(f) }) failed++
if (!withContext(Dispatchers.IO) { FileOps.delete(f) { job?.isActive == false } }) failed++
}
isOperationRunning = false
operationJob = null
if (operationJob === job) operationJob = null
loadDirectory(currentDir, resetScroll = false)
if (failed > 0) {
Toast.makeText(context, context.resources.getQuantityString(R.plurals.fm_delete_some_failed, failed, failed), Toast.LENGTH_SHORT).show()
@@ -582,7 +673,7 @@ fun FileManagerScreen(
.background(MaterialTheme.colorScheme.surfaceContainer)
.padding(horizontal = 8.dp, vertical = 6.dp),
) {
IconButton(onClick = { goUp() }, enabled = canGoUp) {
IconButton(onClick = { requestNavigation(FileManagerNavigation.BACK) }, enabled = canGoUp && !cancellingNavigation) {
Icon(Icons.Filled.ArrowBack, stringResource(R.string.fm_back), tint = MaterialTheme.colorScheme.primary)
}
@@ -672,6 +763,13 @@ fun FileManagerScreen(
)
}
if (launchDir != null) {
IconButton(onClick = { requestNavigation(FileManagerNavigation.RETURN_TO_START) }, enabled = !cancellingNavigation) {
Icon(Icons.AutoMirrored.Filled.KeyboardReturn, stringResource(R.string.fm_return_to_start), tint = MaterialTheme.colorScheme.primary)
}
if (LocalConfiguration.current.screenWidthDp >= 700) Spacer(Modifier.width(56.dp))
}
if (!showFavorites) {
if (!pickMode) {
OutlinedButton(
@@ -747,6 +845,11 @@ fun FileManagerScreen(
Icon(Icons.Filled.StarBorder, stringResource(R.string.fm_show_favorites), tint = MaterialTheme.colorScheme.onSurfaceVariant)
}
}
if (!pickMode && onExit != null) {
IconButton(onClick = { requestNavigation(FileManagerNavigation.EXIT) }, enabled = !cancellingNavigation) {
Icon(Icons.AutoMirrored.Filled.ExitToApp, stringResource(R.string.fm_exit), tint = MaterialTheme.colorScheme.onSurfaceVariant)
}
}
}
if (showSearch && !showFavorites) {
@@ -986,7 +1089,7 @@ fun FileManagerScreen(
contentPadding = PaddingValues(8.dp),
) {
if (canGoUp) item(key = "..", span = { GridItemSpan(maxLineSpan) }) {
ParentFolderRow(compact = compactRows, onTap = { goUp() })
ParentFolderRow(compact = compactRows, onTap = { requestNavigation(FileManagerNavigation.BACK) })
}
items(shownEntries, key = { it.absolutePath }) { file ->
val isFav = remember(file.absolutePath, favTick) {
@@ -1052,7 +1155,7 @@ fun FileManagerScreen(
} else
LazyColumn(state = listState, modifier = Modifier.fillMaxSize()) {
if (canGoUp) item(key = "..") {
ParentFolderRow(compact = compactRows, onTap = { goUp() })
ParentFolderRow(compact = compactRows, onTap = { requestNavigation(FileManagerNavigation.BACK) })
}
if (entries.isEmpty()) {
item {
@@ -9,6 +9,7 @@ import java.io.FileOutputStream
import java.io.IOException
import java.nio.file.Files
import java.util.Locale
import java.util.concurrent.CancellationException
object FileOps {
private const val TAG = "FileOps"
@@ -24,24 +25,27 @@ object FileOps {
fun isSymlink(file: File): Boolean = try { Files.isSymbolicLink(file.toPath()) } catch (e: Exception) { false }
fun delete(target: File?): Boolean {
fun delete(target: File?, isCancelled: () -> Boolean = { false }): Boolean {
if (isCancelled()) throw CancellationException("Delete cancelled: $target")
if (target == null) return false
if (target.isDirectory && !isSymlink(target)) {
if (!clear(target)) return false
if (!clear(target, isCancelled)) return false
}
if (isCancelled()) throw CancellationException("Delete cancelled: $target")
return target.delete()
}
fun clear(dir: File): Boolean {
fun clear(dir: File, isCancelled: () -> Boolean = { false }): Boolean {
val children = dir.listFiles() ?: return true
var ok = true
for (child in children) if (!delete(child)) ok = false
for (child in children) if (!delete(child, isCancelled)) ok = false
return ok
}
fun totalSize(f: File?): Long {
fun totalSize(f: File?, isCancelled: () -> Boolean = { false }): Long {
if (isCancelled()) throw CancellationException("Size scan cancelled: $f")
if (f == null || !f.exists() || isSymlink(f)) return 0
if (f.isDirectory) return f.listFiles()?.sumOf { totalSize(it) } ?: 0
if (f.isDirectory) return f.listFiles()?.sumOf { totalSize(it, isCancelled) } ?: 0
return f.length()
}
@@ -53,12 +57,12 @@ object FileOps {
return true
}
if (!copyWithProgress(src, dst, progress, isCancelled)) return false
if (isCancelled()) return false
// Once the destination is committed, finish deleting the source.
return delete(src)
}
fun copyWithProgress(src: File, dst: File, progress: ProgressCallback?, isCancelled: () -> Boolean = { false }): Boolean {
val total = maxOf(totalSize(src), 1L)
val total = maxOf(totalSize(src, isCancelled), 1L)
return copyWithProgress(src, dst, longArrayOf(0), total, progress, isCancelled)
}
@@ -71,15 +75,23 @@ object FileOps {
return false
}
if (src.isDirectory) {
if (!dst.exists() && !dst.mkdirs()) return false
var allOk = true
src.list()?.forEach { name ->
if (!copyWithProgress(File(src, name), File(dst, name), done, total, progress, isCancelled)) {
Log.e(TAG, "Failed to copy: ${File(src, name)}")
allOk = false
val created = if (dst.exists()) false else {
if (!dst.mkdirs()) return false
true
}
try {
var allOk = true
src.list()?.forEach { name ->
if (!copyWithProgress(File(src, name), File(dst, name), done, total, progress, isCancelled)) {
Log.e(TAG, "Failed to copy: ${File(src, name)}")
allOk = false
}
}
return allOk
} catch (e: CancellationException) {
if (created) delete(dst)
throw e
}
return allOk
}
val parent = dst.parentFile
if (!src.exists() || (parent != null && !parent.exists() && !parent.mkdirs())) return false
@@ -118,6 +130,7 @@ object FileOps {
val size = input.size()
var position = 0L
while (position < size) {
if (isCancelled()) throw CancellationException("Copy cancelled: $src")
val transferred = input.transferTo(position, minOf(chunk, size - position), channel)
if (transferred <= 0) break
position += transferred
@@ -125,12 +138,19 @@ object FileOps {
progress?.onProgress(done[0], total)
}
if (position < size) throw IOException("Incomplete copy: $position/$size bytes")
if (size > 0 && isCancelled()) throw CancellationException("Copy cancelled: $src")
}
}
staging?.let { directory ->
val copied = File(directory, "file").toPath()
if (permissions != null && Files.getPosixFilePermissions(copied) != permissions) {
Files.setPosixFilePermissions(copied, permissions)
if (permissions != null) {
try {
if (Files.getPosixFilePermissions(copied) != permissions) {
Files.setPosixFilePermissions(copied, permissions)
}
} catch (e: Exception) {
Log.w(TAG, "Failed to restore destination permissions: $target", e)
}
}
if (isCancelled()) throw java.util.concurrent.CancellationException("Copy cancelled: $src")
Files.move(copied, target.toPath(), java.nio.file.StandardCopyOption.ATOMIC_MOVE)
@@ -50,6 +50,7 @@ class FilePickerActivity : ComponentActivity() {
setResult(Activity.RESULT_OK, Intent().putExtra(EXTRA_SELECTED_FILE, file.absolutePath))
finish()
},
onExit = { finish() },
)
}
}
@@ -274,7 +274,7 @@ object AddedGames {
class FolderResult(val added: List<Game>, val already: Int)
fun addFolder(context: Context, dir: File, onGame: (Game) -> Unit = {}, onChecking: (String?) -> Unit = {}): FolderResult {
fun addFolder(context: Context, dir: File, onGame: (Game) -> Unit = {}, onChecking: (String?) -> Unit = {}, showHidden: Boolean = false): FolderResult {
val app = context.applicationContext
// Binds are mounted at session start, so a new one reaches the session from the next start.
if (guestPath(app, dir) == null) bindFolder(app, dir)
@@ -283,7 +283,7 @@ object AddedGames {
var already = 0
val fresh = ArrayList<String>()
val added = ArrayList<Game>()
for (sub in dir.listFiles { f -> f.isDirectory && !f.name.startsWith(".") }?.sortedBy { it.name.lowercase() }.orEmpty()) {
for (sub in dir.listFiles { f -> f.isDirectory && (showHidden || !f.name.startsWith(".")) }?.sortedBy { it.name.lowercase() }.orEmpty()) {
val path = canonical(sub)
if (listed.any { it == path || inside(path, it) || inside(it, path) }) { already++; continue }
onChecking(sub.name)
@@ -1,6 +1,8 @@
package com.droiddeck.launcher.gpu
import android.content.Context
import android.util.Log
import com.droiddeck.launcher.session.SessionPrefs
object TpUbwcHint {
const val ENV = "FD_DEV_FEATURES"
@@ -8,31 +10,43 @@ object TpUbwcHint {
@Volatile private var resolved = false
@Volatile private var cached: String? = null
@Volatile var activeMode: String? = null
private set
// On Adreno 740, TPL1_DBG_ECO_CNTL1.TP_UBWC_FLAG_HINT is shared by every driver on the GPU and must
// match the system driver: blob v6xx leaves it off, newer blobs set it. A mismatch corrupts Android UI.
// match the system driver. A mismatch corrupts Android UI.
// Samsung's One UI firmware sets it whatever blob version it reports.
internal fun features(model: Int, systemDriverVersion: String?, samsung: Boolean = false): String? {
internal fun features(model: Int, systemDriverVersion: String?, samsung: Boolean = false,
mode: String = SessionPrefs.TP_UBWC_AUTO): String? {
if (model != 740) return null
if (mode == SessionPrefs.TP_UBWC_ON) return "enable_tp_ubwc_flag_hint=1"
if (mode == SessionPrefs.TP_UBWC_OFF) return "enable_tp_ubwc_flag_hint=0"
if (samsung) return "enable_tp_ubwc_flag_hint=1"
val blob = systemDriverVersion?.split('.')?.getOrNull(1)?.toIntOrNull() ?: return null
return "enable_tp_ubwc_flag_hint=" + if (blob >= 700) "1" else "0"
val parts = systemDriverVersion?.split('.') ?: return null
val blob = parts.getOrNull(1)?.toIntOrNull() ?: return null
val patch = parts.getOrNull(2)?.toIntOrNull() ?: 0
val on = blob >= 700 || (blob == 676 && patch >= 76)
return "enable_tp_ubwc_flag_hint=" + if (on) "1" else "0"
}
@Synchronized
fun forThisDevice(): String? {
fun forThisDevice(context: Context): String? {
if (resolved) return cached
val mode = SessionPrefs.tpUbwcMode(context)
val gpu = GpuInfo.detect()
val model = gpu.model
val version = if (model == 740) VulkanInfo.query()["driver_version"] else null
cached = features(model, version, gpu.oneUi8Gen2)
cached = features(model, version, gpu.oneUi8Gen2, mode)
activeMode = mode
resolved = true
Log.i(TAG, "Adreno $model${if (gpu.oneUi8Gen2) " (One UI)" else ""}, system driver ${version ?: "n/a"}: ${cached ?: "driver default"}")
Log.i(TAG, "Adreno $model${if (gpu.oneUi8Gen2) " (One UI)" else ""}, system driver ${version ?: "n/a"}, mode $mode: ${cached ?: "driver default"}")
return cached
}
fun applyToProcess() {
val value = forThisDevice() ?: return
fun restartRequired(context: Context): Boolean = resolved && activeMode != SessionPrefs.tpUbwcMode(context)
fun applyToProcess(context: Context) {
val value = forThisDevice(context) ?: return
runCatching { android.system.Os.setenv(ENV, value, true) }
.onFailure { Log.w(TAG, "setenv $ENV failed: ${it.javaClass.simpleName}") }
}
@@ -301,15 +301,18 @@ class LinuxNetworkLinkComponent(
}
}
private fun seededMac(): String {
val id = Settings.Secure.getString(appContext.contentResolver, Settings.Secure.ANDROID_ID) ?: "bannerlator"
val bytes = java.security.MessageDigest.getInstance("SHA-1").digest(id.toByteArray())
val b0 = (bytes[0].toInt() and 0xfc) or 0x02
return listOf(b0, bytes[1].toInt(), bytes[2].toInt(), bytes[3].toInt(), bytes[4].toInt(), bytes[5].toInt())
.joinToString(":") { "%02x".format(it and 0xff) }
}
private fun seededMac(): String =
seededMac { Settings.Secure.getString(appContext.contentResolver, Settings.Secure.ANDROID_ID) }
companion object {
internal fun seededMac(readId: () -> String?): String {
val id = runCatching(readId).getOrNull() ?: "bannerlator"
val bytes = java.security.MessageDigest.getInstance("SHA-1").digest(id.toByteArray())
val b0 = (bytes[0].toInt() and 0xfc) or 0x02
return listOf(b0, bytes[1].toInt(), bytes[2].toInt(), bytes[3].toInt(), bytes[4].toInt(), bytes[5].toInt())
.joinToString(":") { "%02x".format(it and 0xff) }
}
private const val TAG = "LinuxNetworkLink"
private const val LINK_FILE = "etc/droiddeck-net"
private const val LINK_INDEX = 2
@@ -721,13 +721,19 @@ object ComponentsManager {
class StoredOriginal(val protonId: String, val protonName: String?, val comp: String, val protonVersion: String, val size: Long, val kept: Boolean)
class Stored(val packages: List<StoredPackage>, val originals: List<StoredOriginal>)
private fun packagesInUse(state: JSONObject): Set<String> {
internal fun liveSelection(key: String, entry: JSONObject, proton: Proton?): Boolean =
proton != null && (key == "queued" || entry.optString("protonVersion") == proton.version)
private fun packagesInUse(state: JSONObject, installed: Map<String, Proton>): Set<String> {
val names = HashSet<String>()
for (key in listOf("active", "queued")) {
val byProton = state.optJSONObject(key) ?: continue
for (pid in byProton.keys()) {
val comps = byProton.optJSONObject(pid) ?: continue
for (comp in comps.keys()) comps.optJSONObject(comp)?.optString("file")?.takeIf { it.isNotEmpty() }?.let(names::add)
for (comp in comps.keys()) {
val entry = comps.optJSONObject(comp) ?: continue
if (liveSelection(key, entry, installed[pid])) entry.optString("file").takeIf { it.isNotEmpty() }?.let(names::add)
}
}
}
val profiles = state.optJSONObject("profiles")
@@ -747,8 +753,8 @@ object ComponentsManager {
fun stored(context: Context): Stored = synchronized(lock) {
val state = loadState(context)
val used = packagesInUse(state)
val installed = protons(context).associateBy { it.id }
val installed = protons(context).distinctBy { it.id }.associateBy { it.id }
val used = packagesInUse(state, installed)
val originals = originalsDir(context).listFiles()?.filter { it.isDirectory }?.flatMap { proton ->
proton.listFiles()?.filter { it.isDirectory }?.flatMap { version ->
COMPONENTS.mapNotNull { comp ->
@@ -777,24 +783,36 @@ object ComponentsManager {
fun deletePackage(context: Context, file: String): String = synchronized(lock) {
val name = safeName(file)
val state = loadState(context)
val queued = state.sub("queued")
for (pid in queued.keys()) {
val comps = queued.optJSONObject(pid) ?: continue
for (comp in comps.keys()) check(comps.optJSONObject(comp)?.optString("file") != name) { context.getString(R.string.cmgr_package_in_use, name, pid) }
}
val active = state.sub("active")
for (pid in active.keys()) {
val comps = active.optJSONObject(pid) ?: continue
for (comp in comps.keys()) check(comps.optJSONObject(comp)?.optString("file") != name) { context.getString(R.string.cmgr_package_in_use, name, pid) }
}
val profiles = state.sub("profiles")
for (scope in profiles.keys()) {
val profile = profiles.optJSONObject(scope) ?: continue
check(COMPONENTS.none { profile.optString(it) == name }) { context.getString(R.string.cmgr_package_in_use, name, scope) }
val installed = protons(context).distinctBy { it.id }.associateBy { it.id }
var changed = false
for (key in listOf("queued", "active")) {
val byProton = state.sub(key)
for (pid in byProton.keys().asSequence().toList()) {
val comps = byProton.optJSONObject(pid) ?: continue
for (comp in comps.keys().asSequence().toList()) {
val entry = comps.optJSONObject(comp) ?: continue
if (entry.optString("file") != name) continue
check(!liveSelection(key, entry, installed[pid])) { context.getString(R.string.cmgr_package_in_use, name, installed[pid]?.name ?: pid) }
comps.remove(comp)
changed = true
}
if (comps.length() == 0) byProton.remove(pid)
}
}
val f = File(packagesDir(context), name)
check(f.isFile) { context.getString(R.string.cmgr_package_not_stored, name) }
f.delete()
val profiles = state.sub("profiles")
for (scope in profiles.keys().asSequence().toList()) {
val profile = profiles.optJSONObject(scope) ?: continue
for (comp in COMPONENTS.filter { profile.optString(it) == name }) {
rememberProfiledComponent(state, comp)
profile.remove(comp)
changed = true
}
if (profile.length() == 0) profiles.remove(scope)
}
check(f.delete()) { name }
if (changed) saveState(context, state)
context.getString(R.string.cmgr_deleted, name)
}
@@ -26,6 +26,7 @@ object GpuClockPin {
pinned = true
"gpu clock: held at its top"
} catch (t: Throwable) {
File(context.filesDir, MARKER).delete()
Log.w(TAG, "pin", t)
"gpu clock: pin failed"
}
@@ -58,6 +58,7 @@ object SessionFiles {
"usr/local/bin/droiddeck-steam-install" to "usr/local/bin/droiddeck-steam-install",
"usr/local/bin/droiddeck-steam-ui-scale" to "usr/local/bin/droiddeck-steam-ui-scale",
"usr/local/bin/droiddeck-steam-language" to "usr/local/bin/droiddeck-steam-language",
"usr/local/bin/droiddeck-steam-shaders" to "usr/local/bin/droiddeck-steam-shaders",
"usr/local/bin/droiddeck-steam-desktop-ui" to "usr/local/bin/droiddeck-steam-desktop-ui",
"usr/local/bin/droiddeck-steam-library" to "usr/local/bin/droiddeck-steam-library",
"usr/local/bin/droiddeck-seed-redists" to "usr/local/bin/droiddeck-seed-redists",
@@ -78,6 +79,7 @@ object SessionFiles {
"usr/local/bin/droiddeck-steam-games" to "usr/local/bin/droiddeck-steam-games",
"usr/local/bin/droiddeck-pad-defaults" to "usr/local/bin/droiddeck-pad-defaults",
"usr/local/bin/droiddeck-steam-x64" to "usr/local/bin/droiddeck-steam-x64",
"usr/local/bin/droiddeck-steamrt-shim" to "usr/local/bin/droiddeck-steamrt-shim",
"usr/local/bin/droiddeck-x64-arm-proton" to "usr/local/bin/droiddeck-x64-arm-proton",
"usr/local/bin/droiddeck-x64-arm-webhelper" to "usr/local/bin/droiddeck-x64-arm-webhelper",
"usr/local/bin/droiddeck-x64-webhelper" to "usr/local/bin/droiddeck-x64-webhelper",
@@ -4,7 +4,6 @@ import android.content.Context
import android.content.pm.ActivityInfo
import androidx.annotation.StringRes
import com.droiddeck.launcher.R
import com.droiddeck.launcher.core.CpuAllocationDefaults
import com.droiddeck.launcher.core.GameEnvironment
import com.droiddeck.launcher.core.TextureFiltering
import com.droiddeck.launcher.gpu.Cardboard
@@ -50,9 +49,9 @@ object SessionPrefs {
)
fun orientation(context: Context): Int =
prefs(context).getInt("orientation", ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE)
prefs(context).getInt("orientation", ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE)
.takeIf { value -> orientationOptions.any { it.first == value } }
?: ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
?: ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE
fun setOrientation(context: Context, orientation: Int) {
require(orientationOptions.any { it.first == orientation })
@@ -263,6 +262,19 @@ object SessionPrefs {
const val GPU_DRIVERS_MANUAL = "manual"
const val GPU_DRIVERS_MIX = "mix"
const val TP_UBWC_AUTO = "auto"
const val TP_UBWC_ON = "on"
const val TP_UBWC_OFF = "off"
fun tpUbwcMode(context: Context): String =
prefs(context).getString("tpUbwcMode", TP_UBWC_AUTO)
?.takeIf { it in setOf(TP_UBWC_AUTO, TP_UBWC_ON, TP_UBWC_OFF) } ?: TP_UBWC_AUTO
fun setTpUbwcMode(context: Context, mode: String) {
require(mode in setOf(TP_UBWC_AUTO, TP_UBWC_ON, TP_UBWC_OFF))
prefs(context).edit().putString("tpUbwcMode", mode).commit()
}
fun gpuDriverMode(context: Context): String =
prefs(context).getString("gpuDriverMode", GPU_DRIVERS_AUTO) ?: GPU_DRIVERS_AUTO
@@ -304,6 +316,34 @@ object SessionPrefs {
prefs(context).edit().putBoolean("returnAfterGame", on).apply()
}
private fun shaderPrecacheApplied(context: Context) =
java.io.File(com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(context), "root/.bl-shader-precache-applied")
/**
* Shader pre-caching as the launcher last set it, until a session reports it written into the
* client's config.vdf; after that the client's own toggle is the user's again.
*/
fun pendingShaderPrecache(context: Context): Boolean? {
val prefs = prefs(context)
if (!prefs.contains("shaderPrecache")) return null
val on = prefs.getBoolean("shaderPrecache", true)
val applied = shaderPrecacheApplied(context)
val written = runCatching { applied.readText().trim() }.getOrNull() ?: return on
applied.delete()
if (written != if (on) "1" else "0") return on
prefs.edit().remove("shaderPrecache").apply()
return null
}
fun setShaderPrecache(context: Context, on: Boolean) {
shaderPrecacheApplied(context).delete()
prefs(context).edit().putBoolean("shaderPrecache", on).apply()
}
fun shaderPrecache(context: Context): Boolean = pendingShaderPrecache(context)
?: runCatching { com.droiddeck.launcher.storage.SteamStorage.shaderPrecache(
java.io.File(steamRoot(context, steamClientArch(context)), "config/config.vdf").readText()) }.getOrDefault(true)
fun stretch16x9(context: Context): Boolean = prefs(context).getBoolean("stretch16x9", false)
fun setStretch16x9(context: Context, on: Boolean) {
@@ -341,30 +381,19 @@ object SessionPrefs {
prefs(context).edit().putBoolean("wifiDiscoveryAsked", true).apply()
}
internal data class CoreAllocation(val clientOverride: Boolean, val clientCpus: String, val gameCpus: String)
internal fun coreAllocation(context: Context, defaults: CpuAllocationDefaults.Allocation? = CpuAllocationDefaults.device): CoreAllocation {
val saved = prefs(context)
return CoreAllocation(
saved.getBoolean("clientCpusOverride", defaults != null && !saved.contains("clientCpus")),
saved.getString("clientCpus", defaults?.client.orEmpty()).orEmpty(),
saved.getString("gameCpus", defaults?.game.orEmpty()).orEmpty(),
)
}
fun clientCpusOverride(context: Context): Boolean = coreAllocation(context).clientOverride
fun clientCpusOverride(context: Context): Boolean = prefs(context).getBoolean("clientCpusOverride", false)
fun setClientCpusOverride(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("clientCpusOverride", on).apply()
}
fun clientCpus(context: Context): String = coreAllocation(context).clientCpus
fun clientCpus(context: Context): String = prefs(context).getString("clientCpus", "").orEmpty()
fun setClientCpus(context: Context, list: String) {
prefs(context).edit().putString("clientCpus", list).apply()
}
fun gameCpus(context: Context): String = coreAllocation(context).gameCpus
fun gameCpus(context: Context): String = prefs(context).getString("gameCpus", "").orEmpty()
fun setGameCpus(context: Context, list: String) {
prefs(context).edit().putString("gameCpus", list).apply()
@@ -376,7 +405,7 @@ object SessionPrefs {
prefs(context).edit().putBoolean("noXalia", on).apply()
}
fun fastSync(context: Context): Boolean = prefs(context).getBoolean("fastSync", false)
fun fastSync(context: Context): Boolean = prefs(context).getBoolean("fastSync", true)
fun setFastSync(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("fastSync", on).apply()
@@ -411,6 +440,17 @@ object SessionPrefs {
.apply()
}
fun applyNtsyncDefault(context: Context) {
val prefs = prefs(context)
if (prefs.getBoolean("ntsyncDefaultV1", false)) return
prefs.edit()
.putBoolean("fastSync", true)
.putBoolean("fsyncFirst", false)
.putBoolean("syncFallback", true)
.putBoolean("ntsyncDefaultV1", true)
.apply()
}
fun syncFallback(context: Context): Boolean = prefs(context).getBoolean("syncFallback", true)
fun setSyncFallback(context: Context, on: Boolean) {
@@ -444,6 +484,13 @@ object SessionPrefs {
prefs(context).edit().putBoolean("prootFastPath", on).apply()
}
/** gamescope draws the cursor itself. Off by default: on a phone that plane costs frames. */
fun cursorComposite(context: Context): Boolean = prefs(context).getBoolean("cursorComposite", false)
fun setCursorComposite(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("cursorComposite", on).apply()
}
const val DEFAULT_GUEST_HOSTNAME = "DroidDeck"
@JvmStatic
@@ -764,6 +811,14 @@ object SessionPrefs {
it.getInt("gradientSecondary", com.droiddeck.launcher.ui.Themes.DEFAULT_SECONDARY)
}
/** How fast the Inner Gamer theme cycles its colours, 1 to 10. */
fun rgbSpeed(context: Context): Int =
prefs(context).getInt("innerGamerSpeed", com.droiddeck.launcher.ui.Themes.DEFAULT_RGB_SPEED).coerceIn(1, com.droiddeck.launcher.ui.Themes.RGB_SPEEDS)
fun setRgbSpeed(context: Context, speed: Int) {
prefs(context).edit().putInt("innerGamerSpeed", speed.coerceIn(1, com.droiddeck.launcher.ui.Themes.RGB_SPEEDS)).apply()
}
fun setGradientColors(context: Context, primary: Int, secondary: Int) {
prefs(context).edit().putInt("gradientPrimary", primary).putInt("gradientSecondary", secondary).apply()
}
@@ -335,6 +335,9 @@ class SessionService : Service() {
suspendAttemptFailed = false
suspendController = null
SessionState.suspended = false
SessionState.resumeRequested = false
SessionState.resuming = false
SessionState.resumeFailed = false
SessionState.pipActive = false
pipTask = false
SessionState.program = intent?.getStringExtra(EXTRA_PROGRAM)
@@ -401,7 +404,7 @@ class SessionService : Service() {
private fun runSession(gen: Int) {
SessionTerminal.clear()
com.droiddeck.launcher.gpu.TpUbwcHint.forThisDevice()
com.droiddeck.launcher.gpu.TpUbwcHint.forThisDevice(this)
try {
LinuxRuntime.writeAccounts(this)
} catch (e: Exception) {
@@ -678,6 +681,7 @@ class SessionService : Service() {
com.droiddeck.launcher.core.AppLanguage.system(this).country,
))
guest.add("TZ=" + java.util.TimeZone.getDefault().id)
if (SessionState.mode == MODE_STEAM) SessionPrefs.pendingShaderPrecache(this)?.let { guest.add("BL_SHADER_PRECACHE=" + if (it) "1" else "0") }
guest.add("XDG_RUNTIME_DIR=" + LinuxRuntime.GUEST_RUNTIME_DIR)
guest.add("XDG_SESSION_TYPE=wayland")
guest.add("WAYLAND_DISPLAY=wayland-0")
@@ -700,7 +704,6 @@ class SessionService : Service() {
val tuOverride = tuDebugOverride()
val tuDriver = sysmemDriver(linuxDriverId)
(tuOverride ?: "sysmem".takeIf { tuDriver || SessionPrefs.tuSysmem(this) })?.let { guest.add("TU_DEBUG=$it") }
com.droiddeck.launcher.gpu.TpUbwcHint.forThisDevice()?.let { guest.add("${com.droiddeck.launcher.gpu.TpUbwcHint.ENV}=$it") }
if (SessionPrefs.zinkLazy(this)) {
guest.add("ZINK_DESCRIPTORS=lazy")
guest.add("ZINK_DEBUG=compact")
@@ -724,11 +727,13 @@ class SessionService : Service() {
guest.add("BL_SYNC_FALLBACK=" + (if (SessionPrefs.syncFallback(this)) "1" else "0"))
guest.add("BL_FSYNC_FIRST=" + (if (SessionPrefs.fsyncFirst(this)) "1" else "0"))
guest.add("BL_GAMESCOPE_REALTIME=" + (if (SessionPrefs.gamescopeRealtime(this)) "1" else "0"))
if (SessionPrefs.cursorComposite(this)) guest.add("BL_CURSOR_COMPOSITE=1")
if (com.droiddeck.launcher.core.ZramSupport.supported()) guest.add("BL_ZRAM=1")
guest.add("BANNER_AUDIO_DIRECT_DECAY=0")
val extra = extraEnv() + com.droiddeck.launcher.agent.AgentEnv.beginSession(this)
if (extra.none { it.startsWith("TU_DEBUG=") }) guest.add("$GAME_TU_DEBUG=" + (tuOverride ?: if (tuDriver) "sysmem" else ""))
extra.forEach { guest.add(it) }
com.droiddeck.launcher.gpu.TpUbwcHint.forThisDevice(this)?.let { guest.add("${com.droiddeck.launcher.gpu.TpUbwcHint.ENV}=$it") }
val clientPinned = steamHere && SessionPrefs.clientCpusOverride(this)
if (clientPinned) {
guest.add("BL_CLIENT_CPUS=" + CpuCores.listOrAll(SessionPrefs.clientCpus(this)))
@@ -1218,6 +1223,7 @@ class SessionService : Service() {
}
private fun resumeSession(panelVisible: Boolean = true) {
if (SessionState.suspended) SessionState.resumeRequested = true
if (panelVisible) activityVisible = true
screenOn = readScreenOn()
manualPauseRequested = false
@@ -1418,6 +1424,9 @@ class SessionService : Service() {
val downloadsBlockingSuspend = downloadsKeepAwake() && hidden && !suspendDownloadNow
if (suspendPolicy == SessionPrefs.SUSPEND_MANUAL && hidden && !downloadsBlockingSuspend) {
manualPauseRequested = true
} else if (!hidden && !SessionState.suspended) {
// Coming back before the freeze finished keeps the game running instead of pausing it a moment later.
manualPauseRequested = false
}
val controller = suspendController ?: return
if (downloadsBlockingSuspend) acquireLocks()
@@ -1443,6 +1452,7 @@ class SessionService : Service() {
freezeCancelled = true
controller.cancelFreeze()
}
if (shouldSuspend && SessionState.suspended && !suspendOperationPending) SessionState.resumeRequested = false
if (suspendOperationPending || suspendAttemptFailed || shouldSuspend == SessionState.suspended) return
val gen = sessionGen
suspendOperationPending = true
@@ -1466,6 +1476,7 @@ class SessionService : Service() {
freezePending = false
if (success) {
SessionState.suspended = true
SessionState.resumeFailed = false
SessionEvents.transition(SessionPhase.SUSPENDED, "session.suspended")
releaseLocks()
refreshNotification()
@@ -1484,16 +1495,22 @@ class SessionService : Service() {
}
} else {
acquireLocks()
SessionState.resuming = true
controller.resume { success ->
mainHandler.post {
if (gen != sessionGen || !SessionState.running) return@post
suspendOperationPending = false
SessionState.resuming = false
SessionState.resumeRequested = false
if (success) {
SessionState.suspended = false
SessionState.resumeFailed = false
SessionEvents.transition(SessionEvents.resumePhase(), "session.resumed")
refreshNotification()
} else {
suspendAttemptFailed = true
SessionState.resumeFailures++
SessionState.resumeFailed = true
Log.w(TAG, "could not confirm that the session resumed")
}
updateSuspendPolicy()
@@ -1583,6 +1600,9 @@ class SessionService : Service() {
return@post
}
SessionState.suspended = false
SessionState.resumeRequested = false
SessionState.resuming = false
SessionState.resumeFailed = false
SessionState.pipActive = false
pipTask = false
SessionState.guestPid = -1
@@ -2047,6 +2067,7 @@ class SessionService : Service() {
fun resume(context: Context) {
if (!SessionState.running) return
if (SessionState.suspended) SessionState.resumeRequested = true
context.startService(Intent(context, SessionService::class.java).setAction(ACTION_RESUME))
}
@@ -2,6 +2,7 @@ package com.droiddeck.launcher.session
import java.io.File
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
@@ -46,6 +47,10 @@ object SessionState {
@Volatile
var runtimeDriver: String? = null
var suspended by mutableStateOf(false)
var resumeRequested by mutableStateOf(false)
var resuming by mutableStateOf(false)
var resumeFailures by mutableIntStateOf(0)
var resumeFailed by mutableStateOf(false)
@Volatile var pipActive = false
@Volatile
var program: String? = null
@@ -20,7 +20,7 @@ object SettingsReset {
"gpuDriverMode", "androidDriver", "linuxDriver", "linuxDriver.steam", "linuxDriver.desktop",
"tuSysmem", "glThread", "noGlError", "zinkLazy", "mangoapp", "gpuClockPin", "gamescopeRealtime",
"directAudio", "mic", "wifiDiscovery", "clientCpusOverride", "clientCpus", "gameCpus",
"noXalia", "fastSync", "fsyncFirst", "syncFallback", "prootNoSeccomp", "prootFastPath",
"noXalia", "fastSync", "fsyncFirst", "syncFallback", "prootNoSeccomp", "prootFastPath", "cursorComposite",
"guestHostname", "fexPreset", "forceSsbs", "logs", "storageDiagnostics",
"upscaler", "upscaleSharpness", "screenEffects", "textureAnisotropy", "textureLodBias",
"steamDownloadsInBackground", "steam_offline", "bootMovie", "bootMovieSound", "bootMovieVolume", "bootMovieSeconds",
@@ -28,6 +28,8 @@ object SteamStorage {
private val LAST_PLAYED = Regex("^\\s*\"LastPlayed\"\\s*\"(\\d+)\"", RegexOption.MULTILINE)
private val MAPPING = Regex("\"(\\d+)\"\\s*\\{\\s*\"name\"\\s*\"([^\"]*)\"")
private val COMPAT_NAME = Regex("\"compat_tools\"\\s*\\{\\s*\"([^\"]+)\"")
private val VDF_TOKEN = Regex("\"((?:\\\\.|[^\"\\\\])*)\"|[{}]|//[^\n]*")
private val SHADER_CACHE_OFF = listOf("InstallConfigStore", "Software", "Valve", "Steam", "ShaderCacheManager", "DisableShaderCache")
data class Manifest(
val file: File, val appId: Int, val name: String, val installDir: String?,
@@ -118,6 +120,28 @@ object SteamStorage {
return MAPPING.findAll(configVdf.substring(open, end)).associate { it.groupValues[1] to it.groupValues[2] }
}
fun shaderPrecache(configVdf: String): Boolean = vdfValue(configVdf, SHADER_CACHE_OFF) != "1"
private fun vdfValue(text: String, path: List<String>): String? {
val blocks = ArrayList<String>()
var key: String? = null
for (token in VDF_TOKEN.findAll(text)) {
val name = key
when {
token.value.startsWith("//") -> {}
token.value == "{" -> { blocks.add(name.orEmpty()); key = null }
token.value == "}" -> { blocks.removeLastOrNull(); key = null }
name == null -> key = token.groupValues[1]
else -> {
val at = blocks + name
if (at.size == path.size && at.zip(path).all { (a, b) -> a.equals(b, ignoreCase = true) }) return token.groupValues[1]
key = null
}
}
}
return null
}
fun compatToolName(compatibilityToolVdf: String): String? = COMPAT_NAME.find(compatibilityToolVdf)?.groupValues?.get(1)
private val ARM_IN_NAME = Regex("arm64|aarch64")
@@ -308,6 +308,7 @@ internal fun AppDialog(
width: Dp? = null, fitContent: Boolean = false,
back: (() -> Unit)? = null,
scrollable: Boolean = true,
scrollState: androidx.compose.foundation.ScrollState = rememberScrollState(),
content: @Composable ColumnScope.() -> Unit,
) {
val pal = LocalPalette.current
@@ -345,7 +346,7 @@ internal fun AppDialog(
.blockTouches()
.controllerBack(back ?: close)
.then(modifier)
.then(if (scrollable) Modifier.verticalScroll(rememberScrollState()) else Modifier)
.then(if (scrollable) Modifier.verticalScroll(scrollState) else Modifier)
.padding(horizontal = 18.dp, vertical = 16.dp),
content = content,
)
@@ -13,6 +13,7 @@ import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
@@ -70,12 +71,15 @@ internal fun ColorPickerDialog(title: String, initial: Int, onDismiss: () -> Uni
var hexText by remember { mutableStateOf(ThemeColors.hex(initial)) }
val current = ThemeColors.fromHsv(hue, sat, value)
val first = remember { FocusRequester() }
val scroll = rememberScrollState()
var typingHex by remember { mutableStateOf(false) }
LaunchedEffect(Unit) { focusSoon { first } }
LaunchedEffect(typingHex, scroll.maxValue) { if (typingHex) scroll.animateScrollTo(scroll.maxValue) }
fun picked(h: Float = hue, s: Float = sat, v: Float = value) {
hue = h.coerceIn(0f, 360f); sat = s.coerceIn(0f, 1f); value = v.coerceIn(0f, 1f)
hexText = ThemeColors.hex(ThemeColors.fromHsv(hue, sat, value))
}
AppDialog(shown, close, "colorPicker", wide = false, maxWidth = 460.dp) {
AppDialog(shown, close, "colorPicker", wide = false, maxWidth = 460.dp, scrollState = scroll) {
DialogTitleRow(title, close)
Row(horizontalArrangement = Arrangement.spacedBy(14.dp), verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {
ColorWheel(hue, sat, value) { h, s -> picked(h = h, s = s) }
@@ -95,6 +99,7 @@ internal fun ColorPickerDialog(title: String, initial: Int, onDismiss: () -> Uni
ThemeColors.parseHex(text)?.let { argb -> ThemeColors.toHsv(argb).let { hsv -> hue = hsv.h; sat = hsv.s; value = hsv.v } }
},
label = "", keyboardType = KeyboardType.Ascii, imeAction = ImeAction.Done, placeholder = stringResource(R.string.theme_color_hex),
onFocusChange = { typingHex = it },
onDone = { ThemeColors.parseHex(hexText)?.let { onApply(it); close() } },
)
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth()) {
@@ -27,6 +27,8 @@ import androidx.compose.material.icons.outlined.Image
import androidx.compose.material.icons.outlined.InsertDriveFile
import androidx.compose.material.icons.outlined.SdCard
import androidx.compose.material.icons.outlined.Smartphone
import androidx.compose.material.icons.outlined.Visibility
import androidx.compose.material.icons.outlined.VisibilityOff
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
@@ -81,8 +83,8 @@ internal class PickFolder(val dir: File, val readable: Boolean)
internal class PickListing(val folders: List<PickFolder>, val files: List<File>)
internal fun pickListing(dir: File, kind: PickKind): PickListing {
val all = dir.listFiles()?.filter { !it.name.startsWith(".") }.orEmpty().sortedBy { it.name.lowercase() }
internal fun pickListing(dir: File, kind: PickKind, showHidden: Boolean = false): PickListing {
val all = dir.listFiles()?.filter { showHidden || !it.name.startsWith(".") }.orEmpty().sortedBy { it.name.lowercase() }
return PickListing(
all.filter { it.isDirectory }.map { PickFolder(it, it.canRead() && it.list() != null) },
all.filter { it.isFile && it.extension.lowercase() in kind.extensions },
@@ -92,11 +94,13 @@ internal fun pickListing(dir: File, kind: PickKind): PickListing {
@Composable
internal fun ExePickerDialog(
title: String, kind: PickKind = PickKind.EXE, start: File? = null,
onAddAll: ((File) -> Unit)? = null, onPick: (File) -> Unit, onDismiss: () -> Unit,
onAddAll: ((File, Boolean) -> Unit)? = null, onPick: (File) -> Unit, onDismiss: () -> Unit,
) {
val ctx = LocalContext.current
val colors = MaterialTheme.colorScheme
val density = LocalDensity.current
val prefs = remember(ctx) { ctx.getSharedPreferences("game_picker", Context.MODE_PRIVATE) }
var showHidden by remember { mutableStateOf(prefs.getBoolean("show_hidden", false)) }
val shown = rememberShown(onDismiss)
val close = { shown.targetState = false }
val volumes = remember { pickVolumes(ctx) }
@@ -107,14 +111,23 @@ internal fun ExePickerDialog(
val back = { if (dir == null) close() else up() }
val first = remember(dir) { FocusRequester() }
LaunchedEffect(dir) { focusWithinFrames({ false }) { first } }
val listing = remember(dir) { dir?.let { pickListing(it, kind) } }
val listing = remember(dir, showHidden) { dir?.let { pickListing(it, kind, showHidden) } }
var locked by remember { mutableStateOf<Dp?>(null) }
AppDialog(
shown, close, "filePicker", wide = false, maxWidth = 520.dp, width = locked, fitContent = locked == null, back = back,
modifier = Modifier.onSizeChanged { if (locked == null && it.width > 0) locked = with(density) { it.width.toDp() } },
) {
Column(verticalArrangement = Arrangement.spacedBy(6.dp), modifier = Modifier.fillMaxWidth()) {
DialogTitleRow(title, onClose = close)
DialogTitleRow(title, onClose = close, leading = {
SmallIconButton(
if (showHidden) Icons.Outlined.VisibilityOff else Icons.Outlined.Visibility,
stringResource(if (showHidden) R.string.fm_hide_hidden else R.string.fm_show_hidden),
if (showHidden) colors.primary else colors.onSurfaceVariant,
) {
showHidden = !showHidden
prefs.edit().putBoolean("show_hidden", showHidden).apply()
}
})
if (dir != null && volume != null) {
val crumbs = listOf(volume.label) + dir!!.path.removePrefix(volume.root.path).split('/').filter { it.isNotEmpty() }
Text(crumbs.joinToString(" › "), fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
@@ -135,7 +148,7 @@ internal fun ExePickerDialog(
val shownListing = listing ?: PickListing(emptyList(), emptyList())
PickerRow(Icons.AutoMirrored.Outlined.ArrowBack, "..", null, focus = first, onClick = up)
if (onAddAll != null && shownListing.folders.any { it.readable }) {
PickerRow(Icons.Filled.Add, stringResource(R.string.games_add_all), null, accent = true) { onAddAll(dir!!); close() }
PickerRow(Icons.Filled.Add, stringResource(R.string.games_add_all), null, accent = true) { onAddAll(dir!!, showHidden); close() }
}
for (f in shownListing.folders) key(f.dir.path) {
PickerRow(Icons.Outlined.Folder, f.dir.name, null, enabled = f.readable) { dir = f.dir }
@@ -424,7 +424,7 @@ private fun GamesDialogs(a: FrontEndActions, games: List<Library.SteamGame>) {
val st = GamesDialogState
if (st.adding) ExePickerDialog(
stringResource(R.string.games_add_title),
onAddAll = { dir ->
onAddAll = { dir, showHidden ->
st.summary = emptyList<com.droiddeck.launcher.frontend.AddedGames.Game>() to 0
st.checking = dir.name
scope.launch {
@@ -433,6 +433,7 @@ private fun GamesDialogs(a: FrontEndActions, games: List<Library.SteamGame>) {
ctx.applicationContext, dir,
onGame = { g -> scope.launch { st.summary?.let { (list, n) -> st.summary = (list + g) to n } } },
onChecking = { name -> scope.launch { st.checking = name } },
showHidden = showHidden,
)
}
st.checking = null
@@ -132,7 +132,7 @@ class FrontEndState(
val controller: com.droiddeck.launcher.input.ControllerPrefs.Settings? = null,
val phantomProcessStatus: PhantomProcessStatus = PhantomProcessStatus.NOT_APPLICABLE,
val showPhantomGate: Boolean = false,
val orientation: Int = android.content.pm.ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE,
val orientation: Int = android.content.pm.ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE,
val launcherFullscreen: Boolean = true,
val downloadSource: String = DownloadSource.MODE_AUTO,
val downloadMirror: String = "",
@@ -359,6 +359,7 @@ internal fun SetupPanel(
}
}
}
if (s.theme == Themes.INNER_GAMER) RgbSpeedRow()
if (s.theme == Themes.GRADIENT) GradientColorRows()
ChoiceRow(
host, "app-scale", stringResource(R.string.setup_app_scale), stringResource(R.string.setup_app_scale_hint),
@@ -792,6 +793,13 @@ private fun LanguageRow(host: MenuHost, chosen: String, onPick: (String) -> Unit
}
}
/** How fast Inner Gamer cycles its colours. */
@Composable
private fun RgbSpeedRow() {
val ctx = androidx.compose.ui.platform.LocalContext.current.applicationContext
SliderRow(stringResource(R.string.theme_rgb_speed), stringResource(R.string.theme_rgb_speed_hint), Themes.rgbSpeed, 1..Themes.RGB_SPEEDS) { Themes.setRgbSpeed(ctx, it) }
}
/** The two colours of the Gradient theme, each a small square that opens the colour picker. */
@Composable
private fun GradientColorRows() {
@@ -23,6 +23,7 @@ import androidx.compose.ui.platform.LocalClipboardManager
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.AnnotatedString
import com.droiddeck.launcher.gpu.DeviceInfo
import com.droiddeck.launcher.session.SessionPrefs
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import androidx.compose.ui.res.stringResource
@@ -128,6 +129,8 @@ class GpuDriversState(
val runtime: DriverSlot = DriverSlot(),
val canRestart: Boolean = true,
val checkedAt: Long = 0L,
val tpUbwcMode: String? = null,
val tpUbwcRestartRequired: Boolean = false,
) {
val activePair: PairRow? get() = pairs.firstOrNull { it.active }
}
@@ -147,6 +150,7 @@ class GpuDriversActions(
val onRestoreBundled: () -> Unit = {},
val onMode: (String) -> Unit = {},
val onRestart: () -> Unit = {},
val onTpUbwcMode: (String) -> Unit = {},
)
@Composable
@@ -259,6 +263,27 @@ internal fun GpuDriversBody(
GPU_MODE_PAIR -> PairBody(gpu, actions)
else -> MixBody(single, actions, slotFocus, onOpenSlot)
}
gpu.tpUbwcMode?.let { selected ->
var advanced by rememberSaveable { mutableStateOf(false) }
SecondaryButton(stringResource(R.string.gpu_advanced) + if (advanced) " ▴" else " ▾", modifier = Modifier.fillMaxWidth()) { advanced = !advanced }
AnimatedVisibility(advanced) {
Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
ChoiceRow(
rememberMenuHost(), "tp-ubwc", stringResource(R.string.gpu_ubwc_title),
stringResource(R.string.gpu_ubwc_hint),
listOf(
SessionPrefs.TP_UBWC_AUTO to stringResource(R.string.common_auto),
SessionPrefs.TP_UBWC_ON to stringResource(R.string.widgets_on),
SessionPrefs.TP_UBWC_OFF to stringResource(R.string.widgets_off),
), selected, onPick = actions.onTpUbwcMode,
)
if (gpu.tpUbwcRestartRequired) {
Text(stringResource(R.string.gpu_ubwc_restart), fontSize = 13.sp, color = AttentionAmber)
if (gpu.canRestart) SecondaryButton(stringResource(R.string.gpu_restart_now), onClick = actions.onRestart)
}
}
}
}
}
}
@@ -82,6 +82,8 @@ class ModeSettings(
val steamClientArch: String? = null,
/** Steam only: a game launched from the front end returns there when it closes; null hides the row. */
val returnAfterGame: Boolean? = null,
/** Steam only: the client's Shader Pre-Caching setting; null hides the row. */
val shaderPrecache: Boolean? = null,
val steamRepairQueued: Boolean = false,
val mangoapp: Boolean = true,
val steamController: String? = null,
@@ -136,6 +138,7 @@ class ModeSettingsActions(
val onSteamClientArch: (String) -> Unit = {},
val onMangoapp: (Boolean) -> Unit = {},
val onReturnAfterGame: (Boolean) -> Unit = {},
val onShaderPrecache: (Boolean) -> Unit = {},
val onSteamController: (String) -> Unit = {},
val onUnfoldedControls: (Boolean) -> Unit = {},
val onUnfoldedControlsWithController: (Boolean) -> Unit = {},
@@ -478,6 +481,11 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras:
stringResource(R.string.mode_return_after_game_hint),
s.returnAfterGame, onChange = a.onReturnAfterGame,
)
if (s.shaderPrecache != null) ToggleRow(
host, "shaderprecache", stringResource(R.string.mode_shader_precache),
stringResource(R.string.mode_shader_precache_hint),
s.shaderPrecache, onChange = a.onShaderPrecache,
)
SettingsRow(
stringResource(R.string.mode_steam_repair),
stringResource(if (s.steamRepairQueued) R.string.mode_steam_repair_queued else R.string.mode_steam_repair_hint),
@@ -46,6 +46,7 @@ fun PerformancePage(
gpuClockPin: Boolean,
prootNoSeccomp: Boolean,
prootFastPath: Boolean,
cursorComposite: Boolean,
guestHostname: String,
phantomWarning: String?,
onClientOverride: (Boolean) -> Unit,
@@ -61,6 +62,7 @@ fun PerformancePage(
onGpuClockPin: (Boolean) -> Unit,
onProotNoSeccomp: (Boolean) -> Unit,
onProotFastPath: (Boolean) -> Unit,
onCursorComposite: (Boolean) -> Unit,
onGuestHostname: (String) -> Unit,
onClientCore: (Int, Boolean) -> Unit,
onGameCore: (Int, Boolean) -> Unit,
@@ -158,6 +160,11 @@ fun PerformancePage(
else stringResource(R.string.perf_fastpath_hint),
prootFastPath && !prootNoSeccomp, enabled = !prootNoSeccomp, onChange = onProotFastPath,
)
ToggleRow(
host, "cursorcomposite", stringResource(R.string.perf_cursor_composite),
stringResource(R.string.perf_cursor_composite_hint),
cursorComposite, onChange = onCursorComposite,
)
}
SettingsGroup(stringResource(R.string.perf_identity)) {
var draft by remember(guestHostname) { mutableStateOf(guestHostname) }
@@ -24,7 +24,6 @@ import androidx.compose.animation.core.FastOutSlowInEasing
import androidx.compose.animation.core.tween
import androidx.compose.material.icons.Icons
import androidx.compose.foundation.layout.heightIn
import androidx.compose.material.icons.filled.Pause
import androidx.compose.foundation.rememberScrollState
import androidx.compose.material3.Icon
import androidx.compose.foundation.Canvas
@@ -345,37 +344,3 @@ private fun CancelHint(onCancel: () -> Unit, modifier: Modifier = Modifier) {
Text(stringResource(R.string.common_cancel), fontSize = 13.sp, color = colors.onSurfaceVariant)
}
}
@Composable
fun SessionPausedOverlay(title: String = stringResource(R.string.load_steam_paused), onResume: () -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val resumeFocus = remember { FocusRequester() }
LaunchedEffect(Unit) {
androidx.compose.runtime.withFrameNanos { }
runCatching { resumeFocus.requestFocus() }
}
Box(
modifier = Modifier
.fillMaxSize()
.background(pal.background.copy(alpha = 0.94f))
.blockTouches(),
contentAlignment = Alignment.Center,
) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(10.dp),
modifier = Modifier.widthIn(max = 440.dp).padding(32.dp),
) {
Box(contentAlignment = Alignment.Center, modifier = Modifier.padding(bottom = 6.dp).size(64.dp).border(2.dp, pal.line2, CircleShape)) {
Icon(Icons.Filled.Pause, contentDescription = null, tint = colors.onBackground, modifier = Modifier.size(30.dp))
}
Text(title, fontSize = 28.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, textAlign = TextAlign.Center)
PrimaryButton(
stringResource(R.string.resume_session),
modifier = Modifier.padding(top = 14.dp).focusRequester(resumeFocus).controllerConfirm(onClick = onResume),
onClick = onResume,
)
}
}
}
@@ -0,0 +1,276 @@
package com.droiddeck.launcher.ui
import android.os.Build
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.CubicBezierEasing
import androidx.compose.animation.core.FastOutLinearInEasing
import androidx.compose.animation.core.LinearEasing
import androidx.compose.animation.core.LinearOutSlowInEasing
import androidx.compose.animation.core.Spring
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.infiniteRepeatable
import androidx.compose.animation.core.keyframes
import androidx.compose.animation.core.rememberInfiniteTransition
import androidx.compose.animation.core.tween
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxScope
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.PlayArrow
import androidx.compose.material3.Icon
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.State
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.snapshotFlow
import androidx.compose.runtime.setValue
import androidx.compose.runtime.withFrameNanos
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.blur
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.drawWithContent
import androidx.compose.ui.draw.drawBehind
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.graphics.ColorMatrix
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.graphics.drawscope.rotate
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp
import com.droiddeck.launcher.R
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import kotlinx.coroutines.withTimeoutOrNull
/** The last game frame, captured as the session left the screen, and where it sat in the overlay. */
class PausedFrame(val image: ImageBitmap, val bounds: android.graphics.Rect)
private const val CARD_SCALE = 0.82f
private const val FRAME_WAIT_MS = 600L
private fun tone(saturation: Float, brightness: Float): ColorMatrix =
ColorMatrix().apply {
setToSaturation(saturation)
timesAssign(ColorMatrix().apply { setToScale(brightness, brightness, brightness, 1f) })
}
@Composable
fun SessionPausedOverlay(
suspended: Boolean,
engaged: Boolean,
failures: Int,
frame: PausedFrame?,
title: String,
onResume: () -> Unit,
onFrameNeeded: () -> Unit,
onHidden: () -> Unit,
) {
val currentFrame by rememberUpdatedState(frame)
var shown by remember { mutableStateOf(suspended) }
val lift = remember { Animatable(if (suspended) 1f else 0f) }
val orb = remember { Animatable(if (suspended) 1f else 0f) }
val press = remember { Animatable(1f) }
val ring = remember { Animatable(0f) }
val shake = remember { Animatable(0f) }
LaunchedEffect(suspended, engaged) {
when {
suspended && !engaged -> {
if (!shown) {
if (currentFrame == null) {
onFrameNeeded()
withTimeoutOrNull(FRAME_WAIT_MS) { snapshotFlow { currentFrame }.first { it != null } }
}
// Pausing mostly happens while the screen is off or the app is away, so it appears already settled.
press.snapTo(1f)
ring.snapTo(0f)
lift.snapTo(1f)
orb.snapTo(1f)
shown = true
return@LaunchedEffect
}
launch { press.animateTo(1f, Motion.sp(0.5f, Spring.StiffnessMedium)) }
launch { ring.animateTo(0f, Motion.tw(200)) }
orb.animateTo(1f, Motion.tw(200))
}
suspended -> {
if (!shown) return@LaunchedEffect
launch { orb.animateTo(1f, Motion.tw(200)) }
launch { press.animateTo(0.92f, Motion.tw(140)) }
ring.animateTo(0.25f, Motion.tw(140))
ring.animateTo(0.8f, Motion.tw(650, easing = CubicBezierEasing(0.1f, 0.6f, 0.3f, 1f)))
ring.animateTo(0.92f, Motion.tw(2000, easing = LinearOutSlowInEasing))
}
shown -> {
ring.animateTo(1f, Motion.tw(110))
coroutineScope {
launch { orb.animateTo(0f, Motion.tw(220, easing = FastOutLinearInEasing)) }
lift.animateTo(0f, Motion.sp(0.62f, 380f))
}
shown = false
ring.snapTo(0f)
press.snapTo(1f)
onHidden()
}
}
}
val seenFailures = remember { mutableIntStateOf(failures) }
LaunchedEffect(failures) {
if (failures == seenFailures.intValue) return@LaunchedEffect
seenFailures.intValue = failures
if (!shown || Motion.scale == 0f) return@LaunchedEffect
shake.animateTo(0f, keyframes {
durationMillis = Motion.ms(360)
10f at Motion.ms(60)
-8f at Motion.ms(140)
5f at Motion.ms(220)
-2f at Motion.ms(300)
})
}
if (!shown) return
val presence = lift.value.coerceIn(0f, 1f)
val idle = suspended && !engaged
val focus = remember { FocusRequester() }
LaunchedEffect(Unit) {
withFrameNanos { }
runCatching { focus.requestFocus() }
}
val resumeLabel = stringResource(R.string.resume_session)
Box(
contentAlignment = Alignment.Center,
modifier = Modifier
.fillMaxSize()
.semantics { contentDescription = title }
.focusRequester(focus)
.controllerConfirm(enabled = idle, onClick = onResume)
.clickable(
interactionSource = remember { MutableInteractionSource() },
indication = null,
role = Role.Button,
onClickLabel = resumeLabel,
) { if (idle) onResume() },
) {
if (frame != null) {
PausedCard(frame, lift.value, presence)
} else {
Box(Modifier.fillMaxSize().graphicsLayer { alpha = presence }.background(Color.Black.copy(alpha = 0.55f)))
}
ResumeOrb(orb.value, press.value, ring.value, shake.value, idle)
}
}
@Composable
private fun BoxScope.PausedCard(frame: PausedFrame, lift: Float, presence: Float) {
val density = LocalDensity.current
val bounds = frame.bounds
val ambient = remember { ColorFilter.colorMatrix(tone(0.1f, 0.3f)) }
Box(Modifier.fillMaxSize().graphicsLayer { alpha = presence }.background(Color.Black)) {
Image(
frame.image, contentDescription = null, contentScale = ContentScale.Crop, colorFilter = ambient,
modifier = Modifier.fillMaxSize().then(if (Build.VERSION.SDK_INT >= 31) Modifier.blur(32.dp) else Modifier),
)
}
Image(
frame.image, contentDescription = null, contentScale = ContentScale.FillBounds,
colorFilter = ColorFilter.colorMatrix(tone(1f - 0.92f * presence, 1f - 0.45f * presence)),
modifier = Modifier
.align(Alignment.TopStart)
.offset { IntOffset(bounds.left, bounds.top) }
.size(with(density) { bounds.width().toDp() }, with(density) { bounds.height().toDp() })
.graphicsLayer {
val scale = 1f - (1f - CARD_SCALE) * lift
scaleX = scale
scaleY = scale
shape = RoundedCornerShape((20f * presence).dp)
clip = true
shadowElevation = 24.dp.toPx() * presence
},
)
}
@Composable
private fun ResumeOrb(presence: Float, press: Float, ring: Float, shake: Float, idle: Boolean) {
val glintAlpha by animateFloatAsState(if (idle) 1f else 0f, Motion.tw(160), label = "glintAlpha")
val glint: State<Float>? = if (Motion.scale > 0f) {
rememberInfiniteTransition(label = "glint").animateFloat(
0f, 360f, infiniteRepeatable(tween(Motion.ms(3600), easing = LinearEasing)), label = "glintAngle",
)
} else null
Box(
contentAlignment = Alignment.Center,
modifier = Modifier
.size(96.dp)
.graphicsLayer {
val scale = press * (0.4f + 0.6f * presence)
scaleX = scale
scaleY = scale
alpha = presence.coerceIn(0f, 1f)
translationX = shake.dp.toPx()
}
.drawBehind {
val halo = size.minDimension * 0.8f
drawCircle(Brush.radialGradient(0.6f to Color.Black.copy(alpha = 0.35f), 1f to Color.Transparent, radius = halo), radius = halo)
}
.clip(CircleShape)
.background(Color.White.copy(alpha = 0.08f))
.drawWithContent {
drawContent()
val stroke = 2.5.dp.toPx()
val radius = size.minDimension / 2f * 0.92f
if (glint != null && glintAlpha > 0f) {
rotate(glint.value) {
drawCircle(
Brush.sweepGradient(
0f to Color.Transparent,
0.083f to Color.White.copy(alpha = 0.4f * glintAlpha),
0.166f to Color.Transparent,
1f to Color.Transparent,
),
radius = radius, style = Stroke(stroke),
)
}
}
if (ring > 0f) {
drawArc(
Color.White, startAngle = -90f, sweepAngle = 360f * ring.coerceAtMost(1f), useCenter = false,
topLeft = Offset(center.x - radius, center.y - radius), size = Size(radius * 2f, radius * 2f),
style = Stroke(stroke, cap = StrokeCap.Round),
)
}
},
) {
Icon(Icons.Rounded.PlayArrow, contentDescription = null, tint = Color.White, modifier = Modifier.size(48.dp))
}
}
@@ -3,7 +3,15 @@ package com.droiddeck.launcher.ui
import androidx.annotation.StringRes
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.animation.core.LinearEasing
import androidx.compose.animation.core.RepeatMode
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.infiniteRepeatable
import androidx.compose.animation.core.rememberInfiniteTransition
import androidx.compose.animation.core.tween
import androidx.compose.runtime.Composable
import androidx.compose.runtime.key
import androidx.compose.runtime.SideEffect
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.staticCompositionLocalOf
import androidx.compose.runtime.getValue
@@ -13,6 +21,7 @@ import android.content.Context
import androidx.compose.runtime.remember
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.luminance
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalContext
import com.droiddeck.launcher.R
import androidx.compose.ui.platform.LocalConfiguration
@@ -33,6 +42,7 @@ object Themes {
const val PAPER = "paper"
const val ICON_BLUE = "blue"
const val ELECTRIC = "electric"
const val INNER_GAMER = "inner_gamer"
const val GRADIENT = "gradient"
const val DEFAULT_PRIMARY = 0xFF8B5CF6.toInt()
@@ -42,10 +52,42 @@ object Themes {
var gradientColors by mutableStateOf(DEFAULT_PRIMARY to DEFAULT_SECONDARY)
private set
const val RGB_SPEEDS = 10
const val DEFAULT_RGB_SPEED = 3
const val RGB_HUE_STEP = 3f
/** How fast Inner Gamer cycles, 1 (slow) to [RGB_SPEEDS] (fast). */
var rgbSpeed by mutableStateOf(DEFAULT_RGB_SPEED)
private set
/** Where Inner Gamer is on the colour wheel, in whole [RGB_HUE_STEP] steps so the app restyles only when the colour visibly moves. */
var rgbHue by mutableStateOf(0f)
private set
fun moveRgbHue(hue: Float) {
rgbHue = hue
}
fun setRgbSpeed(context: Context, speed: Int) {
val value = speed.coerceIn(1, RGB_SPEEDS)
SessionPrefs.setRgbSpeed(context, value)
rgbSpeed = value
}
/** Milliseconds for one trip round the colour wheel. */
fun rgbCycleMillis(speed: Int): Int = 30_000 / speed.coerceIn(1, RGB_SPEEDS)
fun loadGradient(context: Context) {
gradientColors = SessionPrefs.gradientColors(context)
rgbSpeed = SessionPrefs.rgbSpeed(context)
}
/** The Inner Gamer palette at one point on the colour wheel. */
fun innerGamer(hue: Float): Palette = ThemeColors.palette(
Color.hsv(hue % 360f, 0.9f, 1f).toArgb(), Color.hsv((hue + 60f) % 360f, 0.9f, 1f).toArgb(),
R.string.theme_inner_gamer, R.string.theme_inner_gamer_detail, INNER_GAMER,
)
fun setGradient(context: Context, primary: Int, secondary: Int) {
SessionPrefs.setGradientColors(context, primary, secondary)
gradientColors = primary to secondary
@@ -54,7 +96,7 @@ object Themes {
/** The theme the person chose, with the custom colours read first; for code that is not in a composition. */
fun current(context: Context): Palette {
val id = SessionPrefs.theme(context)
if (id == GRADIENT) loadGradient(context)
if (id == GRADIENT || id == INNER_GAMER) loadGradient(context)
return byId(id)
}
@@ -87,10 +129,12 @@ object Themes {
primary = Color(0xFF2E86FF), primary2 = Color(0xFF2684FF), onPrimary = Color(0xFF03111F), signal = Color(0xFF2E86FF),
good = Color(0xFF4CD37F),
),
innerGamer(0f),
ThemeColors.palette(DEFAULT_PRIMARY, DEFAULT_SECONDARY, R.string.theme_gradient, R.string.theme_gradient_detail),
)
fun byId(id: String): Palette {
if (id == INNER_GAMER) return innerGamer(rgbHue)
if (id == GRADIENT) return ThemeColors.palette(gradientColors.first, gradientColors.second, R.string.theme_gradient, R.string.theme_gradient_detail)
return all.firstOrNull { it.id == id } ?: all[0]
}
@@ -103,6 +147,7 @@ val Palette.onSignal: Color get() = if (signal.luminance() > 0.18f) Color(0xFF03
@Composable
fun DroidDeckTheme(theme: String? = null, appScale: Int = AppUiPrefs.DEFAULT_SCALE, content: @Composable () -> Unit) {
val id = theme ?: SessionPrefs.theme(LocalContext.current)
if (id == Themes.INNER_GAMER) InnerGamerHue(Themes.rgbSpeed)
val p = Themes.byId(id)
val scheme = darkColorScheme(
primary = p.primary, onPrimary = p.onPrimary, secondary = p.onSurfaceVariant,
@@ -121,3 +166,21 @@ fun DroidDeckTheme(theme: String? = null, appScale: Int = AppUiPrefs.DEFAULT_SCA
LocalConfiguration provides configuration,
) { MaterialTheme(colorScheme = scheme, content = content) }
}
/** Turns the colour wheel on the system's own animation clock; with animations off, in the app or in Android, the colour holds still. */
@Composable
private fun InnerGamerHue(speed: Int) {
if (Motion.scale == 0f) return
key(speed) { InnerGamerCycle(speed) }
}
/** One run of the cycle at one speed, picking up from the colour on screen so a new speed takes over at once without a jump. */
@Composable
private fun InnerGamerCycle(speed: Int) {
val start = remember { Themes.rgbHue }
val hue by rememberInfiniteTransition(label = "innerGamer").animateFloat(
start, start + 360f, infiniteRepeatable(tween(Themes.rgbCycleMillis(speed).coerceAtLeast(1), easing = LinearEasing), RepeatMode.Restart), label = "hue",
)
val stepped = ((hue % 360f) / Themes.RGB_HUE_STEP).toInt() * Themes.RGB_HUE_STEP
SideEffect { Themes.moveRgbHue(stepped) }
}
@@ -132,7 +132,7 @@ internal object ThemeColors {
}
}
fun palette(primary: Int, secondary: Int, label: Int, detail: Int): Palette {
fun palette(primary: Int, secondary: Int, label: Int, detail: Int, id: String = Themes.GRADIENT): Palette {
val seen = readable(primary)
val seenSecond = readable(secondary)
val ink = inkFor(seen, seenSecond)
@@ -146,7 +146,7 @@ internal object ThemeColors {
second = nextSecond
}
return Palette(
Themes.GRADIENT, label, detail,
id, label, detail,
background = tint(first, 0.50f, 0.045f), surface = tint(first, 0.45f, 0.075f), surfaceVariant = tint(first, 0.42f, 0.115f),
line = tint(first, 0.40f, 0.16f), line2 = tint(first, 0.36f, 0.22f),
onBackground = tint(first, 0.05f, 0.97f), onSurfaceVariant = tint(first, 0.16f, 0.68f),
@@ -23,6 +23,7 @@ object CompositorHost {
@Synchronized
fun startOrAttach(
context: android.content.Context,
surface: Surface,
xdgRuntimeDir: String,
driverPath: String?,
@@ -41,7 +42,7 @@ object CompositorHost {
resumeVsync()
return false
}
com.droiddeck.launcher.gpu.TpUbwcHint.applyToProcess()
com.droiddeck.launcher.gpu.TpUbwcHint.applyToProcess(context)
WaylandCompositor.nativeStartWithSurface(
surface, xdgRuntimeDir, driverPath, libraryName, nativeLibDir,
)