mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-12-04 12:05:39 +00:00
Compare commits
9
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
883e8d40f6 | ||
|
|
10c12b2998 | ||
|
|
0cafa83ea7 | ||
|
|
435beb7f19 | ||
|
|
78fcb60fd5 | ||
|
|
4995b3553b | ||
|
|
3c2878cc52 | ||
|
|
715032062d | ||
|
|
dde08414fc |
No files matched your search
@@ -186,7 +186,7 @@ jobs:
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: app/src/main/assets/linuxfs
|
||||
key: preloads-${{ env.PRELOAD_CACHE_VERSION }}-${{ hashFiles('app/src/main/cpp/fakeinput_steam.cpp', 'tools/linuxfs/preload/*.c', 'tools/linuxfs/build-x86-preloads.sh', 'tools/linuxfs/fex/*', 'tools/linuxfs/clipboard/*.c', 'tools/linuxfs/ssbs/*.c', 'tools/proot/fastpath/*.c', 'tools/linuxfs/overlay/usr/local/bin/*', 'tools/linuxfs/overlay/usr/bin/**', 'tools/linuxfs/desktop/*', 'tools/gamescope/release.env', 'tools/wlroots/release.env', 'tools/linuxfs/uruntime.env', 'tools/linuxfs/licenses/*', 'tools/mangoapp/*', 'tools/msitools/**', 'tools/linuxfs/debian-image.env') }}
|
||||
key: preloads-${{ env.PRELOAD_CACHE_VERSION }}-${{ hashFiles('app/src/main/cpp/fakeinput_steam.cpp', 'app/src/main/cpp/adrenotools/src/hook/kgsl.h', 'tools/quest/*', 'tools/linuxfs/preload/*.c', 'tools/linuxfs/build-x86-preloads.sh', 'tools/linuxfs/fex/*', 'tools/linuxfs/clipboard/*.c', 'tools/linuxfs/ssbs/*.c', 'tools/proot/fastpath/*.c', 'tools/linuxfs/overlay/usr/local/bin/*', 'tools/linuxfs/overlay/usr/bin/**', 'tools/linuxfs/desktop/*', 'tools/gamescope/release.env', 'tools/wlroots/release.env', 'tools/linuxfs/uruntime.env', 'tools/linuxfs/licenses/*', 'tools/mangoapp/*', 'tools/msitools/**', 'tools/linuxfs/debian-image.env') }}
|
||||
|
||||
- name: Build libfakeinput.so and libblsession.so (glibc aarch64)
|
||||
if: steps.preloads.outputs.cache-hit != 'true'
|
||||
@@ -457,6 +457,7 @@ jobs:
|
||||
SGDB_API_KEY: ${{ secrets.SGDB_API_KEY }}
|
||||
run: |
|
||||
set -o pipefail
|
||||
python3 tools/quest/build-driver.py "$ANDROID_HOME/ndk/$NDK_VERSION"
|
||||
python3 tools/release/runtime_inputs.py record
|
||||
./gradlew assembleRelease --console=plain -PndkVersion="$NDK_VERSION" 2>&1 | tee /tmp/build.log
|
||||
python3 tools/release/check_session_assets.py app/build/outputs/apk/release/app-release.apk
|
||||
|
||||
@@ -302,4 +302,7 @@ dependencies {
|
||||
|
||||
testImplementation 'junit:junit:4.13.2'
|
||||
testImplementation 'org.robolectric:robolectric:4.16.1'
|
||||
testImplementation 'androidx.compose.ui:ui-test-junit4'
|
||||
// The Android archive does not include the host natives used by JVM archive tests.
|
||||
testRuntimeOnly 'com.github.luben:zstd-jni:1.5.2-3@jar'
|
||||
}
|
||||
@@ -3600,6 +3600,13 @@ static bool wait_snapshot(std::shared_ptr<FakeController> fake,
|
||||
}
|
||||
}
|
||||
|
||||
static int forward_ioctl(int fd, ioctl_request_t op, void *argp) {
|
||||
using ioctl_fn = int (*)(int, ioctl_request_t, ...);
|
||||
// Preserve later preload hooks, including GPU allocation adapters.
|
||||
static const auto next = reinterpret_cast<ioctl_fn>(dlsym(RTLD_NEXT, "ioctl"));
|
||||
return next ? next(fd, op, argp) : static_cast<int>(syscall(SYS_ioctl, fd, op, argp));
|
||||
}
|
||||
|
||||
EXPORT int ioctl(int fd, ioctl_request_t op, ...) {
|
||||
va_list va;
|
||||
void *argp;
|
||||
@@ -3611,7 +3618,7 @@ EXPORT int ioctl(int fd, ioctl_request_t op, ...) {
|
||||
// The lock must not be held across the passthrough: binder's transport is a
|
||||
// blocking ioctl(BINDER_WRITE_READ), so a parked binder pool thread would own
|
||||
// controller_mutex() for as long as it waits and deadlock every other ioctl.
|
||||
if (!watched(fd)) return syscall(SYS_ioctl, fd, op, argp);
|
||||
if (!watched(fd)) return forward_ioctl(fd, op, argp);
|
||||
std::unique_lock<std::recursive_mutex> guard(controller_mutex());
|
||||
auto maker = uinput_map().find(fd);
|
||||
if (maker != uinput_map().end()) return ioctl_uinput(*maker->second, op, argp);
|
||||
@@ -3629,7 +3636,7 @@ EXPORT int ioctl(int fd, ioctl_request_t op, ...) {
|
||||
auto controller = controller_map().find(fd);
|
||||
if (controller == controller_map().end()) {
|
||||
guard.unlock();
|
||||
return syscall(SYS_ioctl, fd, op, argp);
|
||||
return forward_ioctl(fd, op, argp);
|
||||
}
|
||||
|
||||
int type = (op >> 8 & 0xFF);
|
||||
@@ -3825,7 +3832,7 @@ EXPORT int ioctl(int fd, ioctl_request_t op, ...) {
|
||||
} else {
|
||||
Logger::log("Unhandled evdev ioctl, type %d number %d\n", type, number);
|
||||
guard.unlock();
|
||||
return syscall(SYS_ioctl, fd, op, argp);
|
||||
return forward_ioctl(fd, op, argp);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -22,6 +22,7 @@ class App : Application() {
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
CrashHandler.install(this)
|
||||
com.droiddeck.launcher.session.QuestExperimental.initialize(this)
|
||||
com.droiddeck.launcher.session.SessionPrefs.settleGpuDriverMode(this)
|
||||
com.droiddeck.launcher.update.AppUpdates.init(this)
|
||||
GpuClockPin.clearLeftover(this)
|
||||
|
||||
@@ -994,6 +994,8 @@ class MainActivity : ComponentActivity() {
|
||||
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({
|
||||
@@ -1145,6 +1147,7 @@ class MainActivity : ComponentActivity() {
|
||||
components.refreshComponents(snapshotFirst = true)
|
||||
drivers.refreshDrivers()
|
||||
protons.refreshProtons()
|
||||
protons.checkUpdates()
|
||||
}
|
||||
|
||||
private fun importComponent(uri: Uri) {
|
||||
@@ -1180,6 +1183,9 @@ class MainActivity : ComponentActivity() {
|
||||
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,
|
||||
onGeneralFexPreset = { id -> SessionPrefs.setFexPreset(this, id); fexPreset = id },
|
||||
gpu = drivers.state(),
|
||||
gpuActions = com.droiddeck.launcher.ui.GpuDriversActions(
|
||||
onAuto = { on -> drivers.setMode(on) },
|
||||
@@ -1203,7 +1209,8 @@ class MainActivity : ComponentActivity() {
|
||||
protonActions = com.droiddeck.launcher.ui.ProtonsActions(
|
||||
onInstall = { id -> protons.installProton(id) },
|
||||
onCancel = { id -> ProtonExtras.tools.firstOrNull { it.id == id }?.let { ProtonExtras.unqueue(this, it) }; protons.refreshProtons() },
|
||||
onRemove = { id -> protons.removeProton(id) },
|
||||
onRemove = { id, dir -> protons.removeProton(id, dir) },
|
||||
onRemoveOlder = { id -> protons.removeProton(id, older = true) },
|
||||
),
|
||||
protonOptions = {
|
||||
com.droiddeck.launcher.ui.ProtonOptions(
|
||||
|
||||
@@ -10,14 +10,16 @@ import com.droiddeck.launcher.ui.ProtonRow
|
||||
import com.droiddeck.launcher.session.SessionState
|
||||
|
||||
/**
|
||||
* The optional ARM64 Protons (GE-Proton, proton-cachyos): the rows the page lists and an install or
|
||||
* removal in progress. The launcher screen keeps one and shows it.
|
||||
* 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)
|
||||
var protonStage by mutableStateOf<String?>(null)
|
||||
var protonPercent by mutableIntStateOf(-1)
|
||||
private val checking = java.util.concurrent.atomic.AtomicBoolean(false)
|
||||
|
||||
fun installProton(id: String) {
|
||||
val tool = ProtonExtras.tools.firstOrNull { it.id == id } ?: return
|
||||
@@ -40,14 +42,15 @@ internal class ProtonMenu(private val activity: android.app.Activity, private va
|
||||
}, "install-proton-$id").start()
|
||||
}
|
||||
|
||||
fun removeProton(id: String) {
|
||||
/** 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
|
||||
protonBusyId = id
|
||||
protonStage = activity.getString(R.string.main_removing_named, tool.name)
|
||||
protonStage = activity.getString(R.string.main_removing_named, dir ?: tool.name)
|
||||
protonPercent = -1
|
||||
Thread({
|
||||
ProtonExtras.remove(activity, tool)
|
||||
if (older) ProtonExtras.removeOlder(activity, tool) else ProtonExtras.remove(activity, tool, dir)
|
||||
ui.post {
|
||||
protonBusyId = null
|
||||
protonStage = null
|
||||
@@ -57,6 +60,18 @@ internal class ProtonMenu(private val activity: android.app.Activity, private va
|
||||
}
|
||||
|
||||
fun refreshProtons() {
|
||||
protonRows = ProtonExtras.tools.map { ProtonRow(it.id, it.name, ProtonExtras.installed(activity, it), ProtonExtras.queued(activity, it)) }
|
||||
protonRows = ProtonExtras.tools.map {
|
||||
val all = ProtonExtras.installedAll(activity, it)
|
||||
ProtonRow(it.id, it.name, all.lastOrNull(), ProtonExtras.queued(activity, it), all, ProtonExtras.update(activity, it))
|
||||
}
|
||||
}
|
||||
|
||||
/** 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({
|
||||
val asked = try { ProtonExtras.checkLatest(activity, force) } catch (_: Throwable) { false } finally { checking.set(false) }
|
||||
if (asked) ui.post { refreshProtons() }
|
||||
}, "proton-updates").start()
|
||||
}
|
||||
}
|
||||
@@ -40,6 +40,7 @@ import com.droiddeck.launcher.core.FileUtils
|
||||
import com.droiddeck.launcher.core.TextureFiltering
|
||||
import com.droiddeck.launcher.files.InAppFilePicker
|
||||
import com.droiddeck.launcher.frontend.Library
|
||||
import com.droiddeck.launcher.agent.AgentGuest
|
||||
import com.droiddeck.launcher.gpu.FrameGen
|
||||
import com.droiddeck.launcher.gpu.ScreenEffectLooks
|
||||
import com.droiddeck.launcher.gpu.ScreenEffects
|
||||
@@ -64,6 +65,9 @@ import com.droiddeck.launcher.session.PerfHud
|
||||
import com.droiddeck.launcher.session.PerfMode
|
||||
import com.droiddeck.launcher.session.SteamRepair
|
||||
import com.droiddeck.launcher.session.GameEnvironmentStore
|
||||
import com.droiddeck.launcher.session.GameProfileFollowState
|
||||
import com.droiddeck.launcher.session.GameProfileInventoryCache
|
||||
import com.droiddeck.launcher.session.GameProfileRefreshState
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import com.droiddeck.launcher.session.SessionEvents
|
||||
import com.droiddeck.launcher.session.SessionArtifacts
|
||||
@@ -73,6 +77,9 @@ import com.droiddeck.launcher.session.SessionPaths
|
||||
import com.droiddeck.launcher.wayland.HdrSupport
|
||||
import com.droiddeck.launcher.session.SessionService
|
||||
import com.droiddeck.launcher.session.SessionState
|
||||
import com.droiddeck.launcher.session.ProtonDefault
|
||||
import com.droiddeck.launcher.session.SelectedGameProfile
|
||||
import com.droiddeck.launcher.session.WinComponents
|
||||
import com.droiddeck.launcher.ui.CursorOverlay
|
||||
import androidx.compose.ui.graphics.asImageBitmap
|
||||
import com.droiddeck.launcher.ui.DrawerActions
|
||||
@@ -86,6 +93,7 @@ import com.droiddeck.launcher.wayland.CompositorHost
|
||||
import com.droiddeck.launcher.wayland.WaylandCompositor
|
||||
import java.io.File
|
||||
import com.droiddeck.launcher.session.ComponentsManager
|
||||
import com.droiddeck.launcher.session.LatestRequestCoordinator
|
||||
import com.droiddeck.launcher.ui.SessionDrawerPage
|
||||
import com.droiddeck.launcher.ui.sessionDrawerPages
|
||||
import com.droiddeck.launcher.ui.step
|
||||
@@ -138,8 +146,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
private fun openDeckRing(why: String) {
|
||||
val deck = SessionState.deckPad
|
||||
val opened = if (deck) padBridge?.start() else null
|
||||
// Every pad already connected is a player from the start, before its first press.
|
||||
padBridge?.claimConnected()
|
||||
Log.i(TAG, "deck ring ($why): deck pad $deck" + when (opened) {
|
||||
null -> ", left for first input"
|
||||
true -> ", ring open"
|
||||
@@ -249,6 +255,24 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
private var closeAtOnce = false
|
||||
/** The drawer's Components tab: the Protons as last read (ComponentsManager). */
|
||||
private var drawerComponents by mutableStateOf<ComponentsManager.Snapshot?>(null)
|
||||
private var drawerGameProfileId by mutableStateOf<Long?>(null)
|
||||
private val drawerGameInventory = GameProfileInventoryCache<Library.SteamGame>()
|
||||
private var drawerGameInventoryRevision = 0L
|
||||
private var drawerGameFexPresetSaving by mutableStateOf(false)
|
||||
private val drawerGameProfileFollowState = GameProfileFollowState()
|
||||
private data class DrawerGameProfileRefresh(
|
||||
val followsSteam: Boolean,
|
||||
val requestedAppId: Long?,
|
||||
val inventoryRevision: Long,
|
||||
)
|
||||
private data class DrawerGameProfileResult(
|
||||
val profiles: List<Pair<Long, String>>,
|
||||
val selectedAppId: Long?,
|
||||
val profile: SelectedGameProfile?,
|
||||
val error: Exception? = null,
|
||||
)
|
||||
private var drawerGameProfileRefresh by mutableStateOf(GameProfileRefreshState<DrawerGameProfileResult>())
|
||||
private val drawerGameProfileRefreshes = LatestRequestCoordinator<DrawerGameProfileRefresh>()
|
||||
private var drawerPage by mutableStateOf(SessionDrawerPage.CONTROLLER)
|
||||
private var drawerControllerActive by mutableStateOf(false)
|
||||
private var backActionsInverted by mutableStateOf(false)
|
||||
@@ -262,6 +286,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
private var effects by mutableStateOf(ScreenEffects.OFF)
|
||||
private var textureAnisotropy by mutableStateOf(0)
|
||||
private var textureLodBias by mutableStateOf(TextureFiltering.LOD_BIAS_OFF)
|
||||
private var drawerTextureAnisotropy by mutableStateOf<Int?>(null)
|
||||
private var drawerTextureLodBias by mutableStateOf<String?>(null)
|
||||
private var lossless by mutableStateOf(Lossless.State.NONE)
|
||||
private val pickLossless = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
|
||||
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedFile(r.data)?.let { importLossless(it) }
|
||||
@@ -312,7 +338,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
private val deviceListener = object : InputManager.InputDeviceListener {
|
||||
override fun onInputDeviceAdded(deviceId: Int) {
|
||||
logInputDevice("connected", deviceId)
|
||||
padBridge?.claimConnected()
|
||||
updateOnScreenControls()
|
||||
updatePointerCapture()
|
||||
}
|
||||
@@ -547,7 +572,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
androidApps = androidApps,
|
||||
hudOn = hudOn,
|
||||
upscaler = upscaler, upscaleSharpness = upscaleSharpness,
|
||||
effects = effects, textureAnisotropy = textureAnisotropy, textureLodBias = textureLodBias,
|
||||
effects = effects,
|
||||
textureAnisotropy = if (drawerGameProfileId == null) textureAnisotropy else drawerTextureAnisotropy,
|
||||
textureLodBias = if (drawerGameProfileId == null) textureLodBias else drawerTextureLodBias,
|
||||
frameGen = frameGen,
|
||||
lossless = lossless,
|
||||
oscMode = oscMode, onScreenButtonsVisible = onScreenButtonsVisible, suspendPolicy = suspendPolicy,
|
||||
@@ -572,8 +599,24 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
SessionPrefs.setScreenEffects(this@SessionActivity, e); effects = e
|
||||
e.push(upscaler)
|
||||
},
|
||||
onTextureAnisotropy = { v -> SessionPrefs.setTextureAnisotropy(this@SessionActivity, v); textureAnisotropy = v },
|
||||
onTextureLodBias = { v -> SessionPrefs.setTextureLodBias(this@SessionActivity, v); textureLodBias = v },
|
||||
onTextureAnisotropy = { value ->
|
||||
drawerGameProfileId?.let { appId ->
|
||||
SessionPrefs.setGameTextureAnisotropy(this@SessionActivity, appId.toString(), value)
|
||||
drawerTextureAnisotropy = value
|
||||
} ?: value?.let {
|
||||
SessionPrefs.setTextureAnisotropy(this@SessionActivity, it)
|
||||
textureAnisotropy = it
|
||||
}
|
||||
},
|
||||
onTextureLodBias = { value ->
|
||||
drawerGameProfileId?.let { appId ->
|
||||
SessionPrefs.setGameTextureLodBias(this@SessionActivity, appId.toString(), value)
|
||||
drawerTextureLodBias = value
|
||||
} ?: value?.let {
|
||||
SessionPrefs.setTextureLodBias(this@SessionActivity, it)
|
||||
textureLodBias = it
|
||||
}
|
||||
},
|
||||
onFrameGenPick = { mode ->
|
||||
FrameGen.set(this@SessionActivity, mode)
|
||||
readPrefs()
|
||||
@@ -669,7 +712,22 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
onClose = { drawerOpen = false },
|
||||
components = drawerComponents,
|
||||
onComponentsRefresh = { refreshDrawerComponents() },
|
||||
gameProfiles = drawerGameProfileRefresh.data?.profiles.orEmpty(),
|
||||
selectedGameProfileId = drawerGameProfileId,
|
||||
selectedGameProfile = drawerGameProfileRefresh.data
|
||||
?.takeIf { it.selectedAppId == drawerGameProfileId }?.profile,
|
||||
gameProfilesLoaded = drawerGameProfileRefresh.loaded,
|
||||
gameProfileRefreshFailed = drawerGameProfileRefresh.failed,
|
||||
onSelectedGameProfile = ::selectDrawerGameProfile,
|
||||
onGameProfilesPageOpened = {
|
||||
drawerGameProfileFollowState.resumeFollowingSteam()
|
||||
drawerGameInventoryRevision++
|
||||
},
|
||||
onSelectedGameProfileRefresh = ::refreshDrawerGameProfile,
|
||||
gameFexPresetSaving = drawerGameFexPresetSaving,
|
||||
onGameFexPreset = ::setDrawerGameFexPreset,
|
||||
onComponentSwap = { pid, comp, value -> swapDrawerComponent(pid, comp, value) },
|
||||
onGameComponent = ::setDrawerGameComponent,
|
||||
))
|
||||
if (SessionState.suspended) SessionPausedOverlay(
|
||||
title = pausedTitle(),
|
||||
@@ -766,6 +824,107 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
}, "drawer-components").start()
|
||||
}
|
||||
|
||||
private fun selectDrawerGameProfile(appId: Long?) {
|
||||
drawerGameProfileFollowState.selectManually()
|
||||
drawerGameProfileId = appId
|
||||
drawerGameProfileRefresh = drawerGameProfileRefresh.retrying()
|
||||
readDrawerTextureFiltering(appId)
|
||||
refreshDrawerGameProfile()
|
||||
}
|
||||
|
||||
private fun readDrawerTextureFiltering(appId: Long?) {
|
||||
val choice = appId?.let { SessionPrefs.gameTextureFiltering(this, it.toString()) }
|
||||
drawerTextureAnisotropy = choice?.anisotropy
|
||||
drawerTextureLodBias = choice?.lodBias
|
||||
}
|
||||
|
||||
private fun refreshDrawerGameProfile() {
|
||||
val refresh = DrawerGameProfileRefresh(
|
||||
drawerGameProfileFollowState.followsSteam,
|
||||
drawerGameProfileId,
|
||||
drawerGameInventoryRevision,
|
||||
)
|
||||
if (!drawerGameProfileRefreshes.submit(refresh)) return
|
||||
Thread({
|
||||
var request = drawerGameProfileRefreshes.takeLatest()
|
||||
while (request != null) {
|
||||
val current = request
|
||||
val result = resolveDrawerGameProfileRefresh(current.value)
|
||||
uiHandler.post {
|
||||
if (!drawerGameProfileRefreshes.isLatest(current)) return@post
|
||||
applyDrawerGameProfileRefresh(current.value, result)
|
||||
}
|
||||
request = drawerGameProfileRefreshes.takeLatest()
|
||||
}
|
||||
}, "drawer-game-profile").start()
|
||||
}
|
||||
|
||||
private fun resolveDrawerGameProfileRefresh(
|
||||
refresh: DrawerGameProfileRefresh,
|
||||
): DrawerGameProfileResult {
|
||||
return try {
|
||||
val games = drawerGameInventory.get(refresh.inventoryRevision) { Library.launchableGames(this) }
|
||||
val options = games.mapNotNull { game ->
|
||||
game.profileKey.toLongOrNull()?.let { it to game.name }
|
||||
}.sortedBy { it.second.lowercase() }
|
||||
val installedAppIds = options.mapTo(mutableSetOf()) { it.first }
|
||||
val selectedAppId = if (refresh.followsSteam) {
|
||||
val activeAppId = AgentGuest.activeSteamAppId(this, installedAppIds)
|
||||
val selectedSteamAppId = runCatching { AgentGuest.selectedSteamAppId(this) }
|
||||
AgentGuest.selectedOrActiveInstalledSteamAppId(selectedSteamAppId, activeAppId, installedAppIds)
|
||||
?: refresh.requestedAppId
|
||||
} else {
|
||||
refresh.requestedAppId
|
||||
}
|
||||
val profile = selectedAppId?.let { resolveDrawerGameProfile(it, games) }
|
||||
DrawerGameProfileResult(options, selectedAppId, profile)
|
||||
} catch (error: Exception) {
|
||||
DrawerGameProfileResult(emptyList(), refresh.requestedAppId, null, error)
|
||||
}
|
||||
}
|
||||
|
||||
private fun applyDrawerGameProfileRefresh(
|
||||
refresh: DrawerGameProfileRefresh,
|
||||
result: DrawerGameProfileResult,
|
||||
) {
|
||||
if (result.error != null) {
|
||||
if (!drawerGameProfileRefresh.failed) {
|
||||
Log.w(TAG, "Could not refresh the selected game profile", result.error)
|
||||
}
|
||||
drawerGameProfileRefresh = drawerGameProfileRefresh.failed()
|
||||
return
|
||||
}
|
||||
drawerGameProfileRefresh = drawerGameProfileRefresh.succeeded(result)
|
||||
if (refresh.followsSteam) {
|
||||
if (drawerGameProfileFollowState.followsSteam) {
|
||||
drawerGameProfileId = result.selectedAppId
|
||||
readDrawerTextureFiltering(result.selectedAppId)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun resolveDrawerGameProfile(
|
||||
selectedAppId: Long,
|
||||
games: List<Library.SteamGame>,
|
||||
): SelectedGameProfile? {
|
||||
val game = games.firstOrNull { it.profileKey == selectedAppId.toString() } ?: return null
|
||||
val snapshot = drawerComponents ?: ComponentsManager.snapshot(this)
|
||||
val protons = snapshot.protons.map { it.proton }
|
||||
val gameChoice = ProtonDefault.gameChoice(this, game.profileKey)
|
||||
return SelectedGameProfile.resolve(
|
||||
selectedAppId = selectedAppId,
|
||||
games = games,
|
||||
generalFexPreset = SessionPrefs.fexPreset(this),
|
||||
environment = GameEnvironmentStore.read(this),
|
||||
snapshot = snapshot,
|
||||
generalProtonId = ProtonDefault.selectedId(this, protons),
|
||||
gameProtonChoice = gameChoice,
|
||||
gameProtonId = ProtonDefault.gameSelectedId(this, game.profileKey, protons),
|
||||
gameComponents = ComponentsManager.gameComponents(this, game.profileKey),
|
||||
gameWindowsComponents = WinComponents.picks(this, game.profileKey),
|
||||
)
|
||||
}
|
||||
|
||||
private fun swapDrawerComponent(protonId: String, comp: String, value: String) {
|
||||
Thread({
|
||||
val message = runCatching {
|
||||
@@ -787,6 +946,43 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
}, "drawer-components-swap").start()
|
||||
}
|
||||
|
||||
private fun setDrawerGameComponent(appId: Long, comp: String, file: String?) {
|
||||
val name = drawerGameProfileRefresh.data?.profiles?.firstOrNull { it.first == appId }?.second ?: appId.toString()
|
||||
Thread({
|
||||
val message = runCatching {
|
||||
ComponentsManager.setGameComponent(this, appId.toString(), comp, file)
|
||||
getString(R.string.comp_game_saved_next, name)
|
||||
}.getOrElse { e ->
|
||||
getString(R.string.session_profile_save_failed, e.message ?: e.javaClass.simpleName)
|
||||
}
|
||||
uiHandler.post {
|
||||
android.widget.Toast.makeText(this, message, android.widget.Toast.LENGTH_LONG).show()
|
||||
refreshDrawerComponents()
|
||||
refreshDrawerGameProfile()
|
||||
}
|
||||
}, "drawer-game-component").start()
|
||||
}
|
||||
|
||||
private fun setDrawerGameFexPreset(appId: Long, preset: String?) {
|
||||
if (drawerGameFexPresetSaving) return
|
||||
drawerGameFexPresetSaving = true
|
||||
val name = drawerGameProfileRefresh.data?.profiles?.firstOrNull { it.first == appId }?.second ?: appId.toString()
|
||||
Thread({
|
||||
val message = try {
|
||||
GameEnvironmentStore.setGameFexPreset(this, appId.toString(), preset)
|
||||
getString(R.string.comp_game_saved_next, name)
|
||||
} catch (error: Exception) {
|
||||
Log.w(TAG, "Could not save the game FEX preset for $appId", error)
|
||||
getString(R.string.session_profile_save_failed, error.message ?: error.javaClass.simpleName)
|
||||
}
|
||||
uiHandler.post {
|
||||
drawerGameFexPresetSaving = false
|
||||
Toast.makeText(this, message, Toast.LENGTH_LONG).show()
|
||||
refreshDrawerGameProfile()
|
||||
}
|
||||
}, "drawer-game-fex-preset").start()
|
||||
}
|
||||
|
||||
/** The session this screen is bringing up: the live one when re-attached, else the intent's. */
|
||||
private fun loadingMode(): String =
|
||||
if (SessionState.running) SessionState.mode
|
||||
|
||||
@@ -85,6 +85,63 @@ object AgentGuest {
|
||||
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") }
|
||||
val focusableAppIds = snapshot.optJSONArray("focusableApps")?.let { apps ->
|
||||
buildList {
|
||||
for (index in 0 until apps.length()) {
|
||||
apps.optLong(index).takeIf { it > 0 }?.let(::add)
|
||||
}
|
||||
}
|
||||
}.orEmpty()
|
||||
val baselayerAppIds = snapshot.optJSONArray("baselayerAppIds")?.let { apps ->
|
||||
buildList {
|
||||
for (index in 0 until apps.length()) {
|
||||
apps.optLong(index).takeIf { it > 0 }?.let(::add)
|
||||
}
|
||||
}
|
||||
}.orEmpty()
|
||||
return activeInstalledSteamAppId(focusedAppId, focusableAppIds, installedAppIds, baselayerAppIds)
|
||||
}
|
||||
|
||||
internal fun focusedInstalledSteamAppId(focusedAppId: Long?, installedAppIds: Set<Long>): Long? =
|
||||
focusedAppId?.takeIf { it in installedAppIds }
|
||||
|
||||
internal fun activeInstalledSteamAppId(
|
||||
focusedAppId: Long?,
|
||||
focusableAppIds: List<Long>,
|
||||
installedAppIds: Set<Long>,
|
||||
baselayerAppIds: List<Long> = emptyList(),
|
||||
): Long? = focusedInstalledSteamAppId(focusedAppId, installedAppIds)
|
||||
?: focusableAppIds.filter { it in installedAppIds }.distinct().singleOrNull()
|
||||
?: baselayerAppIds.filter { it in installedAppIds }.distinct().singleOrNull()
|
||||
|
||||
internal fun preferredInstalledSteamAppId(
|
||||
selectedAppId: Long?,
|
||||
activeAppId: Long?,
|
||||
installedAppIds: Set<Long>,
|
||||
): Long? = selectedAppId?.takeIf { it in installedAppIds }
|
||||
?: activeAppId?.takeIf { it in installedAppIds }
|
||||
|
||||
internal fun selectedOrActiveInstalledSteamAppId(
|
||||
selectedAppId: Result<Long?>,
|
||||
activeAppId: Long?,
|
||||
installedAppIds: Set<Long>,
|
||||
): Long? {
|
||||
preferredInstalledSteamAppId(selectedAppId.getOrNull(), activeAppId, installedAppIds)?.let { return it }
|
||||
selectedAppId.exceptionOrNull()?.let { throw it }
|
||||
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)
|
||||
|
||||
@@ -30,4 +30,11 @@ object FexPreset {
|
||||
|
||||
/** Game-launch variables in KEY=VALUE form. */
|
||||
fun env(id: String): List<String> = byId(id).env
|
||||
|
||||
val environmentKeys: Set<String> by lazy {
|
||||
all.flatMap { it.env }.mapTo(linkedSetOf()) { it.substringBefore('=') }
|
||||
}
|
||||
|
||||
fun environment(id: String): Map<String, String> =
|
||||
env(id).associate { it.substringBefore('=') to it.substringAfter('=') }
|
||||
}
|
||||
@@ -46,4 +46,37 @@ object GameEnvironment {
|
||||
|
||||
fun effective(config: Config, preset: String, scope: String, forceSsbs: Boolean = false): Map<String, String?> =
|
||||
defaults(preset, forceSsbs) + config.shared + if (scope.isEmpty()) emptyMap() else config.games[scope].orEmpty()
|
||||
|
||||
fun hasOverride(config: Config, scope: String, name: String): Boolean =
|
||||
scope.isNotEmpty() && config.entries(scope).containsKey(name)
|
||||
|
||||
fun withScopeValue(config: Config, scope: String, name: String, value: String?): Config {
|
||||
require(scope.isEmpty() || validScope(scope))
|
||||
val entries = config.entries(scope).toMutableMap()
|
||||
if (value == null) entries.remove(name) else entries[name] = value
|
||||
return config.withEntries(scope, entries)
|
||||
}
|
||||
|
||||
fun gameFexPreset(config: Config, scope: String): String? {
|
||||
require(scope.isNotEmpty() && validScope(scope))
|
||||
val entries = config.games[scope].orEmpty()
|
||||
if (FexPreset.environmentKeys.none(entries::containsKey)) return null
|
||||
return FexPreset.all.firstOrNull { preset ->
|
||||
val expected = FexPreset.environment(preset.id)
|
||||
FexPreset.environmentKeys.all { key -> entries.containsKey(key) && entries[key] == expected[key] }
|
||||
}?.id ?: CUSTOM_FEX_PRESET
|
||||
}
|
||||
|
||||
fun withGameFexPreset(config: Config, scope: String, preset: String?): Config {
|
||||
require(scope.isNotEmpty() && validScope(scope))
|
||||
require(preset == null || FexPreset.all.any { it.id == preset })
|
||||
val entries = config.entries(scope).filterKeys { it !in FexPreset.environmentKeys }.toMutableMap()
|
||||
if (preset != null) {
|
||||
val values = FexPreset.environment(preset)
|
||||
FexPreset.environmentKeys.forEach { key -> entries[key] = values[key] }
|
||||
}
|
||||
return config.withEntries(scope, entries)
|
||||
}
|
||||
|
||||
const val CUSTOM_FEX_PRESET = "__custom__"
|
||||
}
|
||||
@@ -31,6 +31,8 @@ object Library {
|
||||
) {
|
||||
/** 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"
|
||||
|
||||
@@ -50,7 +50,8 @@ public final class TurnipDriver {
|
||||
/** Adreno 8xx (8 Elite, e.g. a Fold 8's A830). */
|
||||
private static final String DRIVER_A8XX = "turnip-sdk36";
|
||||
/** The two the apk carries; never removable, unpacked on demand. */
|
||||
public static final List<String> BUNDLED = Collections.unmodifiableList(Arrays.asList(DRIVER_A7XX, DRIVER_A8XX));
|
||||
public static final List<String> BUNDLED = Collections.unmodifiableList(Arrays.asList(
|
||||
DRIVER_A7XX, DRIVER_A8XX, com.droiddeck.launcher.session.QuestExperimental.DRIVER));
|
||||
/** Overrides the pick, for a device we cannot reach: a7xx, a8xx or system. */
|
||||
private static final String OVERRIDE_FILE = "Download/droiddeck-driver";
|
||||
/** Bundled drivers the user deleted: hidden from the list, their unpacked copy removed. */
|
||||
|
||||
@@ -29,9 +29,7 @@ import java.util.concurrent.atomic.AtomicIntegerArray;
|
||||
* Guide-then-A chord the client itself answers.
|
||||
*
|
||||
* <p>Each further controller is another player: slots 1 to 3, an Xbox 360 pad each, which in a
|
||||
* Steam session only the client reads (libfakeinput) and hands games through Steam Input. Slot 0
|
||||
* is the device's own controls wherever it has them: a Bluetooth pad pressed first used to take
|
||||
* it, and played as the handheld while its built-in pad became player 2.
|
||||
* Steam session only the client reads (libfakeinput) and hands games through Steam Input.
|
||||
*/
|
||||
public final class PadBridge {
|
||||
private static final String TAG = "PadBridge";
|
||||
@@ -103,27 +101,6 @@ public final class PadBridge {
|
||||
|
||||
/** No physical controller is driving the pad: nothing yet, or the on-screen controls were last. */
|
||||
public static final int NO_CONTROLLER = -1;
|
||||
|
||||
/**
|
||||
* Whether this controller is the device's own controls, which play in slot 0: the one Android
|
||||
* calls built-in, else - a handheld whose pad Android calls external, as AYN's present theirs -
|
||||
* the controller connected longest, there since boot where it is the device's own. A phone
|
||||
* with only connected pads has its first one there.
|
||||
*/
|
||||
static boolean isBuiltIn(InputDevice device) {
|
||||
int own = NO_CONTROLLER;
|
||||
boolean ownInternal = false;
|
||||
for (int id : InputDevice.getDeviceIds()) {
|
||||
InputDevice d = InputDevice.getDevice(id);
|
||||
if (!isFromController(d)) continue;
|
||||
boolean internal = !d.isExternal();
|
||||
if (own == NO_CONTROLLER || (internal && !ownInternal) || (internal == ownInternal && id < own)) {
|
||||
own = id;
|
||||
ownInternal = internal;
|
||||
}
|
||||
}
|
||||
return device.getId() == own;
|
||||
}
|
||||
/**
|
||||
* The Android input device id of the physical controller that last drove any slot, or
|
||||
* {@link #NO_CONTROLLER}: where rumble goes when it names no slot of ours (RumbleComponent).
|
||||
@@ -434,19 +411,6 @@ public final class PadBridge {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gives every connected controller its slot now, so the client lists each one as it is
|
||||
* connected instead of on its first press: a further player's pad is plugged in, at rest.
|
||||
*/
|
||||
public synchronized void claimConnected() {
|
||||
for (int id : InputDevice.getDeviceIds()) {
|
||||
InputDevice device = InputDevice.getDevice(id);
|
||||
if (!isFromController(device)) continue;
|
||||
int slot = slotFor(device);
|
||||
if (slot > 0 && playerWriters[slot] == null) publish(slot);
|
||||
}
|
||||
}
|
||||
|
||||
/** A controller went away: its player's buttons are let go, and a further player's pad is unplugged. */
|
||||
public synchronized void onDeviceRemoved(int deviceId) {
|
||||
for (int slot = 0; slot < SLOTS; slot++) {
|
||||
@@ -507,47 +471,23 @@ public final class PadBridge {
|
||||
publish();
|
||||
}
|
||||
|
||||
/**
|
||||
* The slot this controller plays in: the one it has, else slot 0 for the device's own controls
|
||||
* and a further player's slot for a connected pad (slot 0 too while the device has no controls
|
||||
* of its own), else player 1's.
|
||||
*/
|
||||
/** The slot this controller plays in: the one it has, else the first free one, else player 1's. */
|
||||
private int slotFor(InputDevice device) {
|
||||
int id = device.getId();
|
||||
for (int slot = 0; slot < SLOTS; slot++) {
|
||||
if (owners[0] == id) return 0;
|
||||
for (int slot = 1; slot < SLOTS; slot++) {
|
||||
if (owners[slot] == id) return slot;
|
||||
}
|
||||
for (int slot = 0; slot < SLOTS; slot++) {
|
||||
if (owners[slot] != NO_CONTROLLER && InputDevice.getDevice(owners[slot]) == null) free(slot);
|
||||
}
|
||||
if (isBuiltIn(device)) {
|
||||
// A connected pad playing as the device's own controls moves to a player's slot of its own.
|
||||
int was = owners[0];
|
||||
if (was != NO_CONTROLLER) {
|
||||
free(0);
|
||||
InputDevice other = InputDevice.getDevice(was);
|
||||
if (other != null && !isBuiltIn(other)) {
|
||||
int to = claim(other, 1);
|
||||
if (to > 0) publish(to);
|
||||
}
|
||||
}
|
||||
owners[0] = id;
|
||||
Log.i(TAG, "\"" + device.getName() + "\" (id " + id + ") is player 1, the device's own controls");
|
||||
return 0;
|
||||
}
|
||||
int slot = claim(device, 1);
|
||||
return slot >= 0 ? slot : 0;
|
||||
}
|
||||
|
||||
/** Takes the first free slot from {@code from} for this controller, or -1 if none is free. */
|
||||
private int claim(InputDevice device, int from) {
|
||||
for (int slot = from; slot < SLOTS; slot++) {
|
||||
for (int slot = 0; slot < SLOTS; slot++) {
|
||||
if (owners[slot] != NO_CONTROLLER) continue;
|
||||
owners[slot] = device.getId();
|
||||
Log.i(TAG, "\"" + device.getName() + "\" (id " + device.getId() + ") is player " + (slot + 1));
|
||||
owners[slot] = id;
|
||||
Log.i(TAG, "\"" + device.getName() + "\" (id " + id + ") is player " + (slot + 1));
|
||||
return slot;
|
||||
}
|
||||
return -1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
private PadState stateFor(int slot) {
|
||||
|
||||
@@ -33,7 +33,7 @@ import java.util.concurrent.atomic.AtomicInteger
|
||||
*/
|
||||
object BwrapSpawner {
|
||||
private const val TAG = "BwrapSpawner"
|
||||
const val SOCKET = "com.droiddeck.launcher.bwrap"
|
||||
fun socket(context: Context): String = "${context.packageName}.bwrap"
|
||||
private val seq = AtomicInteger()
|
||||
@Volatile private var server: LocalServerSocket? = null
|
||||
|
||||
@@ -42,10 +42,11 @@ object BwrapSpawner {
|
||||
fun start(context: Context) {
|
||||
if (server != null) return
|
||||
val app = context.applicationContext
|
||||
val name = socket(app)
|
||||
val socket = try {
|
||||
LocalServerSocket(SOCKET)
|
||||
LocalServerSocket(name)
|
||||
} catch (e: IOException) {
|
||||
Log.e(TAG, "cannot listen on $SOCKET", e)
|
||||
Log.e(TAG, "cannot listen on $name", e)
|
||||
return
|
||||
}
|
||||
server = socket
|
||||
|
||||
@@ -51,6 +51,7 @@ object GuestCommand {
|
||||
"/usr/bin/env", "-i", "HOME=/root", "USER=root", "LANG=C.UTF-8",
|
||||
"PATH=/usr/local/bin:/usr/bin:/bin", "XDG_RUNTIME_DIR=${LinuxRuntime.GUEST_RUNTIME_DIR}",
|
||||
"XDG_DATA_HOME=/root/.local/share", "FLATPAK_BWRAP=${FlatpakManager.BWRAP}",
|
||||
"DROIDDECK_BWRAP_SOCKET=${BwrapSpawner.socket(context)}",
|
||||
"XDG_DATA_DIRS=/root/.local/share/flatpak/exports/share:/usr/local/share:/usr/share",
|
||||
)
|
||||
cmd += argv
|
||||
|
||||
@@ -6,6 +6,7 @@ import android.content.Context
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.core.Downloader
|
||||
import com.droiddeck.launcher.core.FileUtils
|
||||
import com.droiddeck.launcher.core.GameEnvironment
|
||||
import com.droiddeck.launcher.gpu.GpuInfo
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import com.github.luben.zstd.ZstdInputStream
|
||||
@@ -79,7 +80,14 @@ object ComponentsManager {
|
||||
private const val PLUGIN_DATA = "root/homebrew/data/decky-components-manager"
|
||||
|
||||
data class Proton(val id: String, val name: String, val dir: File, val guestPath: String, val version: String, val valve: Boolean)
|
||||
data class Component(val detected: String, val detail: String, val inUse: String, val activeFile: String?, val queued: String?)
|
||||
data class Component(
|
||||
val detected: String,
|
||||
val detail: String,
|
||||
val inUse: String,
|
||||
val selected: String,
|
||||
val activeFile: String?,
|
||||
val queued: String?,
|
||||
)
|
||||
data class Original(val comp: String, val protonVersion: String, val label: String, val size: Long)
|
||||
data class Package(val file: String, val comp: String, val version: String, val description: String, val size: Long)
|
||||
data class CatalogItem(val file: String, val comp: String, val release: String, val url: String, val size: Long, val digest: String)
|
||||
@@ -129,23 +137,121 @@ object ComponentsManager {
|
||||
|
||||
// ------------------------------------------------------------------ state
|
||||
|
||||
private fun loadState(context: Context): JSONObject =
|
||||
runCatching { JSONObject(stateFile(context).readText()) }.getOrElse { JSONObject() }.apply {
|
||||
private fun pendingStateFile(context: Context) = File(dataDir(context), "state.pending.json")
|
||||
|
||||
private fun loadState(context: Context): JSONObject {
|
||||
recoverState(context)
|
||||
return runCatching { JSONObject(stateFile(context).readText()) }.getOrElse { JSONObject() }.apply {
|
||||
if (!has("active")) put("active", JSONObject())
|
||||
if (!has("queued")) put("queued", JSONObject())
|
||||
if (!has("profiles")) put("profiles", JSONObject())
|
||||
}
|
||||
}
|
||||
|
||||
private fun writeStateFile(file: File, text: String) {
|
||||
val tmp = File(file.parentFile, file.name + ".tmp")
|
||||
try {
|
||||
writeSynced(tmp, text)
|
||||
check(tmp.renameTo(file)) { "Could not save component selections: ${file.name}" }
|
||||
} finally {
|
||||
tmp.delete()
|
||||
}
|
||||
}
|
||||
|
||||
private fun writeSynced(file: File, text: String) {
|
||||
FileOutputStream(file).use {
|
||||
it.write(text.toByteArray(Charsets.UTF_8))
|
||||
it.fd.sync()
|
||||
}
|
||||
}
|
||||
|
||||
private fun recoverState(context: Context) {
|
||||
val pending = pendingStateFile(context)
|
||||
if (!pending.exists()) return
|
||||
val transaction = JSONObject(pending.readText())
|
||||
val state = transaction.getJSONObject("state")
|
||||
val expected = transaction.getString("launchSha256")
|
||||
val published = File(launchDir(context), "desired.tsv")
|
||||
val staged = File(launchDir(context), "desired.tsv.tmp")
|
||||
// The launch-table rename is the commit point. Never read stale app selections after it.
|
||||
if (!staged.exists() && published.isFile && Hashes.sha256(published) == expected) {
|
||||
writeStateFile(stateFile(context), state.toString(2))
|
||||
Log.i(TAG, "recovered published component selections")
|
||||
} else {
|
||||
Log.i(TAG, "discarded unpublished component selections")
|
||||
}
|
||||
check(pending.delete()) { "Could not finish component selection recovery" }
|
||||
if (staged.exists()) check(staged.delete()) { "Could not remove unpublished component selections" }
|
||||
}
|
||||
|
||||
private fun saveState(context: Context, state: JSONObject) {
|
||||
val f = stateFile(context)
|
||||
val tmp = File(f.parentFile, f.name + ".tmp")
|
||||
tmp.writeText(state.toString(2))
|
||||
tmp.renameTo(f)
|
||||
// Every change of choice reaches the launch wrappers at once.
|
||||
runCatching { syncLaunchState(context, state) }.onFailure { Log.w(TAG, "launch state", it) }
|
||||
val prepared = prepareLaunchState(context, state)
|
||||
val dir = launchDir(context)
|
||||
val tmp = File(dir, "desired.tsv.tmp")
|
||||
try {
|
||||
writeSynced(tmp, prepared.text)
|
||||
writeStateFile(pendingStateFile(context), JSONObject()
|
||||
.put("state", state)
|
||||
.put("launchSha256", Hashes.sha256(tmp))
|
||||
.toString())
|
||||
check(tmp.renameTo(File(dir, "desired.tsv"))) { "Could not publish component selections" }
|
||||
writeStateFile(stateFile(context), state.toString(2))
|
||||
check(pendingStateFile(context).delete()) { "Could not finish saving component selections" }
|
||||
} finally {
|
||||
if (!pendingStateFile(context).exists()) tmp.delete()
|
||||
}
|
||||
File(dir, "store").listFiles()?.filter { it.isDirectory && it.name !in prepared.keep }
|
||||
?.forEach { it.deleteRecursively() }
|
||||
}
|
||||
|
||||
private fun JSONObject.sub(key: String): JSONObject = optJSONObject(key) ?: JSONObject().also { put(key, it) }
|
||||
|
||||
// Keep launch-time restore rows after the last per-game selection is removed.
|
||||
private fun rememberProfiledComponent(state: JSONObject, comp: String) {
|
||||
val profiled = state.optJSONArray("profiledComponents")?.let { values ->
|
||||
(0 until values.length()).mapNotNull { values.optString(it).takeIf(COMPONENTS::contains) }
|
||||
}.orEmpty().toMutableSet()
|
||||
if (profiled.add(comp)) state.put("profiledComponents", JSONArray(profiled.sorted()))
|
||||
}
|
||||
|
||||
fun gameComponents(context: Context, scope: String): Map<String, String> = synchronized(lock) {
|
||||
val profile = loadState(context).sub("profiles").optJSONObject(scope) ?: return emptyMap()
|
||||
COMPONENTS.mapNotNull { comp -> profile.optString(comp).takeIf(String::isNotEmpty)?.let { comp to it } }.toMap()
|
||||
}
|
||||
|
||||
fun setGameComponent(context: Context, scope: String, comp: String, file: String?) = synchronized(lock) {
|
||||
require(scope.matches(Regex("[1-9][0-9]{0,9}")) && scope.toLong() <= 4294967295L)
|
||||
require(comp in COMPONENTS)
|
||||
val state = loadState(context)
|
||||
val profiles = state.sub("profiles")
|
||||
val profile = profiles.optJSONObject(scope) ?: JSONObject().also { profiles.put(scope, it) }
|
||||
if (file == null) {
|
||||
if (profile.optString(comp).isNotEmpty()) rememberProfiledComponent(state, comp)
|
||||
profile.remove(comp)
|
||||
if (profile.length() == 0) profiles.remove(scope)
|
||||
} else {
|
||||
val name = safeName(file)
|
||||
val wcp = File(packagesDir(context), name)
|
||||
require(packageInfo(context, wcp).comp == comp)
|
||||
for (proton in protons(context)) ensureOriginal(context, proton, comp, state)
|
||||
rememberProfiledComponent(state, comp)
|
||||
profile.put(comp, name)
|
||||
}
|
||||
saveState(context, state)
|
||||
}
|
||||
|
||||
fun clearGameComponents(context: Context, scope: String) = synchronized(lock) {
|
||||
require(GameEnvironment.validScope(scope))
|
||||
val state = loadState(context)
|
||||
val profiles = state.sub("profiles")
|
||||
profiles.optJSONObject(scope)?.let { profile ->
|
||||
COMPONENTS.filter { profile.optString(it).isNotEmpty() }
|
||||
.forEach { rememberProfiledComponent(state, it) }
|
||||
}
|
||||
profiles.remove(scope)
|
||||
saveState(context, state)
|
||||
}
|
||||
|
||||
/** Takes over the Decky plugin's packages, originals and swap records, once. */
|
||||
private fun migratePlugin(context: Context) {
|
||||
val marker = File(dataDir(context), ".plugin-imported")
|
||||
@@ -220,24 +326,33 @@ object ComponentsManager {
|
||||
* Is anything running on this Proton right now - a game, or the client's own start-up runs,
|
||||
* whose Wine processes can outlive them? Swaps wait while it is. Read from the command lines.
|
||||
*/
|
||||
fun inUse(context: Context, proton: Proton): Boolean = anyProcess(context, proton) { needle, text -> text.contains(needle + "proton ") || text.contains(needle + "files/bin") }
|
||||
fun inUse(context: Context, proton: Proton): Boolean =
|
||||
anyProcess(context, proton) { paths, text -> processUsesProton(paths, text, gameOnly = false) }
|
||||
|
||||
/**
|
||||
* Is a game running on this Proton? Only a launch runs proton with the verb waitforexitandrun
|
||||
* (Proton's own script stays up until the game exits); the client's start-up runs do not.
|
||||
*/
|
||||
fun gameRunning(context: Context, proton: Proton): Boolean = anyProcess(context, proton) { needle, text -> text.contains(needle + "proton waitforexitandrun") }
|
||||
fun gameRunning(context: Context, proton: Proton): Boolean =
|
||||
anyProcess(context, proton) { paths, text -> processUsesProton(paths, text, gameOnly = true) }
|
||||
|
||||
private fun anyProcess(context: Context, proton: Proton, match: (String, String) -> Boolean): Boolean {
|
||||
val needles = (listOf(proton.guestPath) + EsyncPacks.distPathsFor(root(context), proton.guestPath))
|
||||
.map { it.trimEnd('/') + "/" }
|
||||
internal fun processUsesProton(paths: List<String>, text: String, gameOnly: Boolean): Boolean =
|
||||
paths.any { path ->
|
||||
val needle = path.trimEnd('/') + "/"
|
||||
if (gameOnly) text.contains(needle + "proton waitforexitandrun")
|
||||
else text.contains(needle + "proton ") || text.contains(needle + "files/bin")
|
||||
}
|
||||
|
||||
private fun anyProcess(context: Context, proton: Proton, match: (List<String>, String) -> Boolean): Boolean {
|
||||
val guestPaths = listOf(proton.guestPath) + EsyncPacks.distPathsFor(root(context), proton.guestPath)
|
||||
val paths = (guestPaths + guestPaths.map { host(context, it).absolutePath } + proton.dir.absolutePath).distinct()
|
||||
val procs = File("/proc").listFiles() ?: return false
|
||||
for (p in procs) {
|
||||
if (!p.name.all(Char::isDigit)) continue
|
||||
val cmd = runCatching { File(p, "cmdline").readBytes() }.getOrNull() ?: continue
|
||||
if (cmd.isEmpty()) continue
|
||||
val text = String(cmd).replace('\u0000', ' ')
|
||||
if (needles.any { match(it, text) }) return true
|
||||
if (match(paths, text)) return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -261,7 +376,7 @@ object ComponentsManager {
|
||||
private fun compFiles(dir: File, comp: String): List<String> {
|
||||
if (comp == "fex") return FEX_FILES.filter { File(dir, it).isFile }
|
||||
val base = File(dir, COMP_DIR.getValue(comp))
|
||||
return base.walkTopDown().filter { it.isFile }.map { it.relativeTo(dir).path }.sorted().toList()
|
||||
return base.walkTopDown().filter { it.isFile }.map { it.relativeTo(dir).invariantSeparatorsPath }.sorted().toList()
|
||||
}
|
||||
|
||||
private fun owned(comp: String, rel: String) = comp == "fex" || PE_ARCHES.any { "/$it/" in rel }
|
||||
@@ -352,7 +467,7 @@ object ComponentsManager {
|
||||
tar.closeArchiveEntry()
|
||||
}
|
||||
}
|
||||
tmp.renameTo(dest)
|
||||
check(tmp.renameTo(dest)) { "Could not save original bundle ${dest.name}" }
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ originals
|
||||
@@ -380,8 +495,18 @@ object ComponentsManager {
|
||||
if (dest.isFile) return
|
||||
val active = state.sub("active").optJSONObject(p.id)?.optJSONObject(comp)
|
||||
if (active != null && active.optString("protonVersion") == p.version) return
|
||||
val published = File(launchDir(context), "desired.tsv")
|
||||
if (published.isFile) {
|
||||
val mayHaveOverride = published.useLines { rows ->
|
||||
rows.any { row ->
|
||||
val fields = row.split('\t')
|
||||
fields.size == 7 && fields[0] != "*" && fields[1] == p.dir.name &&
|
||||
fields[2] == p.version && fields[3] == comp
|
||||
}
|
||||
}
|
||||
check(!mayHaveOverride) { context.getString(R.string.cmgr_original_missing) }
|
||||
}
|
||||
val rels = compFiles(p.dir, comp)
|
||||
if (rels.isEmpty()) return
|
||||
val current = if (comp == "fex") fexVersion(p.dir) else readVersionFile(File(p.dir, "${COMP_DIR.getValue(comp)}/version"))
|
||||
val profile = JSONObject()
|
||||
.put("type", TYPE_OF.getValue(comp))
|
||||
@@ -400,7 +525,7 @@ object ComponentsManager {
|
||||
for (p in protons(context)) for (comp in COMPONENTS) {
|
||||
runCatching { ensureOriginal(context, p, comp, state) }.onFailure { Log.w(TAG, "original $comp of ${p.name}", it) }
|
||||
}
|
||||
runCatching { syncLaunchState(context, state) }.onFailure { Log.w(TAG, "launch state", it) }
|
||||
runCatching { saveState(context, state) }.onFailure { Log.w(TAG, "launch state", it) }
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ view
|
||||
@@ -431,9 +556,14 @@ object ComponentsManager {
|
||||
else context.getString(R.string.cmgr_changed_outside)
|
||||
}
|
||||
}
|
||||
val selectedLabel = when {
|
||||
active == null || active.optString("protonVersion") != p.version ->
|
||||
context.getString(R.string.comp_tag_original)
|
||||
else -> originalLabel(context, active) ?: active.optString("label", active.optString("file"))
|
||||
}
|
||||
val q = state.sub("queued").optJSONObject(p.id)?.optJSONObject(comp)
|
||||
Component(
|
||||
detected.ifEmpty { context.getString(R.string.cmgr_not_present) }, detail, inUseLabel,
|
||||
detected.ifEmpty { context.getString(R.string.cmgr_not_present) }, detail, inUseLabel, selectedLabel,
|
||||
active?.optString("file")?.takeIf { active.optString("protonVersion") == p.version },
|
||||
q?.let { originalLabel(context, it) ?: it.optString("label") },
|
||||
)
|
||||
@@ -455,64 +585,111 @@ object ComponentsManager {
|
||||
|
||||
// ------------------------------------------------------------------ launch-time enforcement
|
||||
|
||||
private data class PreparedLaunchState(val text: String, val keep: Set<String>)
|
||||
|
||||
/**
|
||||
* Writes what each Proton should be using for the launch wrappers: desired.tsv, one line per
|
||||
* file (tool dir, Proton build, component, file, sha256, source copy), and an unpacked copy of
|
||||
* every package or older-build original in use to copy from. Rebuilt whole after every change, so
|
||||
* a restored or deleted choice simply stops being enforced. The Proton's own current-build
|
||||
* originals are not listed: the wrappers also give Steam's probe runs their own prefix, which is
|
||||
* what overwrote files in the first place.
|
||||
* Stages what each Proton should use for the launch wrappers. General rows use scope `*`;
|
||||
* per-game rows use the game's compatdata id and replace General for that component. Deletion
|
||||
* rows remove managed DLLs absent from the chosen package, so switching games cannot leave files
|
||||
* from the previous game's component set behind.
|
||||
*/
|
||||
private fun syncLaunchState(context: Context, state: JSONObject) {
|
||||
private fun prepareLaunchState(context: Context, state: JSONObject): PreparedLaunchState {
|
||||
val dir = launchDir(context)
|
||||
val store = File(dir, "store").apply { mkdirs() }
|
||||
val all = protons(context)
|
||||
val lines = StringBuilder()
|
||||
val keep = HashSet<String>()
|
||||
val active = state.sub("active")
|
||||
for (pid in active.keys()) {
|
||||
val p = all.firstOrNull { it.id == pid } ?: continue
|
||||
val comps = active.optJSONObject(pid) ?: continue
|
||||
for (comp in comps.keys()) {
|
||||
val a = comps.optJSONObject(comp) ?: continue
|
||||
if (a.optString("protonVersion") != p.version) continue
|
||||
val file = a.optString("file")
|
||||
val (key, wcp) = if (file.startsWith("original ")) {
|
||||
val v = file.removePrefix("original ")
|
||||
"original-$pid-${safeName(v)}-$comp" to File(originalsDir(context), "$pid/${safeName(v)}/$comp.wcp")
|
||||
} else safeName(file.removeSuffix(".wcp")) to File(packagesDir(context), file)
|
||||
if (!wcp.isFile) continue
|
||||
val unpacked = File(store, key)
|
||||
if (!File(unpacked, ".complete").isFile) {
|
||||
unpacked.deleteRecursively()
|
||||
readWcp(wcp) { tar ->
|
||||
while (true) {
|
||||
val e = tar.nextTarEntry ?: break
|
||||
val rel = normalize(e.name)
|
||||
if (e.isDirectory || !rel.startsWith("files/") || rel.split('/').any { it == ".." }) continue
|
||||
val out = File(unpacked, rel)
|
||||
out.parentFile?.mkdirs()
|
||||
FileOutputStream(out).use { tar.copyTo(it) }
|
||||
}
|
||||
|
||||
fun unpack(key: String, wcp: File, comp: String): File {
|
||||
check(wcp.isFile) { context.getString(R.string.cmgr_not_stored) }
|
||||
val unpacked = File(store, key)
|
||||
if (!File(unpacked, ".complete").isFile) {
|
||||
check(packageInfo(context, wcp).comp == comp) { "Wrong component in ${wcp.name}" }
|
||||
unpacked.deleteRecursively()
|
||||
check(unpacked.mkdirs()) { "Could not stage component bundle ${wcp.name}" }
|
||||
readWcp(wcp) { tar ->
|
||||
while (true) {
|
||||
val e = tar.nextTarEntry ?: break
|
||||
val rel = normalize(e.name)
|
||||
if (e.isDirectory || !rel.startsWith("files/") || rel.split('/').any { it == ".." }) continue
|
||||
val out = File(unpacked, rel)
|
||||
out.parentFile?.mkdirs()
|
||||
FileOutputStream(out).use { tar.copyTo(it) }
|
||||
}
|
||||
File(unpacked, ".complete").writeText("1\n")
|
||||
}
|
||||
keep += key
|
||||
val files = a.optJSONObject("files") ?: continue
|
||||
for (rel in files.keys()) {
|
||||
val src = File(unpacked, rel)
|
||||
if (!src.isFile) continue
|
||||
val guestSrc = "/" + src.absolutePath.removePrefix(root(context).absolutePath.trimEnd('/')).trimStart('/')
|
||||
lines.append(p.dir.name).append('\t').append(p.version).append('\t').append(comp).append('\t')
|
||||
.append(rel).append('\t').append(files.optString(rel)).append('\t').append(guestSrc).append('\n')
|
||||
}
|
||||
File(unpacked, ".complete").writeText("1\n")
|
||||
}
|
||||
keep += key
|
||||
return unpacked
|
||||
}
|
||||
|
||||
fun managed(comp: String): Set<String> = if (comp == "fex") FEX_FILES.toSet() else buildSet {
|
||||
for (arch in PE_ARCHES) for (dll in COMP_DLLS.getValue(comp)) add("${COMP_DIR.getValue(comp)}/$arch/$dll")
|
||||
}
|
||||
|
||||
fun append(scope: String, p: Proton, comp: String, key: String, wcp: File) {
|
||||
val unpacked = unpack(key, wcp, comp)
|
||||
val files = unpacked.let { base ->
|
||||
File(base, "files").walkTopDown().filter { it.isFile }.map { it.relativeTo(base).invariantSeparatorsPath }
|
||||
.filter { owned(comp, it) }.associateWith { File(base, it) }
|
||||
}
|
||||
for (rel in managed(comp) - files.keys) {
|
||||
lines.append(scope).append('\t').append(p.dir.name).append('\t').append(p.version).append('\t').append(comp)
|
||||
.append('\t').append(rel).append("\t-\t-\n")
|
||||
}
|
||||
for ((rel, src) in files) {
|
||||
val guestSrc = "/" + src.relativeTo(root(context)).invariantSeparatorsPath
|
||||
lines.append(scope).append('\t').append(p.dir.name).append('\t').append(p.version).append('\t').append(comp)
|
||||
.append('\t').append(rel).append('\t').append(Hashes.sha256(src)).append('\t').append(guestSrc).append('\n')
|
||||
}
|
||||
}
|
||||
store.listFiles()?.filter { it.isDirectory && it.name !in keep }?.forEach { it.deleteRecursively() }
|
||||
val list = File(dir, "desired.tsv")
|
||||
val tmp = File(dir, "desired.tsv.tmp")
|
||||
tmp.writeText(lines.toString())
|
||||
tmp.renameTo(list)
|
||||
|
||||
fun choice(p: Proton, comp: String, entry: JSONObject): Pair<String, File>? {
|
||||
val file = entry.optString("file")
|
||||
return if (file.startsWith("original ")) {
|
||||
val version = safeName(file.removePrefix("original "))
|
||||
"original-${p.id}-$version-$comp" to File(originalsDir(context), "${p.id}/$version/$comp.wcp")
|
||||
} else {
|
||||
safeName(file.removeSuffix(".wcp")) to File(packagesDir(context), file)
|
||||
}.takeIf { it.second.isFile }
|
||||
}
|
||||
|
||||
val profiles = state.sub("profiles")
|
||||
val profiledComponents = buildSet {
|
||||
state.optJSONArray("profiledComponents")?.let { stored ->
|
||||
for (index in 0 until stored.length()) {
|
||||
stored.optString(index).takeIf(COMPONENTS::contains)?.let(::add)
|
||||
}
|
||||
}
|
||||
for (scope in profiles.keys()) {
|
||||
val profile = profiles.optJSONObject(scope) ?: continue
|
||||
COMPONENTS.filterTo(this) { profile.optString(it).isNotEmpty() }
|
||||
}
|
||||
}
|
||||
val active = state.sub("active")
|
||||
for (p in all) for (comp in COMPONENTS) {
|
||||
val entry = active.optJSONObject(p.id)?.optJSONObject(comp)
|
||||
val selected = entry?.takeIf { it.optString("protonVersion") == p.version }?.let { choice(p, comp, it) }
|
||||
if (selected != null) append("*", p, comp, selected.first, selected.second)
|
||||
else if (comp in profiledComponents) {
|
||||
ensureOriginal(context, p, comp, state)
|
||||
val original = originalFile(context, p, comp)
|
||||
check(original.isFile) { context.getString(R.string.cmgr_original_missing) }
|
||||
append("*", p, comp, "original-${p.id}-${safeName(p.version)}-$comp", original)
|
||||
}
|
||||
}
|
||||
for (scope in profiles.keys()) {
|
||||
val profile = profiles.optJSONObject(scope) ?: continue
|
||||
for (comp in COMPONENTS) {
|
||||
val file = profile.optString(comp)
|
||||
if (file.isEmpty()) continue
|
||||
val wcp = File(packagesDir(context), file)
|
||||
if (!wcp.isFile) continue
|
||||
val key = safeName(file.removeSuffix(".wcp"))
|
||||
for (p in all) append(scope, p, comp, key, wcp)
|
||||
}
|
||||
}
|
||||
return PreparedLaunchState(lines.toString(), keep)
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ actions
|
||||
@@ -615,6 +792,11 @@ object ComponentsManager {
|
||||
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 f = File(packagesDir(context), name)
|
||||
check(f.isFile) { context.getString(R.string.cmgr_package_not_stored, name) }
|
||||
f.delete()
|
||||
|
||||
@@ -24,6 +24,12 @@ object CrashHandler {
|
||||
Thread.setDefaultUncaughtExceptionHandler { thread, error ->
|
||||
try {
|
||||
Log.e(TAG, "uncaught on ${thread.name}", error)
|
||||
if (QuestExperimental.isSupported()) runCatching {
|
||||
File(context.filesDir, "quest-last-crash.txt").writeText(
|
||||
"${java.time.Instant.now()} thread=${thread.name}\n" +
|
||||
StringWriter().also { error.printStackTrace(PrintWriter(it)) }.toString()
|
||||
)
|
||||
}
|
||||
val dir = SessionPaths.current()
|
||||
if (dir != null && dir.isDirectory) {
|
||||
val trace = StringWriter().also { error.printStackTrace(PrintWriter(it)) }.toString()
|
||||
|
||||
@@ -13,6 +13,7 @@ object GameEnvironmentStore {
|
||||
private const val GUEST_FILE = "root/.config/droiddeck/game-environment.json"
|
||||
/** The published file's extra DXVK options (droiddeck-game-env reads it; the app's own file has none). */
|
||||
const val DXVK_CONFIG = "dxvkConfig"
|
||||
const val DXVK_CONFIG_GAMES = "dxvkConfigGames"
|
||||
|
||||
@Synchronized
|
||||
fun read(context: Context): GameEnvironment.Config {
|
||||
@@ -57,6 +58,13 @@ object GameEnvironmentStore {
|
||||
publish(context, config)
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun setGameFexPreset(context: Context, scope: String, preset: String?): GameEnvironment.Config {
|
||||
val config = GameEnvironment.withGameFexPreset(read(context), scope, preset)
|
||||
save(context, config)
|
||||
return config
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun publish(context: Context, config: GameEnvironment.Config = read(context)) {
|
||||
val resolved = config.copy(shared = GameEnvironment.defaults(SessionPrefs.fexPreset(context), SessionPrefs.forceSsbs(context)) + config.shared)
|
||||
@@ -68,6 +76,21 @@ object GameEnvironmentStore {
|
||||
TextureFiltering.autoLodBias(SessionState.upscaleRatio),
|
||||
)
|
||||
if (dxvk.isNotEmpty()) json.put(DXVK_CONFIG, dxvk)
|
||||
val autoBias = TextureFiltering.autoLodBias(SessionState.upscaleRatio)
|
||||
val generalAnisotropy = SessionPrefs.textureAnisotropy(context)
|
||||
val generalLodBias = SessionPrefs.textureLodBias(context)
|
||||
val gameDxvk = JSONObject()
|
||||
SessionPrefs.gameTextureFiltering(context).forEach { (scope, choice) ->
|
||||
gameDxvk.put(
|
||||
scope,
|
||||
TextureFiltering.dxvkOptions(
|
||||
choice.anisotropy ?: generalAnisotropy,
|
||||
choice.lodBias ?: generalLodBias,
|
||||
autoBias,
|
||||
),
|
||||
)
|
||||
}
|
||||
if (gameDxvk.length() > 0) json.put(DXVK_CONFIG_GAMES, gameDxvk)
|
||||
write(File(LinuxRuntime.rootDir(context), GUEST_FILE), json.toString())
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
internal class GameProfileFollowState {
|
||||
var followsSteam = true
|
||||
private set
|
||||
|
||||
fun selectManually() {
|
||||
followsSteam = false
|
||||
}
|
||||
|
||||
fun resumeFollowingSteam() {
|
||||
followsSteam = true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
internal class GameProfileInventoryCache<T : Any> {
|
||||
private val lock = Any()
|
||||
|
||||
private var revision: Long? = null
|
||||
private var value: List<T>? = null
|
||||
|
||||
// Called only by the refresh worker; the UI invalidates through request revisions.
|
||||
fun get(requestedRevision: Long, load: () -> List<T>): List<T> = synchronized(lock) {
|
||||
value?.takeIf { revision == requestedRevision } ?: load().toList().also {
|
||||
value = it
|
||||
revision = requestedRevision
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.content.Context
|
||||
import com.droiddeck.launcher.core.GameEnvironment
|
||||
|
||||
object GameProfileManager {
|
||||
@Synchronized
|
||||
fun reset(context: Context, scope: String) {
|
||||
require(scope.isNotEmpty() && GameEnvironment.validScope(scope))
|
||||
val failures = mutableListOf<Pair<String, Throwable>>()
|
||||
fun clear(name: String, action: () -> Unit) {
|
||||
runCatching(action).onFailure { failures += name to it }
|
||||
}
|
||||
|
||||
clear("environment") {
|
||||
GameEnvironmentStore.save(
|
||||
context,
|
||||
GameEnvironmentStore.read(context).withEntries(scope, emptyMap()),
|
||||
)
|
||||
}
|
||||
clear("Proton") { ProtonDefault.requestGame(context, scope, null) }
|
||||
clear("component packages") { ComponentsManager.clearGameComponents(context, scope) }
|
||||
clear("texture filtering") { SessionPrefs.clearGameTextureFiltering(context, scope) }
|
||||
clear("Windows components") { WinComponents.setPicks(context, scope, emptyList()) }
|
||||
|
||||
if (failures.isNotEmpty()) {
|
||||
val names = failures.joinToString { it.first }
|
||||
throw IllegalStateException("Could not clear: $names", failures.first().second)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
internal data class GameProfileRefreshState<T>(
|
||||
val data: T? = null,
|
||||
val loaded: Boolean = false,
|
||||
val failed: Boolean = false,
|
||||
) {
|
||||
fun succeeded(data: T) = GameProfileRefreshState(data, loaded = true)
|
||||
|
||||
fun failed() = copy(failed = true)
|
||||
|
||||
fun retrying() = copy(failed = false)
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
internal class LatestRequestCoordinator<T> {
|
||||
data class Request<T>(val generation: Long, val value: T)
|
||||
|
||||
private val lock = Any()
|
||||
private var generation = 0L
|
||||
private var running = false
|
||||
private var latest: Request<T>? = null
|
||||
private var pending: Request<T>? = null
|
||||
|
||||
fun submit(value: T): Boolean = synchronized(lock) {
|
||||
if (latest?.value != value) generation++
|
||||
pending = Request(generation, value).also { latest = it }
|
||||
if (running) {
|
||||
false
|
||||
} else {
|
||||
running = true
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
fun takeLatest(): Request<T>? = synchronized(lock) {
|
||||
pending.also {
|
||||
pending = null
|
||||
if (it == null) running = false
|
||||
}
|
||||
}
|
||||
|
||||
fun isLatest(request: Request<T>): Boolean = synchronized(lock) {
|
||||
request.generation == latest?.generation
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package com.droiddeck.launcher.session
|
||||
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.core.GameEnvironment
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
@@ -9,10 +10,12 @@ import java.io.File
|
||||
object ProtonDefault {
|
||||
private const val TAG = "ProtonDefault"
|
||||
private const val DIR = "root/.local/share/droiddeck-compat"
|
||||
private const val GAMES = "games.json"
|
||||
|
||||
data class Tool(val name: String, val display: String, val dir: String, val valve: Boolean)
|
||||
data class Request(val seq: Long, val valve: Boolean, val dir: String)
|
||||
data class State(val default: String?, val applied: Long, val live: Boolean, val pending: String?, val tools: List<Tool>)
|
||||
data class GameChoice(val valve: Boolean, val dir: String)
|
||||
|
||||
enum class Outcome { LIVE, NEXT_START, NOT_RUNNABLE }
|
||||
|
||||
@@ -60,6 +63,33 @@ object ProtonDefault {
|
||||
return protons.firstOrNull { it.valve == pick.first && it.dir.name == pick.second }?.id
|
||||
}
|
||||
|
||||
internal fun parseGames(text: String?): Map<String, GameChoice?> {
|
||||
val root = runCatching { JSONObject(text ?: "") }.getOrNull() ?: return emptyMap()
|
||||
if (root.optInt("version", 0) != 1) return emptyMap()
|
||||
val games = root.optJSONObject("games") ?: return emptyMap()
|
||||
return buildMap {
|
||||
games.keys().forEach { id ->
|
||||
if (!GameEnvironment.validScope(id)) return@forEach
|
||||
if (games.isNull(id)) {
|
||||
put(id, null)
|
||||
} else {
|
||||
val value = games.optJSONObject(id) ?: return@forEach
|
||||
val gameDir = value.optString("dir")
|
||||
val valve = value.opt("valve")
|
||||
if (gameDir.isNotEmpty() && valve is Boolean) put(id, GameChoice(valve, gameDir))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun gameChoice(context: Context, scope: String): GameChoice? =
|
||||
parseGames(read(File(dir(context), GAMES)))[scope]
|
||||
|
||||
fun gameSelectedId(context: Context, scope: String, protons: List<ComponentsManager.Proton>): String? {
|
||||
val pick = gameChoice(context, scope) ?: return null
|
||||
return protons.firstOrNull { it.valve == pick.valve && it.dir.name == pick.dir }?.id
|
||||
}
|
||||
|
||||
internal fun nextSeq(now: Long, state: State, previous: Request?): Long =
|
||||
maxOf(now, state.applied + 1, (previous?.seq ?: 0) + 1)
|
||||
|
||||
@@ -83,4 +113,33 @@ object ProtonDefault {
|
||||
val tool = state.tools.firstOrNull { it.valve == proton.valve && it.dir == proton.dir.name }
|
||||
return if (SessionState.running && state.live && (tool == null || state.pending != tool.name)) Outcome.LIVE else Outcome.NEXT_START
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun requestGame(context: Context, scope: String, proton: ComponentsManager.Proton?): Outcome {
|
||||
require(GameEnvironment.validScope(scope))
|
||||
val d = dir(context)
|
||||
val choices = parseGames(read(File(d, GAMES))).toMutableMap()
|
||||
choices[scope] = proton?.let { GameChoice(it.valve, it.dir.name) }
|
||||
val games = JSONObject()
|
||||
choices.forEach { (id, choice) ->
|
||||
games.put(id, choice?.let { JSONObject().put("valve", it.valve).put("dir", it.dir) } ?: JSONObject.NULL)
|
||||
}
|
||||
val staged = File(d, "$GAMES.staged")
|
||||
try {
|
||||
d.mkdirs()
|
||||
staged.writeText(JSONObject().put("version", 1).put("games", games).toString(1) + "\n")
|
||||
if (!staged.renameTo(File(d, GAMES))) throw java.io.IOException("rename failed")
|
||||
} catch (e: Exception) {
|
||||
staged.delete()
|
||||
Log.w(TAG, "could not write the per-game Proton request", e)
|
||||
throw e
|
||||
}
|
||||
val state = state(context)
|
||||
val tool = proton?.let { selected -> state.tools.firstOrNull { it.valve == selected.valve && it.dir == selected.dir.name } }
|
||||
return if (SessionState.running && state.live && (proton == null || tool != null && state.pending != tool.name)) {
|
||||
Outcome.LIVE
|
||||
} else {
|
||||
Outcome.NEXT_START
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -10,12 +10,15 @@ import com.droiddeck.launcher.core.FileUtils
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import java.io.File
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
|
||||
/** Immediate download and installation of the optional ARM64 Proton builds. */
|
||||
object ProtonExtras {
|
||||
private const val TAG = "ProtonExtras"
|
||||
private const val NEED_BYTES = 4L * 1024 * 1024 * 1024
|
||||
private const val RELEASES = "https://api.github.com/repos/%s/releases?per_page=15"
|
||||
/** How long a release check stands before the next one goes to GitHub. */
|
||||
const val CHECK_EVERY_MS = 6L * 60 * 60 * 1000
|
||||
@Volatile
|
||||
var installInProgress = false
|
||||
private set
|
||||
@@ -23,23 +26,122 @@ object ProtonExtras {
|
||||
class Tool(val id: String, val name: String, val prefix: String, val repo: String, val assetPattern: Regex)
|
||||
|
||||
/** [sha256] from GitHub's asset digest; [sha512] the URL of a checksum file published beside it. */
|
||||
private data class Asset(val tag: String, val name: String, val url: String, val sha512: String?, val size: Long,
|
||||
internal data class Asset(val tag: String, val name: String, val url: String, val sha512: String?, val size: Long,
|
||||
val sha256: String? = null)
|
||||
|
||||
val tools = listOf(
|
||||
Tool("ge", "GE-Proton", "GE-Proton", "GloriousEggroll/proton-ge-custom", Regex("aarch64\\.tar\\.(gz|xz)$")),
|
||||
Tool("cachyos", "proton-cachyos", "proton-cachyos", "CachyOS/proton-cachyos", Regex("arm64\\.tar\\.(gz|xz)$")),
|
||||
Tool("droiddeck", "DroidDeck-Proton", "DroidDeck-Proton", "The412Banner/DroidDeck-Proton", Regex("aarch64\\.tar\\.(gz|xz)$")),
|
||||
)
|
||||
|
||||
private fun home(context: Context) = File(LinuxRuntime.rootDir(context), "root")
|
||||
private fun requests(context: Context) = File(home(context), ".bl-proton-extra")
|
||||
private fun toolsDir(context: Context) = File(home(context), ".local/share/Steam/compatibilitytools.d")
|
||||
/** The release tag each build was installed from, by directory name. */
|
||||
private fun releasesFile(context: Context) = File(context.filesDir, "proton-extras.json")
|
||||
/** The newest release seen per source, and when it was looked up. */
|
||||
private fun latestFile(context: Context) = File(context.filesDir, "proton-latest.json")
|
||||
|
||||
/** The installed build's directory name (e.g. GE-Proton11-7), or null. */
|
||||
fun installed(context: Context, tool: Tool): String? =
|
||||
toolsDir(context).listFiles()
|
||||
/** The installed build's directory name (e.g. GE-Proton11-7), the newest when there are several, or null. */
|
||||
fun installed(context: Context, tool: Tool): String? = installedIn(toolsDir(context), tool).lastOrNull()
|
||||
|
||||
/** Every installed build's directory name, oldest first. */
|
||||
fun installedAll(context: Context, tool: Tool): List<String> = installedIn(toolsDir(context), tool)
|
||||
|
||||
internal fun installedIn(dir: File, tool: Tool): List<String> =
|
||||
dir.listFiles()
|
||||
?.filter { it.isDirectory && it.name.startsWith(tool.prefix) && File(it, "toolmanifest.vdf").isFile }
|
||||
?.maxByOrNull { it.name }?.name
|
||||
?.map { it.name }
|
||||
?.sortedWith { a, b -> compareVersions(a, b) }
|
||||
?: emptyList()
|
||||
|
||||
// Architecture names carry digits (aarch64, x86_64) that are not part of a version.
|
||||
private val ARCH = Regex("(?i)aarch64|arm64|x86_64|x86-64|amd64")
|
||||
private val NUMBER = Regex("\\d+")
|
||||
|
||||
/** The numbers in a release tag or build folder, in order: GE-Proton11-10 is 11, 10. */
|
||||
internal fun versionKey(name: String): List<Long> =
|
||||
NUMBER.findAll(ARCH.replace(name, " ")).mapNotNull { it.value.toLongOrNull() }.toList()
|
||||
|
||||
/** Orders by those numbers, so 11-10 is after 11-9; the name itself only breaks a tie. */
|
||||
internal fun compareVersions(a: String, b: String): Int {
|
||||
val x = versionKey(a)
|
||||
val y = versionKey(b)
|
||||
for (i in 0 until minOf(x.size, y.size)) if (x[i] != y[i]) return x[i].compareTo(y[i])
|
||||
return if (x.size != y.size) x.size.compareTo(y.size) else a.compareTo(b)
|
||||
}
|
||||
|
||||
/** [latest] when it is newer than every installed release, else null. Nothing installed is not an update. */
|
||||
internal fun updateFor(installed: List<String>, latest: String?): String? {
|
||||
if (latest == null || installed.isEmpty()) return null
|
||||
val newest = installed.maxWithOrNull { a, b -> compareVersions(a, b) } ?: return null
|
||||
val x = versionKey(latest)
|
||||
val y = versionKey(newest)
|
||||
for (i in 0 until minOf(x.size, y.size)) if (x[i] != y[i]) return if (x[i] > y[i]) latest else null
|
||||
return if (x.size > y.size) latest else null
|
||||
}
|
||||
|
||||
/** The release each installed build came from: the tag recorded at install, else its folder name. */
|
||||
fun installedTags(context: Context, tool: Tool): List<String> {
|
||||
val recorded = readJson(releasesFile(context))
|
||||
return installedAll(context, tool).map { recorded.optString(it).ifEmpty { it } }
|
||||
}
|
||||
|
||||
/** A newer release than the installed one, from the last check (no network), or null. */
|
||||
fun update(context: Context, tool: Tool): String? = updateFor(installedTags(context, tool), cachedLatest(context, tool))
|
||||
|
||||
fun cachedLatest(context: Context, tool: Tool): String? =
|
||||
readJson(latestFile(context)).optJSONObject(tool.id)?.optString("tag")?.ifEmpty { null }
|
||||
|
||||
/** Its own lock, not the install's: a check must not wait behind a download. */
|
||||
private val checkLock = Any()
|
||||
/** A failed look-up (offline) is not repeated on every resume, only after this long. */
|
||||
private const val RETRY_MS = 15L * 60 * 1000
|
||||
private var lastAttempt = 0L
|
||||
|
||||
/**
|
||||
* Looks up each source's newest release unless it was looked up within [CHECK_EVERY_MS] (or
|
||||
* [force]). Offline or rate limited, the last answer stands. True when anything was asked.
|
||||
*/
|
||||
fun checkLatest(context: Context, force: Boolean = false, now: Long = System.currentTimeMillis()): Boolean {
|
||||
synchronized(checkLock) {
|
||||
val file = latestFile(context)
|
||||
val cache = readJson(file)
|
||||
val due = tools.filter { tool ->
|
||||
val at = cache.optJSONObject(tool.id)?.optLong("at", 0L) ?: 0L
|
||||
force || (now - at) !in 0 until CHECK_EVERY_MS
|
||||
}
|
||||
if (due.isEmpty() || !force && (now - lastAttempt) in 0 until RETRY_MS) return false
|
||||
lastAttempt = now
|
||||
for (tool in due) {
|
||||
val tag = findLatestAsset(tool)?.tag ?: continue
|
||||
cache.put(tool.id, JSONObject().put("tag", tag).put("at", now))
|
||||
}
|
||||
runCatching { file.writeText(cache.toString()) }
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
private fun record(context: Context, tool: Tool, dir: String?, tag: String) {
|
||||
runCatching {
|
||||
val latest = readJson(latestFile(context))
|
||||
val known = latest.optJSONObject(tool.id)?.optString("tag")
|
||||
if (known.isNullOrEmpty() || compareVersions(tag, known) >= 0) {
|
||||
latest.put(tool.id, JSONObject().put("tag", tag).put("at", System.currentTimeMillis()))
|
||||
latestFile(context).writeText(latest.toString())
|
||||
}
|
||||
if (dir != null) {
|
||||
val releases = readJson(releasesFile(context))
|
||||
val present = toolsDir(context).list()?.toSet() ?: emptySet()
|
||||
releases.keys().asSequence().toList().filter { it !in present }.forEach { releases.remove(it) }
|
||||
releasesFile(context).writeText(releases.put(dir, tag).toString())
|
||||
}
|
||||
}.onFailure { Log.w(TAG, "record ${tool.id} $tag", it) }
|
||||
}
|
||||
|
||||
private fun readJson(file: File): JSONObject =
|
||||
runCatching { JSONObject(FileUtils.readString(file) ?: "{}") }.getOrDefault(JSONObject())
|
||||
|
||||
/** A request left by an earlier app version, still consumed by the session shim. */
|
||||
fun queued(context: Context, tool: Tool): Boolean =
|
||||
@@ -52,9 +154,15 @@ object ProtonExtras {
|
||||
else file.writeText(lines.joinToString("\n") + "\n")
|
||||
}
|
||||
|
||||
/** Deletes the installed build; Steam discovers its absence on its next start. */
|
||||
fun remove(context: Context, tool: Tool) {
|
||||
installed(context, tool)?.let { File(toolsDir(context), it).deleteRecursively() }
|
||||
/** Deletes one installed build ([dir], else the newest); Steam discovers its absence on its next start. */
|
||||
fun remove(context: Context, tool: Tool, dir: String? = null) {
|
||||
val name = if (dir != null) dir.takeIf { it in installedAll(context, tool) } ?: return else installed(context, tool) ?: return
|
||||
File(toolsDir(context), name).deleteRecursively()
|
||||
}
|
||||
|
||||
/** Deletes every build but the newest. */
|
||||
fun removeOlder(context: Context, tool: Tool) {
|
||||
installedAll(context, tool).dropLast(1).forEach { File(toolsDir(context), it).deleteRecursively() }
|
||||
}
|
||||
|
||||
/** Downloads, verifies and registers the latest build without waiting for another session. */
|
||||
@@ -145,9 +253,12 @@ object ProtonExtras {
|
||||
hostEnv["PROOT_TMP_DIR"] = context.cacheDir.path
|
||||
LinuxRuntime.prootLibraryPath(context).takeIf { it.isNotEmpty() }?.let { hostEnv["LD_LIBRARY_PATH"] = it }
|
||||
val child = process.start()
|
||||
var placed: String? = null
|
||||
child.inputStream.bufferedReader().useLines { lines ->
|
||||
lines.forEach { line ->
|
||||
Log.i(TAG, line)
|
||||
// "droiddeck-proton-extra: installed <folder>", the folder as the tarball names it.
|
||||
line.substringAfter("droiddeck-proton-extra: installed ", "").takeIf { it.isNotEmpty() }?.let { placed = it }
|
||||
if (line.contains("unpacking", ignoreCase = true) || line.contains("adopted", ignoreCase = true)) {
|
||||
onProgress(installing, -1)
|
||||
}
|
||||
@@ -158,6 +269,7 @@ object ProtonExtras {
|
||||
else {
|
||||
archive.delete()
|
||||
unqueue(context, tool)
|
||||
record(context, tool, placed, asset.tag)
|
||||
if (EsyncPacks.enabled(context)) {
|
||||
onProgress(context.getString(R.string.esync_fetching), -1)
|
||||
try {
|
||||
@@ -177,32 +289,36 @@ object ProtonExtras {
|
||||
private fun findLatestAsset(tool: Tool): Asset? {
|
||||
val releases = Downloader.downloadString(RELEASES.format(tool.repo)) ?: return null
|
||||
return try {
|
||||
val array = JSONArray(releases)
|
||||
for (i in 0 until array.length()) {
|
||||
val release = array.getJSONObject(i)
|
||||
if (release.optBoolean("draft", false)) continue
|
||||
val assets = release.optJSONArray("assets") ?: continue
|
||||
val entries = (0 until assets.length()).map { assets.getJSONObject(it) }
|
||||
val archive = entries.sortedBy { it.optString("name") }.firstOrNull { tool.assetPattern.containsMatchIn(it.optString("name")) } ?: continue
|
||||
val name = archive.optString("name")
|
||||
val stem = name.substringBefore(".tar")
|
||||
val checksum = entries.firstOrNull {
|
||||
it.optString("name").startsWith(stem) && it.optString("name").contains("sha512", ignoreCase = true)
|
||||
}?.optString("browser_download_url")?.takeIf { it.startsWith("http") }
|
||||
return Asset(
|
||||
release.optString("tag_name"), name,
|
||||
archive.optString("browser_download_url").takeIf { it.startsWith("http") } ?: continue, checksum,
|
||||
archive.optLong("size", 0L),
|
||||
Hashes.githubSha256(archive.optString("digest")),
|
||||
)
|
||||
}
|
||||
null
|
||||
pickAsset(tool, JSONArray(releases))
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "release metadata for ${tool.id}", e)
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
/** The newest full release in GitHub's list (newest first) that carries [tool]'s ARM64 archive. */
|
||||
internal fun pickAsset(tool: Tool, array: JSONArray): Asset? {
|
||||
for (i in 0 until array.length()) {
|
||||
val release = array.getJSONObject(i)
|
||||
if (release.optBoolean("draft", false) || release.optBoolean("prerelease", false)) continue
|
||||
val assets = release.optJSONArray("assets") ?: continue
|
||||
val entries = (0 until assets.length()).map { assets.getJSONObject(it) }
|
||||
val archive = entries.sortedBy { it.optString("name") }.firstOrNull { tool.assetPattern.containsMatchIn(it.optString("name")) } ?: continue
|
||||
val name = archive.optString("name")
|
||||
val stem = name.substringBefore(".tar")
|
||||
val checksum = entries.firstOrNull {
|
||||
it.optString("name").startsWith(stem) && it.optString("name").contains("sha512", ignoreCase = true)
|
||||
}?.optString("browser_download_url")?.takeIf { it.startsWith("http") }
|
||||
return Asset(
|
||||
release.optString("tag_name"), name,
|
||||
archive.optString("browser_download_url").takeIf { it.startsWith("http") } ?: continue, checksum,
|
||||
archive.optLong("size", 0L),
|
||||
Hashes.githubSha256(archive.optString("digest")),
|
||||
)
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
private fun requestLines(context: Context): List<String> =
|
||||
FileUtils.readString(requests(context))?.lines()?.filter { it.isNotBlank() } ?: emptyList()
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.content.Context
|
||||
import android.os.Build
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.BuildConfig
|
||||
import java.io.File
|
||||
|
||||
/** Defaults and launch evidence for this explicitly experimental Quest build. */
|
||||
object QuestExperimental {
|
||||
private const val TAG = "QuestExperimental"
|
||||
const val DRIVER = "turnip25.1.0-quest1"
|
||||
|
||||
// Quest 2 has an A6xx GPU and cannot use this bundled A7xx driver.
|
||||
internal fun supported(model: String, device: String, manufacturer: String): Boolean =
|
||||
model.equals("Quest 3", ignoreCase = true) || model.equals("Quest 3S", ignoreCase = true) ||
|
||||
((manufacturer.equals("Oculus", ignoreCase = true) || manufacturer.equals("Meta", ignoreCase = true)) &&
|
||||
(device == "eureka" || device == "panther"))
|
||||
|
||||
fun isSupported(): Boolean = supported(Build.MODEL, Build.DEVICE, Build.MANUFACTURER)
|
||||
|
||||
fun initialize(context: Context) {
|
||||
if (!isSupported()) return
|
||||
val prefs = context.getSharedPreferences("session", Context.MODE_PRIVATE)
|
||||
if (!prefs.getBoolean("questDefaultsV1", false)) {
|
||||
// Auto would download an unwrapped display driver and lose the compatibility path.
|
||||
// Apply once so deliberate changes made during headset testing remain possible.
|
||||
prefs.edit()
|
||||
.putString("gpuDriverMode", SessionPrefs.GPU_DRIVERS_MANUAL)
|
||||
.putString("androidDriver", DRIVER)
|
||||
.putString("linuxDriver", "")
|
||||
// The existing HDR option uses SurfaceControl presentation. This is a
|
||||
// corruption workaround from upstream issue #245, not a claim of HDR accuracy.
|
||||
.putBoolean("hdr.steam", true)
|
||||
.putBoolean("questDefaultsV1", true)
|
||||
.apply()
|
||||
}
|
||||
val report = buildString {
|
||||
appendLine("DroidDeck Quest Experimental ${BuildConfig.VERSION_NAME}")
|
||||
appendLine("package=${context.packageName}")
|
||||
appendLine("manufacturer=${Build.MANUFACTURER} model=${Build.MODEL}")
|
||||
appendLine("device=${Build.DEVICE} board=${Build.BOARD} hardware=${Build.HARDWARE}")
|
||||
appendLine("android=${Build.VERSION.RELEASE} sdk=${Build.VERSION.SDK_INT}")
|
||||
appendLine("abis=${Build.SUPPORTED_ABIS.joinToString()}")
|
||||
for (name in listOf("gpu_model", "gpu_chipid")) {
|
||||
val value = runCatching { File("/sys/class/kgsl/kgsl-3d0/$name").readText().trim() }
|
||||
.getOrDefault("unavailable")
|
||||
appendLine("$name=$value")
|
||||
}
|
||||
appendLine("driverMode=${SessionPrefs.gpuDriverMode(context)}")
|
||||
appendLine("androidDriver=${SessionPrefs.androidDriver(context)}")
|
||||
appendLine("steamSurfaceControlWorkaround=${SessionPrefs.hdr(context, "steam")}")
|
||||
appendLine("GPUOBJ fallback installed in Android driver and ARM64 libblsession")
|
||||
appendLine("Experimental Quest 3/3S compatibility; 2D panel application")
|
||||
}
|
||||
Log.i(TAG, report)
|
||||
runCatching { File(context.filesDir, "quest-startup.txt").writeText(report) }
|
||||
.onFailure { Log.w(TAG, "Could not write startup report", it) }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import com.droiddeck.launcher.core.FexPreset
|
||||
import com.droiddeck.launcher.core.GameEnvironment
|
||||
import com.droiddeck.launcher.frontend.Library
|
||||
|
||||
data class ProfileValue(val value: String, val inherited: Boolean)
|
||||
|
||||
data class SelectedGameProfile(
|
||||
val appId: Long,
|
||||
val name: String,
|
||||
val fexPreset: ProfileValue,
|
||||
val proton: ProfileValue,
|
||||
val protonId: String?,
|
||||
val components: Map<String, ProfileValue>,
|
||||
val componentFiles: Map<String, String>,
|
||||
val environmentOverrides: Int,
|
||||
val windowsComponentNames: List<String>,
|
||||
) {
|
||||
val hasOverrides: Boolean
|
||||
get() = !fexPreset.inherited ||
|
||||
!proton.inherited ||
|
||||
components.values.any { !it.inherited } ||
|
||||
environmentOverrides > 0 ||
|
||||
windowsComponentNames.isNotEmpty()
|
||||
|
||||
companion object {
|
||||
fun resolve(
|
||||
selectedAppId: Long,
|
||||
games: List<Library.SteamGame>,
|
||||
generalFexPreset: String,
|
||||
environment: GameEnvironment.Config,
|
||||
snapshot: ComponentsManager.Snapshot,
|
||||
generalProtonId: String?,
|
||||
gameProtonChoice: ProtonDefault.GameChoice?,
|
||||
gameProtonId: String?,
|
||||
gameComponents: Map<String, String>,
|
||||
gameWindowsComponents: List<String>,
|
||||
): SelectedGameProfile? {
|
||||
val game = games.firstOrNull { it.profileKey == selectedAppId.toString() } ?: return null
|
||||
val fexOverride = GameEnvironment.gameFexPreset(environment, game.profileKey)
|
||||
val selectedProtonId = if (gameProtonChoice == null) generalProtonId else gameProtonId
|
||||
val selectedProton = snapshot.protons.firstOrNull { it.proton.id == selectedProtonId }
|
||||
val packages = snapshot.packages.associateBy { it.file }
|
||||
val components = ComponentsManager.COMPONENTS.associateWith { component ->
|
||||
val override = gameComponents[component]
|
||||
ProfileValue(
|
||||
value = override?.let { packages[it]?.version ?: it }
|
||||
?: selectedProton?.components?.get(component)?.selected.orEmpty(),
|
||||
inherited = override == null,
|
||||
)
|
||||
}
|
||||
val otherEnvironment = environment.games[game.profileKey].orEmpty().keys - FexPreset.environmentKeys
|
||||
return SelectedGameProfile(
|
||||
appId = selectedAppId,
|
||||
name = game.name,
|
||||
fexPreset = ProfileValue(fexOverride ?: generalFexPreset, fexOverride == null),
|
||||
proton = ProfileValue(
|
||||
selectedProton?.proton?.name ?: gameProtonChoice?.dir.orEmpty(),
|
||||
gameProtonChoice == null,
|
||||
),
|
||||
protonId = selectedProtonId,
|
||||
components = components,
|
||||
componentFiles = gameComponents,
|
||||
environmentOverrides = otherEnvironment.size,
|
||||
windowsComponentNames = gameWindowsComponents.map(WinComponentNames::of),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -72,6 +72,7 @@ object SessionFiles {
|
||||
"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",
|
||||
"usr/local/bin/droiddeck-launcher-cores" to "usr/local/bin/droiddeck-launcher-cores",
|
||||
"usr/local/bin/droiddeck-proton-extra" to "usr/local/bin/droiddeck-proton-extra",
|
||||
"usr/local/bin/droiddeck-netmanager" to "usr/local/bin/droiddeck-netmanager",
|
||||
"usr/local/bin/droiddeck-login1" to "usr/local/bin/droiddeck-login1",
|
||||
|
||||
@@ -4,12 +4,15 @@ import android.content.Context
|
||||
import android.content.pm.ActivityInfo
|
||||
import androidx.annotation.StringRes
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.core.GameEnvironment
|
||||
import com.droiddeck.launcher.core.TextureFiltering
|
||||
import com.droiddeck.launcher.gpu.ScreenEffects
|
||||
import org.json.JSONObject
|
||||
|
||||
/** The in-session switches: the HUD and how the on-screen controls decide to appear. */
|
||||
object SessionPrefs {
|
||||
data class GameTextureFiltering(val anisotropy: Int? = null, val lodBias: String? = null)
|
||||
|
||||
const val SUSPEND_AUTO = "auto"
|
||||
const val SUSPEND_NATIVE = "native"
|
||||
const val SUSPEND_MANUAL = "manual"
|
||||
@@ -868,6 +871,74 @@ object SessionPrefs {
|
||||
publishGameEnvironment(context)
|
||||
}
|
||||
|
||||
fun gameTextureFiltering(context: Context, scope: String): GameTextureFiltering {
|
||||
require(GameEnvironment.validScope(scope))
|
||||
return gameTextureFiltering(context)[scope] ?: GameTextureFiltering()
|
||||
}
|
||||
|
||||
fun gameTextureFiltering(context: Context): Map<String, GameTextureFiltering> {
|
||||
val json = runCatching {
|
||||
JSONObject(prefs(context).getString("gameTextureFiltering", null) ?: "{}")
|
||||
}.getOrElse { JSONObject() }
|
||||
return buildMap {
|
||||
json.keys().forEach { scope ->
|
||||
if (!GameEnvironment.validScope(scope)) return@forEach
|
||||
val entry = json.optJSONObject(scope) ?: return@forEach
|
||||
val anisotropy = entry.optInt("anisotropy").takeIf {
|
||||
entry.has("anisotropy") && it in TextureFiltering.ANISOTROPY
|
||||
}
|
||||
val lodBias = entry.optString("lodBias").takeIf {
|
||||
entry.has("lodBias") && it in TextureFiltering.LOD_BIAS
|
||||
}
|
||||
if (anisotropy != null || lodBias != null) {
|
||||
put(scope, GameTextureFiltering(anisotropy, lodBias))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun setGameTextureAnisotropy(context: Context, scope: String, value: Int?) {
|
||||
require(value == null || value in TextureFiltering.ANISOTROPY)
|
||||
updateGameTextureFiltering(context, scope) { it.copy(anisotropy = value) }
|
||||
}
|
||||
|
||||
fun setGameTextureLodBias(context: Context, scope: String, choice: String?) {
|
||||
require(choice == null || choice in TextureFiltering.LOD_BIAS)
|
||||
updateGameTextureFiltering(context, scope) { it.copy(lodBias = choice) }
|
||||
}
|
||||
|
||||
fun clearGameTextureFiltering(context: Context, scope: String) {
|
||||
require(GameEnvironment.validScope(scope))
|
||||
val choices = gameTextureFiltering(context).toMutableMap()
|
||||
if (choices.remove(scope) == null) return
|
||||
saveGameTextureFiltering(context, choices)
|
||||
publishGameEnvironment(context)
|
||||
}
|
||||
|
||||
private fun updateGameTextureFiltering(
|
||||
context: Context,
|
||||
scope: String,
|
||||
change: (GameTextureFiltering) -> GameTextureFiltering,
|
||||
) {
|
||||
require(GameEnvironment.validScope(scope))
|
||||
val choices = gameTextureFiltering(context).toMutableMap()
|
||||
val next = change(choices[scope] ?: GameTextureFiltering())
|
||||
if (next.anisotropy == null && next.lodBias == null) choices.remove(scope) else choices[scope] = next
|
||||
saveGameTextureFiltering(context, choices)
|
||||
publishGameEnvironment(context)
|
||||
}
|
||||
|
||||
private fun saveGameTextureFiltering(context: Context, choices: Map<String, GameTextureFiltering>) {
|
||||
val json = JSONObject()
|
||||
choices.forEach { (id, choice) ->
|
||||
json.put(id, JSONObject().apply {
|
||||
choice.anisotropy?.let { put("anisotropy", it) }
|
||||
choice.lodBias?.let { put("lodBias", it) }
|
||||
})
|
||||
}
|
||||
prefs(context).edit().putString("gameTextureFiltering", json.toString()).apply()
|
||||
}
|
||||
|
||||
/** Hands the change to the next game launch (GameEnvironmentStore); the running game keeps its own. */
|
||||
private fun publishGameEnvironment(context: Context) {
|
||||
runCatching { GameEnvironmentStore.publish(context) }
|
||||
|
||||
@@ -343,6 +343,7 @@ class SessionService : Service() {
|
||||
|
||||
val size = SessionState.outputSize
|
||||
val guest = ArrayList<String>()
|
||||
guest.add("DROIDDECK_BWRAP_SOCKET=" + com.droiddeck.launcher.runtime.BwrapSpawner.socket(this))
|
||||
// The desktop's Steam launchers start the client there (droiddeck-steam-launch), through the
|
||||
// same set-up as a Steam session: it gets what the client and its games are started with.
|
||||
val steamHere = SessionState.mode == MODE_STEAM || SessionState.mode == MODE_DESKTOP
|
||||
|
||||
@@ -548,10 +548,10 @@ public final class EpicDownloadManager {
|
||||
try {
|
||||
JSONObject root = new JSONObject(new String(bytes, StandardCharsets.UTF_8));
|
||||
int manifestVersion = 0;
|
||||
try { manifestVersion = Integer.parseInt(root.optString("ManifestFileVersion", "0")); } catch (NumberFormatException ignored) {}
|
||||
try { manifestVersion = (int) blobToNum(root.optString("ManifestFileVersion", "0")); } catch (NumberFormatException ignored) {}
|
||||
Manifest m = new Manifest();
|
||||
m.chunkDir = manifestVersion >= 15 ? "ChunksV4" : manifestVersion >= 6 ? "ChunksV3" : manifestVersion >= 3 ? "ChunksV2" : "ChunksV4";
|
||||
m.launchExe = root.optString("LaunchExe", "").replace('\\', '/');
|
||||
m.launchExe = root.optString("LaunchExeString", root.optString("LaunchExe", "")).replace('\\', '/');
|
||||
m.launchCommand = root.optString("LaunchCommand", "");
|
||||
m.buildVersion = root.optString("BuildVersionString", "");
|
||||
m.prereqName = root.optString("PrereqName", "");
|
||||
@@ -568,10 +568,9 @@ public final class EpicDownloadManager {
|
||||
if (guidHex.length() < 32) continue;
|
||||
ChunkInfo c = new ChunkInfo();
|
||||
for (int k = 0; k < 4; k++) c.guid[k] = (int) Long.parseLong(guidHex.substring(k * 8, k * 8 + 8), 16);
|
||||
String hashHex = chunkHashList.getString(guidHex);
|
||||
if (hashHex != null && hashHex.length() >= 16) { try { c.hash = Long.parseUnsignedLong(hashHex.substring(0, 16), 16); } catch (Exception ignored) {} }
|
||||
if (dataGroupList != null) { try { c.groupNum = Integer.parseInt(dataGroupList.optString(guidHex, "0")); } catch (NumberFormatException ignored) {} }
|
||||
if (chunkFilesizeList != null) { try { c.fileSize = Long.parseLong(chunkFilesizeList.optString(guidHex, "0"), 16); } catch (NumberFormatException ignored) {} }
|
||||
try { c.hash = blobToNum(chunkHashList.getString(guidHex)); } catch (NumberFormatException ignored) {}
|
||||
if (dataGroupList != null) { try { c.groupNum = (int) blobToNum(dataGroupList.optString(guidHex, "0")); } catch (NumberFormatException ignored) {} }
|
||||
if (chunkFilesizeList != null) { try { c.fileSize = blobToNum(chunkFilesizeList.optString(guidHex, "0")); } catch (NumberFormatException ignored) {} }
|
||||
chunkMap.put(guidHex, c);
|
||||
}
|
||||
JSONArray fileList = root.optJSONArray("FileManifestList");
|
||||
@@ -589,8 +588,8 @@ public final class EpicDownloadManager {
|
||||
ChunkPart part = new ChunkPart();
|
||||
String g = po.optString("Guid", "");
|
||||
if (g.length() >= 32) for (int k = 0; k < 4; k++) part.guid[k] = (int) Long.parseLong(g.substring(k * 8, k * 8 + 8), 16);
|
||||
try { part.offset = Integer.parseInt(po.optString("Offset", "0")); } catch (NumberFormatException ignored) {}
|
||||
try { part.size = Integer.parseInt(po.optString("Size", "0")); } catch (NumberFormatException ignored) {}
|
||||
try { part.offset = (int) blobToNum(po.optString("Offset", "0")); } catch (NumberFormatException ignored) {}
|
||||
try { part.size = (int) blobToNum(po.optString("Size", "0")); } catch (NumberFormatException ignored) {}
|
||||
fi.parts.add(part);
|
||||
}
|
||||
files.add(fi);
|
||||
@@ -604,6 +603,24 @@ public final class EpicDownloadManager {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A JSON manifest writes every number as a "blob": each byte as three decimal digits, least
|
||||
* significant first ("013000000000" = 13), as Legendary's blob_to_num reads it. Bits past 64
|
||||
* are dropped; a group that is not digits throws.
|
||||
*/
|
||||
static long blobToNum(String blob) {
|
||||
long num = 0;
|
||||
for (int i = 0, shift = 0; i < blob.length(); i += 3, shift += 8) {
|
||||
String group = blob.substring(i, Math.min(i + 3, blob.length()));
|
||||
for (int k = 0; k < group.length(); k++) {
|
||||
char ch = group.charAt(k);
|
||||
if (ch < '0' || ch > '9') throw new NumberFormatException("not a blob: " + blob);
|
||||
}
|
||||
if (shift < 64) num += Long.parseLong(group) << shift;
|
||||
}
|
||||
return num;
|
||||
}
|
||||
|
||||
public static String readFString(ByteBuffer buf) {
|
||||
int length = buf.getInt();
|
||||
if (length == 0) return "";
|
||||
|
||||
@@ -37,6 +37,7 @@ import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.outlined.Delete
|
||||
import androidx.compose.material.icons.outlined.Refresh
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.LinearProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
@@ -80,6 +81,19 @@ import com.droiddeck.launcher.session.ComponentsManager
|
||||
import com.droiddeck.launcher.session.ComponentsManager.CatalogItem
|
||||
import com.droiddeck.launcher.session.ComponentsManager.Snapshot
|
||||
import kotlinx.coroutines.delay
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import com.droiddeck.launcher.core.FexPreset
|
||||
import com.droiddeck.launcher.core.GameEnvironment
|
||||
import com.droiddeck.launcher.frontend.Library
|
||||
import com.droiddeck.launcher.session.GameEnvironmentStore
|
||||
import com.droiddeck.launcher.session.GameProfileManager
|
||||
import com.droiddeck.launcher.session.ProtonDefault
|
||||
import com.droiddeck.launcher.session.WinComponents
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import java.text.DateFormat
|
||||
import java.util.Date
|
||||
|
||||
@@ -108,6 +122,13 @@ private class InstalledItem(
|
||||
val protonVersion: String?,
|
||||
)
|
||||
|
||||
private data class ProfileEditorState(
|
||||
val environment: GameEnvironment.Config,
|
||||
val protonChoice: ProtonDefault.GameChoice?,
|
||||
val protonId: String?,
|
||||
val components: Map<String, String>,
|
||||
)
|
||||
|
||||
private val GOLD = Color(0xFFF2C66D)
|
||||
private val QUEUED = Color(0xFFFFB86B)
|
||||
private val ROW_SHAPE = RoundedCornerShape(10.dp)
|
||||
@@ -142,6 +163,9 @@ fun ComponentsPage(
|
||||
onRefresh: () -> Unit,
|
||||
onImport: () -> Unit,
|
||||
onBack: () -> Unit,
|
||||
games: List<Library.SteamGame> = emptyList(),
|
||||
generalFexPreset: String = "",
|
||||
onGeneralFexPreset: (String) -> Unit = {},
|
||||
requestInitialFocus: Boolean = true,
|
||||
/** The GPU drivers layer ([GPU_TAB]): what it shows and does. */
|
||||
gpu: GpuDriversState = GpuDriversState(),
|
||||
@@ -160,6 +184,209 @@ fun ComponentsPage(
|
||||
val inputMode = LocalInputModeManager.current
|
||||
val layer = if (comp in LAYERS) comp else GPU_TAB
|
||||
BackHandler(onBack = onBack)
|
||||
var scopeMenu by remember { mutableStateOf(false) }
|
||||
var selectedGameKey by remember { mutableStateOf<String?>(null) }
|
||||
var fexMenu by remember { mutableStateOf(false) }
|
||||
var gameProtonMenu by remember { mutableStateOf(false) }
|
||||
var gameProtonId by remember { mutableStateOf<String?>(null) }
|
||||
var gameProtonChoice by remember { mutableStateOf<ProtonDefault.GameChoice?>(null) }
|
||||
var gameComponents by remember { mutableStateOf<Map<String, String>>(emptyMap()) }
|
||||
var gameComponentMenu by remember { mutableStateOf<String?>(null) }
|
||||
var environmentEditor by remember { mutableStateOf(false) }
|
||||
var winComponentsOpen by remember { mutableStateOf<Boolean?>(null) }
|
||||
var winComponentsRevision by remember { mutableStateOf(0) }
|
||||
var environment by remember { mutableStateOf<GameEnvironment.Config?>(null) }
|
||||
var profileLoading by remember { mutableStateOf(false) }
|
||||
var profileLoadGeneration by remember { mutableStateOf(0L) }
|
||||
var environmentBusy by remember { mutableStateOf(false) }
|
||||
var environmentError by remember { mutableStateOf(false) }
|
||||
var profileNotice by remember { mutableStateOf<String?>(null) }
|
||||
var confirm by remember { mutableStateOf<Pair<String, () -> Unit>?>(null) }
|
||||
var confirmTitle by remember { mutableStateOf("") }
|
||||
var confirmVerb by remember { mutableStateOf(R.string.comp_swap) }
|
||||
fun ask(title: String, body: String, verb: Int, action: () -> Unit) {
|
||||
confirmTitle = title
|
||||
confirmVerb = verb
|
||||
confirm = body to action
|
||||
}
|
||||
val coroutine = rememberCoroutineScope()
|
||||
val selectedGame = games.firstOrNull { it.profileKey == selectedGameKey }
|
||||
LaunchedEffect(Unit) {
|
||||
runCatching { withContext(Dispatchers.IO) { GameEnvironmentStore.read(ctx) } }
|
||||
.onSuccess { environment = it }
|
||||
.onFailure { environmentError = true }
|
||||
}
|
||||
LaunchedEffect(games, selectedGameKey) {
|
||||
if (selectedGameKey != null && games.none { it.profileKey == selectedGameKey }) selectedGameKey = null
|
||||
}
|
||||
LaunchedEffect(selectedGame?.profileKey, snapshot) {
|
||||
profileLoadGeneration++
|
||||
val generation = profileLoadGeneration
|
||||
val game = selectedGame
|
||||
profileNotice = null
|
||||
environmentError = false
|
||||
gameProtonChoice = null
|
||||
gameProtonId = null
|
||||
gameComponents = emptyMap()
|
||||
gameProtonMenu = false
|
||||
gameComponentMenu = null
|
||||
fexMenu = false
|
||||
if (game == null) {
|
||||
profileLoading = false
|
||||
return@LaunchedEffect
|
||||
}
|
||||
profileLoading = true
|
||||
try {
|
||||
val (choice, id, components) = withContext(Dispatchers.IO) {
|
||||
val choice = ProtonDefault.gameChoice(ctx, game.profileKey)
|
||||
Triple(
|
||||
choice,
|
||||
ProtonDefault.gameSelectedId(ctx, game.profileKey, snapshot?.protons.orEmpty().map { it.proton }),
|
||||
ComponentsManager.gameComponents(ctx, game.profileKey),
|
||||
)
|
||||
}
|
||||
if (profileLoadGeneration == generation && selectedGameKey == game.profileKey) {
|
||||
gameProtonChoice = choice
|
||||
gameProtonId = id
|
||||
gameComponents = components
|
||||
}
|
||||
} catch (error: CancellationException) {
|
||||
throw error
|
||||
} catch (error: Exception) {
|
||||
if (profileLoadGeneration == generation && selectedGameKey == game.profileKey) {
|
||||
environmentError = true
|
||||
profileNotice = ctx.getString(
|
||||
R.string.comp_game_load_failed,
|
||||
game.name,
|
||||
error.message ?: error.javaClass.simpleName,
|
||||
)
|
||||
}
|
||||
} finally {
|
||||
if (profileLoadGeneration == generation) profileLoading = false
|
||||
}
|
||||
}
|
||||
fun setGameFexPreset(preset: String?) {
|
||||
val game = selectedGame ?: return
|
||||
environmentBusy = true
|
||||
profileNotice = null
|
||||
coroutine.launch {
|
||||
runCatching {
|
||||
withContext(Dispatchers.IO) {
|
||||
GameEnvironmentStore.setGameFexPreset(ctx, game.profileKey, preset)
|
||||
}
|
||||
}.onSuccess { saved ->
|
||||
environment = saved
|
||||
if (selectedGameKey == game.profileKey) {
|
||||
environmentError = false
|
||||
profileNotice = ctx.getString(R.string.comp_game_saved_next, game.name)
|
||||
}
|
||||
}.onFailure {
|
||||
if (selectedGameKey == game.profileKey) {
|
||||
environmentError = true
|
||||
profileNotice = ctx.getString(R.string.comp_game_save_failed, it.message ?: it.javaClass.simpleName)
|
||||
}
|
||||
}
|
||||
environmentBusy = false
|
||||
}
|
||||
}
|
||||
fun setGameProton(id: String?) {
|
||||
val game = selectedGame ?: return
|
||||
val proton = id?.let { wanted -> snapshot?.protons?.firstOrNull { it.proton.id == wanted }?.proton }
|
||||
environmentBusy = true
|
||||
profileNotice = null
|
||||
coroutine.launch {
|
||||
runCatching { withContext(Dispatchers.IO) { ProtonDefault.requestGame(ctx, game.profileKey, proton) } }
|
||||
.onSuccess { outcome ->
|
||||
if (selectedGameKey == game.profileKey) {
|
||||
gameProtonChoice = proton?.let { ProtonDefault.GameChoice(it.valve, it.dir.name) }
|
||||
gameProtonId = id
|
||||
environmentError = false
|
||||
profileNotice = ctx.getString(
|
||||
when (outcome) {
|
||||
ProtonDefault.Outcome.LIVE -> R.string.comp_game_proton_live
|
||||
ProtonDefault.Outcome.NEXT_START -> R.string.comp_game_proton_next
|
||||
ProtonDefault.Outcome.NOT_RUNNABLE -> R.string.comp_game_proton_not_runnable
|
||||
},
|
||||
game.name,
|
||||
)
|
||||
}
|
||||
}
|
||||
.onFailure {
|
||||
if (selectedGameKey == game.profileKey) {
|
||||
environmentError = true
|
||||
profileNotice = ctx.getString(R.string.comp_game_save_failed, it.message ?: it.javaClass.simpleName)
|
||||
}
|
||||
}
|
||||
environmentBusy = false
|
||||
}
|
||||
}
|
||||
fun setGameComponent(comp: String, file: String?) {
|
||||
val game = selectedGame ?: return
|
||||
environmentBusy = true
|
||||
profileNotice = null
|
||||
coroutine.launch {
|
||||
runCatching { withContext(Dispatchers.IO) { ComponentsManager.setGameComponent(ctx, game.profileKey, comp, file) } }
|
||||
.onSuccess {
|
||||
val components = ComponentsManager.gameComponents(ctx, game.profileKey)
|
||||
if (selectedGameKey == game.profileKey) {
|
||||
gameComponents = components
|
||||
environmentError = false
|
||||
profileNotice = ctx.getString(R.string.comp_game_saved_next, game.name)
|
||||
}
|
||||
}
|
||||
.onFailure {
|
||||
if (selectedGameKey == game.profileKey) {
|
||||
environmentError = true
|
||||
profileNotice = ctx.getString(R.string.comp_game_save_failed, it.message ?: it.javaClass.simpleName)
|
||||
}
|
||||
}
|
||||
environmentBusy = false
|
||||
}
|
||||
}
|
||||
fun resetGameProfile() {
|
||||
val game = selectedGame ?: return
|
||||
environmentBusy = true
|
||||
profileNotice = null
|
||||
coroutine.launch {
|
||||
runCatching {
|
||||
withContext(Dispatchers.IO) {
|
||||
val resetFailure = runCatching { GameProfileManager.reset(ctx, game.profileKey) }.exceptionOrNull()
|
||||
val config = GameEnvironmentStore.read(ctx)
|
||||
val choice = ProtonDefault.gameChoice(ctx, game.profileKey)
|
||||
val id = ProtonDefault.gameSelectedId(
|
||||
ctx,
|
||||
game.profileKey,
|
||||
snapshot?.protons.orEmpty().map { it.proton },
|
||||
)
|
||||
val components = ComponentsManager.gameComponents(ctx, game.profileKey)
|
||||
ProfileEditorState(config, choice, id, components) to resetFailure
|
||||
}
|
||||
}.onSuccess { (state, resetFailure) ->
|
||||
environment = state.environment
|
||||
if (selectedGameKey == game.profileKey) {
|
||||
gameProtonChoice = state.protonChoice
|
||||
gameProtonId = state.protonId
|
||||
gameComponents = state.components
|
||||
winComponentsRevision++
|
||||
environmentError = resetFailure != null
|
||||
profileNotice = if (resetFailure == null) {
|
||||
ctx.getString(R.string.comp_game_reset_done, game.name)
|
||||
} else {
|
||||
ctx.getString(
|
||||
R.string.comp_game_reset_failed,
|
||||
resetFailure.message ?: resetFailure.javaClass.simpleName,
|
||||
)
|
||||
}
|
||||
}
|
||||
}.onFailure {
|
||||
if (selectedGameKey == game.profileKey) {
|
||||
environmentError = true
|
||||
profileNotice = ctx.getString(R.string.comp_game_reset_failed, it.message ?: it.javaClass.simpleName)
|
||||
}
|
||||
}
|
||||
environmentBusy = false
|
||||
}
|
||||
}
|
||||
|
||||
val views = snapshot?.protons ?: emptyList()
|
||||
val view = views.firstOrNull { it.proton.id == protonId } ?: views.firstOrNull()
|
||||
@@ -247,7 +474,7 @@ fun ComponentsPage(
|
||||
val layerFocus = remember { LAYERS.associateWith { FocusRequester() } }
|
||||
// Arrived (from the rail, a hop, a game's card): a pad starts on the chosen layer.
|
||||
LaunchedEffect(requestInitialFocus) {
|
||||
if (!requestInitialFocus || inputMode.inputMode != InputMode.Keyboard) return@LaunchedEffect
|
||||
if (!requestInitialFocus || selectedGame != null || inputMode.inputMode != InputMode.Keyboard) return@LaunchedEffect
|
||||
delay(Motion.ms(200).toLong())
|
||||
focusSoon { layerFocus.getValue(layer) }
|
||||
}
|
||||
@@ -259,7 +486,7 @@ fun ComponentsPage(
|
||||
LaunchedEffect(layer) {
|
||||
if (seenLayer[0] == layer) return@LaunchedEffect
|
||||
seenLayer[0] = layer
|
||||
if (!pageFocused || inputMode.inputMode != InputMode.Keyboard) return@LaunchedEffect
|
||||
if (selectedGame != null || !pageFocused || inputMode.inputMode != InputMode.Keyboard) return@LaunchedEffect
|
||||
if (narrowOpen != null) runCatching { firstRow.requestFocus() }
|
||||
else focusSoon { layerFocus.getValue(layer) }
|
||||
}
|
||||
@@ -316,7 +543,7 @@ fun ComponentsPage(
|
||||
val availableTitle: @Composable (String) -> String = { l ->
|
||||
when (l) {
|
||||
GPU_TAB -> stringResource(R.string.comp_available_count, gpu.pairs.count { !it.installed && it.complete && (it.suits || showAllPairs) })
|
||||
PROTON_TAB -> stringResource(R.string.comp_available_count, protons.rows.count { it.installed == null })
|
||||
PROTON_TAB -> stringResource(R.string.comp_available_count, protons.rows.count { it.installed == null || it.update != null })
|
||||
else -> stringResource(R.string.comp_nightlies_count, availableFor(l, catalog, snapshot).size)
|
||||
}
|
||||
}
|
||||
@@ -355,7 +582,7 @@ fun ComponentsPage(
|
||||
views.forEachIndexed { i, v ->
|
||||
val key = "proton:${v.proton.id}"
|
||||
val swaps = v.components.values.count { it.activeFile != null }
|
||||
val extra = protons.rows.firstOrNull { it.installed == v.proton.dir.name }
|
||||
val extra = protons.rows.firstOrNull { v.proton.dir.name in it.installedAll }
|
||||
val removable = extra != null && protons.busyId == null && protons.runtimeReady && !protons.sessionRunning
|
||||
ChoiceLine(
|
||||
v.proton.name,
|
||||
@@ -365,8 +592,8 @@ fun ComponentsPage(
|
||||
modifier = (if (i == 0) Modifier.focusRequester(firstRow) else Modifier).trackRow(key, rowsAt),
|
||||
onSelect = { if (v.proton.id != view?.proton?.id) { onProton(v.proton.id); flyHome(key, PROTON_TAB) } },
|
||||
onDelete = {
|
||||
if (extra != null) ask(key, right, ctx.getString(R.string.proton_remove_title, v.proton.name), "", ctx.getString(R.string.store_remove), true, v.proton.name) {
|
||||
protonActions.onRemove(extra.id)
|
||||
if (extra != null) ask(key, right, ctx.getString(R.string.proton_remove_title, v.proton.name), ctx.getString(R.string.proton_remove_body), ctx.getString(R.string.store_remove), true, v.proton.name) {
|
||||
protonActions.onRemove(extra.id, v.proton.dir.name)
|
||||
}
|
||||
},
|
||||
)
|
||||
@@ -416,14 +643,22 @@ fun ComponentsPage(
|
||||
}
|
||||
}
|
||||
PROTON_TAB -> {
|
||||
val rows = protons.rows.filter { it.installed == null }
|
||||
// Not installed, and installed with a newer release out: an update goes in beside the
|
||||
// build it replaces, which stays until it is removed (games are mapped to it by name).
|
||||
val rows = protons.rows.filter { it.installed == null || it.update != null }
|
||||
if (rows.isEmpty()) EmptyLine(stringResource(R.string.comp_nothing_new))
|
||||
for (row in rows) GetLine(
|
||||
row.name, if (row.queued) stringResource(R.string.proton_queued) else stringResource(R.string.proton_not_installed),
|
||||
row.name,
|
||||
when {
|
||||
row.update != null -> stringResource(R.string.proton_update_available, row.update)
|
||||
row.queued -> stringResource(R.string.proton_queued)
|
||||
else -> stringResource(R.string.proton_not_installed)
|
||||
},
|
||||
progress = if (protons.busyId == row.id) protons.percent else null,
|
||||
stage = if (protons.busyId == row.id) protons.stage else null,
|
||||
enabled = protons.busyId == null && protons.runtimeReady && !protons.sessionRunning,
|
||||
onCancel = if (row.queued && protons.busyId == null && !protons.sessionRunning) ({ protonActions.onCancel(row.id) }) else null,
|
||||
action = if (row.update != null) stringResource(R.string.common_update) else null,
|
||||
) { protonActions.onInstall(row.id) }
|
||||
}
|
||||
else -> {
|
||||
@@ -461,7 +696,21 @@ fun ComponentsPage(
|
||||
}
|
||||
}
|
||||
}
|
||||
PROTON_TAB -> {}
|
||||
PROTON_TAB -> {
|
||||
val idle = protons.busyId == null && protons.runtimeReady && !protons.sessionRunning
|
||||
for (row in protons.rows.filter { it.installedAll.size > 1 }) {
|
||||
val key = "older:${row.id}"
|
||||
val older = row.installedAll.dropLast(1)
|
||||
Box(Modifier.trackRow(key, rowsAt)) {
|
||||
FocusText(stringResource(R.string.proton_remove_older, row.name), if (idle) pal.signal else colors.onSurfaceVariant) {
|
||||
if (!idle) return@FocusText
|
||||
ask(key, false, ctx.getString(R.string.proton_remove_older, row.name) + "?",
|
||||
ctx.getString(R.string.proton_remove_older_body, older.joinToString(", ")),
|
||||
ctx.getString(R.string.store_remove), true, row.name) { protonActions.onRemoveOlder(row.id) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
else -> {
|
||||
SmallButton(stringResource(R.string.comp_import_wcp), onClick = onImport)
|
||||
val st = compState(l)
|
||||
@@ -512,6 +761,21 @@ fun ComponentsPage(
|
||||
Column(Modifier.weight(1f)) { slide { k -> RowGroup(availableTitle(k)) { availableRows(k) } } }
|
||||
}
|
||||
Box(Modifier.padding(top = 14.dp)) { slide { k -> actions(k) } }
|
||||
if (l == "fex") {
|
||||
SettingsGroup(stringResource(R.string.fex_preset_title)) {
|
||||
SettingsRow(stringResource(R.string.fex_preset_title), null) {
|
||||
FexPresetChip(
|
||||
preset = generalFexPreset,
|
||||
inherited = false,
|
||||
open = fexMenu,
|
||||
enabled = true,
|
||||
onToggle = { fexMenu = !fexMenu },
|
||||
onDismiss = { fexMenu = false },
|
||||
onPick = { it?.let(onGeneralFexPreset) },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
if (l == PROTON_TAB) {
|
||||
Spacer(Modifier.height(10.dp))
|
||||
if (!protons.runtimeReady) EmptyLine(stringResource(R.string.content_needs_runtime))
|
||||
@@ -528,7 +792,10 @@ fun ComponentsPage(
|
||||
Box(Modifier.fillMaxSize().onGloballyPositioned { pageAt = it.positionInRoot() }.onFocusChanged { pageFocused = it.hasFocus }) {
|
||||
Column(
|
||||
Modifier.fillMaxSize().padding(horizontal = if (narrow) 16.dp else 22.dp, vertical = if (narrow) 12.dp else 18.dp)
|
||||
.bumpers(onPrevious = { pick(layerStep(layer, -1)) }, onNext = { pick(layerStep(layer, 1)) }),
|
||||
.then(if (selectedGame == null) Modifier.bumpers(
|
||||
onPrevious = { pick(layerStep(layer, -1)) },
|
||||
onNext = { pick(layerStep(layer, 1)) },
|
||||
) else Modifier),
|
||||
) {
|
||||
// ---- header: the title, the device, when the lists were checked and the one refresh ----
|
||||
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.fillMaxWidth()) {
|
||||
@@ -547,29 +814,109 @@ fun ComponentsPage(
|
||||
}
|
||||
if (narrow) Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(top = 6.dp)) { DeviceChip(gpu) }
|
||||
Spacer(Modifier.height(14.dp))
|
||||
Row(Modifier.weight(1f).fillMaxWidth()) {
|
||||
// ---- the stack ----
|
||||
Box(
|
||||
(if (narrow) Modifier.fillMaxWidth() else Modifier.width(250.dp)).fillMaxHeight()
|
||||
.onGloballyPositioned { stackAt = it.positionInRoot() },
|
||||
) {
|
||||
val tint = rememberUpdatedState(pal.signal)
|
||||
val local = cardsAt[layer]?.translate(-stackAt)
|
||||
ChipGlide(LAYERS.indexOf(layer), local, tint, GlideAxis.Vertical, corner = 12.dp)
|
||||
Stack(
|
||||
layer, view, gpu, focus = layerFocus, landed = landed, rings = rings,
|
||||
onPlaced = { l, r -> cardsAt[l] = r },
|
||||
onFocus = { l -> pick(l) },
|
||||
onOpen = { l ->
|
||||
pick(l)
|
||||
if (narrow) narrowOpen = l
|
||||
else runCatching { firstRow.requestFocus() }
|
||||
if (games.isNotEmpty()) {
|
||||
SettingsGroup(stringResource(R.string.comp_profile_configure)) {
|
||||
SettingsRow(
|
||||
stringResource(R.string.comp_profile),
|
||||
if (selectedGame == null) {
|
||||
stringResource(R.string.comp_scope_general_detail)
|
||||
} else {
|
||||
stringResource(R.string.comp_profile_game_detail, selectedGame.name)
|
||||
},
|
||||
)
|
||||
) {
|
||||
Box {
|
||||
ValueChip(
|
||||
selectedGame?.name ?: stringResource(R.string.comp_scope_general),
|
||||
scopeMenu,
|
||||
modifier = Modifier.widthIn(max = 320.dp).heightIn(min = 44.dp),
|
||||
) { scopeMenu = !scopeMenu }
|
||||
AnchoredMenu(
|
||||
scopeMenu,
|
||||
onDismiss = { scopeMenu = false },
|
||||
title = stringResource(R.string.comp_profile_configure),
|
||||
) { first ->
|
||||
MenuItem(
|
||||
stringResource(R.string.comp_scope_general),
|
||||
checked = selectedGame == null,
|
||||
detail = stringResource(R.string.comp_scope_general_detail),
|
||||
focusRequester = first,
|
||||
) {
|
||||
selectedGameKey = null
|
||||
scopeMenu = false
|
||||
}
|
||||
games.sortedBy { it.name.lowercase() }.forEach { game ->
|
||||
MenuItem(game.name, checked = selectedGameKey == game.profileKey) {
|
||||
selectedGameKey = game.profileKey
|
||||
scopeMenu = false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!narrow) {
|
||||
Spacer(Modifier.width(16.dp))
|
||||
Box(Modifier.weight(1f).fillMaxHeight()) { detail(layer, false) }
|
||||
}
|
||||
|
||||
if (selectedGame != null) {
|
||||
GameComponentOverrides(
|
||||
game = selectedGame,
|
||||
config = environment,
|
||||
generalFexPreset = generalFexPreset,
|
||||
generalProton = view?.proton,
|
||||
protons = views.map { it.proton },
|
||||
protonId = gameProtonId,
|
||||
protonChoice = gameProtonChoice,
|
||||
packages = snapshot?.packages.orEmpty(),
|
||||
componentChoices = gameComponents,
|
||||
componentMenu = gameComponentMenu,
|
||||
protonMenu = gameProtonMenu,
|
||||
fexMenu = fexMenu,
|
||||
busy = environmentBusy || profileLoading,
|
||||
error = environmentError,
|
||||
notice = profileNotice,
|
||||
winComponentsRevision = winComponentsRevision,
|
||||
onFexMenu = { fexMenu = it },
|
||||
onFexPreset = ::setGameFexPreset,
|
||||
onProtonMenu = { gameProtonMenu = it },
|
||||
onProton = ::setGameProton,
|
||||
onComponentMenu = { gameComponentMenu = it },
|
||||
onComponent = ::setGameComponent,
|
||||
onEnvironment = { environmentEditor = true },
|
||||
onWinComponents = { winComponentsOpen = false },
|
||||
onReset = {
|
||||
ask(
|
||||
ctx.getString(R.string.comp_game_reset_title, selectedGame.name),
|
||||
ctx.getString(R.string.comp_game_reset_body),
|
||||
R.string.comp_game_reset,
|
||||
::resetGameProfile,
|
||||
)
|
||||
},
|
||||
modifier = Modifier.weight(1f).fillMaxWidth(),
|
||||
)
|
||||
} else {
|
||||
Row(Modifier.weight(1f).fillMaxWidth()) {
|
||||
// ---- the stack ----
|
||||
Box(
|
||||
(if (narrow) Modifier.fillMaxWidth() else Modifier.width(250.dp)).fillMaxHeight()
|
||||
.onGloballyPositioned { stackAt = it.positionInRoot() },
|
||||
) {
|
||||
val tint = rememberUpdatedState(pal.signal)
|
||||
val local = cardsAt[layer]?.translate(-stackAt)
|
||||
ChipGlide(LAYERS.indexOf(layer), local, tint, GlideAxis.Vertical, corner = 12.dp)
|
||||
Stack(
|
||||
layer, view, gpu, focus = layerFocus, landed = landed, rings = rings,
|
||||
onPlaced = { l, r -> cardsAt[l] = r },
|
||||
onFocus = { l -> pick(l) },
|
||||
onOpen = { l ->
|
||||
pick(l)
|
||||
if (narrow) narrowOpen = l
|
||||
else runCatching { firstRow.requestFocus() }
|
||||
},
|
||||
)
|
||||
}
|
||||
if (!narrow) {
|
||||
Spacer(Modifier.width(16.dp))
|
||||
Box(Modifier.weight(1f).fillMaxHeight()) { detail(layer, false) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -614,6 +961,50 @@ fun ComponentsPage(
|
||||
if (from == null) body() else PageFlood(from, driverLeaving) { body() }
|
||||
}
|
||||
}
|
||||
confirm?.let { (body, action) ->
|
||||
AlertDialog(
|
||||
onDismissRequest = { confirm = null },
|
||||
title = { Text(confirmTitle) },
|
||||
text = { Text(body, fontSize = 14.sp) },
|
||||
// Opens on Cancel, so a stray A press on a controller never swaps or deletes anything.
|
||||
confirmButton = {
|
||||
val del = confirmVerb == R.string.common_delete || confirmVerb == R.string.comp_game_reset
|
||||
FocusText(stringResource(confirmVerb), if (del) colors.error else pal.signal) { confirm = null; action() }
|
||||
},
|
||||
dismissButton = {
|
||||
val cancelFocus = remember { FocusRequester() }
|
||||
LaunchedEffect(Unit) { runCatching { cancelFocus.requestFocus() } }
|
||||
FocusText(stringResource(R.string.common_cancel), colors.onBackground, modifier = Modifier.focusRequester(cancelFocus)) { confirm = null }
|
||||
},
|
||||
)
|
||||
}
|
||||
if (environmentEditor && selectedGame != null) {
|
||||
GameEnvironmentEditor(
|
||||
byPad = androidx.compose.ui.platform.LocalInputModeManager.current.inputMode == androidx.compose.ui.input.InputMode.Keyboard,
|
||||
initialScope = selectedGame.profileKey,
|
||||
) {
|
||||
environmentEditor = false
|
||||
coroutine.launch {
|
||||
runCatching { withContext(Dispatchers.IO) { GameEnvironmentStore.read(ctx) } }
|
||||
.onSuccess { environment = it; environmentError = false }
|
||||
.onFailure { environmentError = true }
|
||||
}
|
||||
}
|
||||
}
|
||||
val winOpen = winComponentsOpen
|
||||
if (winOpen != null && selectedGame != null) {
|
||||
WinComponentsDialog(
|
||||
selectedGame.profileKey,
|
||||
selectedGame.name,
|
||||
selectedGame.gameFiles,
|
||||
winOpen,
|
||||
compat = selectedGame.protonPrefix,
|
||||
steamAppId = selectedGame.appId.takeIf { selectedGame.library != Library.ADDED },
|
||||
) {
|
||||
winComponentsOpen = null
|
||||
winComponentsRevision++
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** The Installed rows of one component layer for the Proton the page shows. */
|
||||
@@ -776,6 +1167,253 @@ private fun EmptyLine(text: String) {
|
||||
Text(text, fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(horizontal = 14.dp, vertical = 12.dp))
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun GameComponentOverrides(
|
||||
game: Library.SteamGame,
|
||||
config: GameEnvironment.Config?,
|
||||
generalFexPreset: String,
|
||||
generalProton: ComponentsManager.Proton?,
|
||||
protons: List<ComponentsManager.Proton>,
|
||||
protonId: String?,
|
||||
protonChoice: ProtonDefault.GameChoice?,
|
||||
packages: List<ComponentsManager.Package>,
|
||||
componentChoices: Map<String, String>,
|
||||
componentMenu: String?,
|
||||
protonMenu: Boolean,
|
||||
fexMenu: Boolean,
|
||||
busy: Boolean,
|
||||
error: Boolean,
|
||||
notice: String?,
|
||||
winComponentsRevision: Int,
|
||||
onFexMenu: (Boolean) -> Unit,
|
||||
onFexPreset: (String?) -> Unit,
|
||||
onProtonMenu: (Boolean) -> Unit,
|
||||
onProton: (String?) -> Unit,
|
||||
onComponentMenu: (String?) -> Unit,
|
||||
onComponent: (String, String?) -> Unit,
|
||||
onEnvironment: () -> Unit,
|
||||
onWinComponents: () -> Unit,
|
||||
onReset: () -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
val override = config?.let { GameEnvironment.gameFexPreset(it, game.profileKey) }
|
||||
val proton = protons.firstOrNull { it.id == protonId }
|
||||
val effectiveProton = if (protonChoice == null) generalProton else proton
|
||||
val picks = remember(game.profileKey, winComponentsRevision) { WinComponents.picks(context, game.profileKey) }
|
||||
Column(
|
||||
verticalArrangement = Arrangement.spacedBy(14.dp),
|
||||
modifier = modifier.verticalScroll(rememberScrollState()).padding(top = 14.dp, bottom = 16.dp),
|
||||
) {
|
||||
Text(
|
||||
stringResource(R.string.comp_game_hint),
|
||||
fontSize = 13.sp,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
SettingsGroup(stringResource(R.string.fex_preset_title)) {
|
||||
SettingsRow(
|
||||
stringResource(R.string.comp_game_fex),
|
||||
stringResource(if (override == null) R.string.comp_game_fex_inherited else R.string.comp_game_fex_override),
|
||||
) {
|
||||
FexPresetChip(
|
||||
preset = override ?: generalFexPreset,
|
||||
inherited = override == null,
|
||||
open = fexMenu,
|
||||
enabled = config != null && !busy,
|
||||
allowInheritance = true,
|
||||
onToggle = { onFexMenu(!fexMenu) },
|
||||
onDismiss = { onFexMenu(false) },
|
||||
onPick = onFexPreset,
|
||||
)
|
||||
}
|
||||
GamePackageRow(
|
||||
comp = "fex",
|
||||
packages = packages,
|
||||
selectedFile = componentChoices["fex"],
|
||||
open = componentMenu == "fex",
|
||||
busy = busy,
|
||||
onMenu = onComponentMenu,
|
||||
onPick = onComponent,
|
||||
)
|
||||
}
|
||||
SettingsGroup(stringResource(R.string.comp_game_compatibility)) {
|
||||
SettingsRow(
|
||||
stringResource(R.string.comp_proton),
|
||||
stringResource(if (protonChoice == null) R.string.comp_game_proton_inherited else R.string.comp_game_proton_override),
|
||||
) {
|
||||
Box {
|
||||
ValueChip(
|
||||
proton?.name ?: protonChoice?.dir ?: stringResource(R.string.comp_game_use_general),
|
||||
protonMenu,
|
||||
enabled = protons.isNotEmpty() && !busy,
|
||||
modifier = Modifier.widthIn(max = 280.dp),
|
||||
) { onProtonMenu(!protonMenu) }
|
||||
AnchoredMenu(
|
||||
protonMenu,
|
||||
onDismiss = { onProtonMenu(false) },
|
||||
title = stringResource(R.string.comp_proton),
|
||||
) { first ->
|
||||
MenuItem(
|
||||
stringResource(R.string.comp_game_use_general),
|
||||
checked = protonChoice == null,
|
||||
focusRequester = first,
|
||||
) { onProton(null); onProtonMenu(false) }
|
||||
protons.forEach { option ->
|
||||
MenuItem(option.name, checked = proton?.id == option.id) {
|
||||
onProton(option.id)
|
||||
onProtonMenu(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
GamePackageRow(
|
||||
comp = "dxvk",
|
||||
packages = packages,
|
||||
selectedFile = componentChoices["dxvk"],
|
||||
open = componentMenu == "dxvk",
|
||||
busy = busy,
|
||||
proton = effectiveProton,
|
||||
onMenu = onComponentMenu,
|
||||
onPick = onComponent,
|
||||
onRuntimeOptions = onEnvironment,
|
||||
)
|
||||
GamePackageRow(
|
||||
comp = "vkd3d",
|
||||
packages = packages,
|
||||
selectedFile = componentChoices["vkd3d"],
|
||||
open = componentMenu == "vkd3d",
|
||||
busy = busy,
|
||||
proton = effectiveProton,
|
||||
onMenu = onComponentMenu,
|
||||
onPick = onComponent,
|
||||
onRuntimeOptions = onEnvironment,
|
||||
)
|
||||
SettingsRow(
|
||||
stringResource(R.string.game_env_title),
|
||||
stringResource(R.string.comp_game_environment_other_hint),
|
||||
) {
|
||||
SecondaryButton(stringResource(R.string.game_env_edit), enabled = !busy, onClick = onEnvironment)
|
||||
}
|
||||
SettingsRow(
|
||||
stringResource(R.string.wincomp_title),
|
||||
if (picks.isEmpty()) stringResource(R.string.wincomp_card_none)
|
||||
else picks.joinToString(", ") { com.droiddeck.launcher.session.WinComponentNames.of(it) },
|
||||
) {
|
||||
SecondaryButton(stringResource(R.string.game_env_edit), onClick = onWinComponents)
|
||||
}
|
||||
}
|
||||
notice?.let {
|
||||
Text(
|
||||
it,
|
||||
fontSize = 13.sp,
|
||||
color = if (error) MaterialTheme.colorScheme.error else LocalPalette.current.good,
|
||||
)
|
||||
}
|
||||
if (error && notice == null) Text(stringResource(R.string.game_env_error), fontSize = 13.sp, color = MaterialTheme.colorScheme.error)
|
||||
if (!busy) {
|
||||
FocusText(
|
||||
stringResource(R.string.comp_game_reset),
|
||||
MaterialTheme.colorScheme.error,
|
||||
onClick = onReset,
|
||||
)
|
||||
}
|
||||
if (busy) LinearProgressIndicator(Modifier.fillMaxWidth())
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun GamePackageRow(
|
||||
comp: String,
|
||||
packages: List<ComponentsManager.Package>,
|
||||
selectedFile: String?,
|
||||
open: Boolean,
|
||||
busy: Boolean,
|
||||
proton: ComponentsManager.Proton? = null,
|
||||
onMenu: (String?) -> Unit,
|
||||
onPick: (String, String?) -> Unit,
|
||||
onRuntimeOptions: (() -> Unit)? = null,
|
||||
) {
|
||||
val choices = packages.filter { it.comp == comp }
|
||||
val selected = choices.firstOrNull { it.file == selectedFile }
|
||||
val title = ComponentsManager.LABEL[comp] ?: comp
|
||||
SettingsRow(
|
||||
title,
|
||||
if (selected == null) {
|
||||
if (proton == null) stringResource(R.string.comp_game_component_general)
|
||||
else stringResource(R.string.comp_game_component_runtime, proton.name)
|
||||
} else stringResource(R.string.comp_game_component_override, selected.version),
|
||||
) {
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
Box {
|
||||
ValueChip(
|
||||
selected?.version ?: stringResource(R.string.comp_game_use_general),
|
||||
open,
|
||||
enabled = !busy,
|
||||
modifier = Modifier.widthIn(max = 240.dp),
|
||||
) { onMenu(if (open) null else comp) }
|
||||
AnchoredMenu(open, onDismiss = { onMenu(null) }, title = title) { first ->
|
||||
MenuItem(
|
||||
stringResource(R.string.comp_game_use_general),
|
||||
checked = selected == null,
|
||||
focusRequester = first,
|
||||
) { onPick(comp, null); onMenu(null) }
|
||||
choices.forEach { option ->
|
||||
MenuItem(option.version, checked = option.file == selectedFile, detail = option.description) {
|
||||
onPick(comp, option.file)
|
||||
onMenu(null)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (onRuntimeOptions != null) {
|
||||
SecondaryButton(stringResource(R.string.comp_game_runtime_options), enabled = !busy, onClick = onRuntimeOptions)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun FexPresetChip(
|
||||
preset: String,
|
||||
inherited: Boolean,
|
||||
open: Boolean,
|
||||
enabled: Boolean,
|
||||
onToggle: () -> Unit,
|
||||
onDismiss: () -> Unit,
|
||||
onPick: (String?) -> Unit,
|
||||
allowInheritance: Boolean = false,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
val chosen = FexPreset.all.firstOrNull { it.id == preset }
|
||||
val label = when {
|
||||
preset == GameEnvironment.CUSTOM_FEX_PRESET -> stringResource(R.string.comp_game_fex_custom)
|
||||
chosen == null -> stringResource(FexPreset.byId("").label)
|
||||
inherited -> stringResource(R.string.comp_game_use_general)
|
||||
else -> stringResource(chosen.label)
|
||||
}
|
||||
Box {
|
||||
ValueChip(label, open, enabled = enabled, modifier = modifier.widthIn(max = 260.dp), onClick = onToggle)
|
||||
AnchoredMenu(open && enabled, onDismiss = onDismiss, title = stringResource(R.string.fex_preset_title)) { first ->
|
||||
if (allowInheritance) {
|
||||
MenuItem(
|
||||
stringResource(R.string.comp_game_use_general),
|
||||
checked = inherited,
|
||||
focusRequester = first,
|
||||
) { onPick(null); onDismiss() }
|
||||
}
|
||||
FexPreset.all.forEachIndexed { index, option ->
|
||||
MenuItem(
|
||||
stringResource(option.label),
|
||||
checked = !inherited && option.id == preset,
|
||||
detail = stringResource(option.detail),
|
||||
focusRequester = if (index == 0 && !allowInheritance) first else null,
|
||||
) { onPick(option.id); onDismiss() }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun ToolIcon(icon: ImageVector, description: String, busy: Boolean = false, enabled: Boolean = true, onClick: () -> Unit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
@@ -908,7 +1546,7 @@ private fun ChoiceLine(
|
||||
@Composable
|
||||
private fun GetLine(
|
||||
name: String, detail: String, progress: Int?, enabled: Boolean,
|
||||
badge: String? = null, stage: String? = null, onCancel: (() -> Unit)? = null, onGet: () -> Unit,
|
||||
badge: String? = null, stage: String? = null, onCancel: (() -> Unit)? = null, action: String? = null, onGet: () -> Unit,
|
||||
) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
@@ -923,7 +1561,7 @@ private fun GetLine(
|
||||
if (progress != null) ProgressBit(progress)
|
||||
else {
|
||||
if (onCancel != null) FocusText(stringResource(R.string.proton_cancel_queued), pal.signal, onClick = onCancel)
|
||||
SmallButton(stringResource(R.string.comp_get), enabled = enabled, accent = true, onClick = onGet)
|
||||
SmallButton(action ?: stringResource(R.string.comp_get), enabled = enabled, accent = true, onClick = onGet)
|
||||
}
|
||||
}
|
||||
Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line))
|
||||
@@ -1014,8 +1652,17 @@ class ProtonsState(
|
||||
class ProtonsActions(
|
||||
val onInstall: (String) -> Unit = {},
|
||||
val onCancel: (String) -> Unit = {},
|
||||
val onRemove: (String) -> Unit = {},
|
||||
/** The source's id and the installed folder to delete. */
|
||||
val onRemove: (String, String) -> Unit = { _, _ -> },
|
||||
/** Deletes every build of the source but the newest. */
|
||||
val onRemoveOlder: (String) -> Unit = {},
|
||||
)
|
||||
|
||||
/** A Proton DroidDeck can install, and the folder it is installed as (null when it is not). */
|
||||
class ProtonRow(val id: String, val name: String, val installed: String?, val queued: Boolean)
|
||||
/**
|
||||
* A Proton DroidDeck can install: the folder its newest build is installed as (null when it is
|
||||
* not), every installed build oldest first, and a newer release's tag when one is out.
|
||||
*/
|
||||
class ProtonRow(
|
||||
val id: String, val name: String, val installed: String?, val queued: Boolean,
|
||||
val installedAll: List<String> = listOfNotNull(installed), val update: String? = null,
|
||||
)
|
||||
@@ -478,10 +478,7 @@ internal fun LaunchSettings(s: FrontEndState, a: FrontEndActions, host: MenuHost
|
||||
val inputMode = androidx.compose.ui.platform.LocalInputModeManager.current
|
||||
// The game's prefix is compatdata/<id>, as droiddeck-game-env reads it: a Steam title's appid, an
|
||||
// added game's shortcut appid (unsigned). Recommended scans the game's own folder either way.
|
||||
val wincompKey = game?.let {
|
||||
if (it.library == com.droiddeck.launcher.frontend.Library.ADDED) Integer.toUnsignedString(it.appId)
|
||||
else it.appId.takeIf { id -> id > 0 }?.toString()
|
||||
}
|
||||
val wincompKey = game?.takeIf { it.library == com.droiddeck.launcher.frontend.Library.ADDED || it.appId > 0 }?.profileKey
|
||||
var wincompOpen by remember(wincompKey) { mutableStateOf<Boolean?>(null) }
|
||||
val wincompPicks = remember(wincompKey, wincompOpen) { wincompKey?.let { com.droiddeck.launcher.session.WinComponents.picks(context, it) }.orEmpty() }
|
||||
val cards = buildList<@Composable (Modifier) -> Unit> {
|
||||
|
||||
@@ -52,7 +52,11 @@ import kotlinx.coroutines.withContext
|
||||
// dialog, with each variable's actions in a menu off its value as everywhere else.
|
||||
|
||||
@Composable
|
||||
fun GameEnvironmentRow(modifier: Modifier = Modifier, showHint: Boolean = true) {
|
||||
fun GameEnvironmentRow(
|
||||
modifier: Modifier = Modifier,
|
||||
showHint: Boolean = true,
|
||||
initialScope: String = "",
|
||||
) {
|
||||
var open by remember { mutableStateOf(false) }
|
||||
// Opened with a pad, the editor starts with focus in it; the dialog is a window of its own and
|
||||
// would otherwise give the pad nothing to move from.
|
||||
@@ -64,7 +68,7 @@ fun GameEnvironmentRow(modifier: Modifier = Modifier, showHint: Boolean = true)
|
||||
open = true
|
||||
}
|
||||
}
|
||||
if (open) GameEnvironmentEditor(byPad) { open = false }
|
||||
if (open) GameEnvironmentEditor(byPad, initialScope) { open = false }
|
||||
}
|
||||
|
||||
/** With a pad driving, focus [target] once the dialog is laid out, and keep the dialog in pad mode. */
|
||||
@@ -81,19 +85,19 @@ internal fun PadFocus(byPad: Boolean, target: FocusRequester) {
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun GameEnvironmentEditor(byPad: Boolean, onClose: () -> Unit) {
|
||||
internal fun GameEnvironmentEditor(byPad: Boolean, initialScope: String = "", onClose: () -> Unit) {
|
||||
val context = LocalContext.current
|
||||
val coroutine = rememberCoroutineScope()
|
||||
val shown = rememberShown(onClose)
|
||||
val close = { shown.targetState = false }
|
||||
var config by remember { mutableStateOf<GameEnvironment.Config?>(null) }
|
||||
var games by remember { mutableStateOf(emptyList<Pair<String, String>>()) }
|
||||
var scope by remember { mutableStateOf("") }
|
||||
var scope by remember { mutableStateOf(initialScope) }
|
||||
var otherId by remember { mutableStateOf<String?>(null) }
|
||||
var menu by remember { mutableStateOf<String?>(null) }
|
||||
var busy by remember { mutableStateOf(false) }
|
||||
var error by remember { mutableStateOf(false) }
|
||||
var editing by remember { mutableStateOf<Pair<String, String>?>(null) }
|
||||
var editing by remember { mutableStateOf<EnvironmentVariableEdit?>(null) }
|
||||
val preset = SessionPrefs.fexPreset(context)
|
||||
val forceSsbs = SessionPrefs.forceSsbs(context)
|
||||
val firstFocus = remember { FocusRequester() }
|
||||
@@ -168,7 +172,7 @@ private fun GameEnvironmentEditor(byPad: Boolean, onClose: () -> Unit) {
|
||||
VariableRow(
|
||||
name, value, inherited = !own.containsKey(name), open = menu == "var:$name", enabled = !busy,
|
||||
onToggle = { menu = if (menu == "var:$name") null else "var:$name" }, onDismiss = { if (menu == "var:$name") menu = null },
|
||||
onEdit = { menu = null; editByPad = dialogInput.inputMode == InputMode.Keyboard; editing = name to (value ?: "") },
|
||||
onEdit = { menu = null; editByPad = dialogInput.inputMode == InputMode.Keyboard; editing = EnvironmentVariableEdit(scope, profileName, name, value ?: "") },
|
||||
// A value set here or inherited can be switched off for this profile; one set here can go back to inheriting.
|
||||
onUnset = if (value != null) ({ menu = null; save(current.withEntries(scope, own + (name to null))) }) else null,
|
||||
onRestore = if (own.containsKey(name)) ({ menu = null; save(current.withEntries(scope, own - name)) }) else null,
|
||||
@@ -185,9 +189,9 @@ private fun GameEnvironmentEditor(byPad: Boolean, onClose: () -> Unit) {
|
||||
SecondaryButton(stringResource(R.string.game_env_add), enabled = !busy) { menu = if (menu == "add") null else "add" }
|
||||
AnchoredMenu(menu == "add", onDismiss = { if (menu == "add") menu = null }, title = stringResource(R.string.game_env_add)) { first ->
|
||||
for ((i, option) in GameEnvironmentOptions.all.withIndex()) MenuItem(option.name, checked = false, focusRequester = if (i == 0) first else null) {
|
||||
menu = null; editByPad = dialogInput.inputMode == InputMode.Keyboard; editing = option.name to option.value
|
||||
menu = null; editByPad = dialogInput.inputMode == InputMode.Keyboard; editing = EnvironmentVariableEdit(scope, profileName, option.name, option.value)
|
||||
}
|
||||
MenuItem(stringResource(R.string.game_env_custom), checked = false) { menu = null; editByPad = dialogInput.inputMode == InputMode.Keyboard; editing = "" to "" }
|
||||
MenuItem(stringResource(R.string.game_env_custom), checked = false) { menu = null; editByPad = dialogInput.inputMode == InputMode.Keyboard; editing = EnvironmentVariableEdit(scope, profileName, "", "") }
|
||||
}
|
||||
}
|
||||
if (current != null && current.entries(scope).isNotEmpty()) FocusText(stringResource(R.string.game_env_reset), LocalPalette.current.signal) {
|
||||
@@ -197,19 +201,21 @@ private fun GameEnvironmentEditor(byPad: Boolean, onClose: () -> Unit) {
|
||||
PrimaryButton(stringResource(R.string.game_env_done), enabled = !busy, onClick = close)
|
||||
}
|
||||
}
|
||||
editing?.let { (name, value) ->
|
||||
VariableDialog(name, value, profileName, editByPad, onDismiss = { editing = null }) { key, content ->
|
||||
editing?.let { edit ->
|
||||
VariableDialog(edit.name, edit.value, edit.profileName, editByPad, onDismiss = { editing = null }) { key, content ->
|
||||
config?.let {
|
||||
val entries = it.entries(scope).toMutableMap()
|
||||
if (name.isNotEmpty() && name != key) entries[name] = null
|
||||
val entries = it.entries(edit.scope).toMutableMap()
|
||||
if (edit.name.isNotEmpty() && edit.name != key) entries[edit.name] = null
|
||||
entries[key] = content
|
||||
save(it.withEntries(scope, entries))
|
||||
save(it.withEntries(edit.scope, entries))
|
||||
}
|
||||
editing = null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private data class EnvironmentVariableEdit(val scope: String, val profileName: String, val name: String, val value: String)
|
||||
|
||||
/** The panel the profile and the variables sit in, as a settings group does. */
|
||||
@Composable
|
||||
private fun Panel(content: @Composable androidx.compose.foundation.layout.ColumnScope.() -> Unit) =
|
||||
|
||||
@@ -18,6 +18,7 @@ import androidx.compose.ui.input.key.type
|
||||
import androidx.compose.ui.layout.LayoutCoordinates
|
||||
import androidx.compose.ui.layout.onSizeChanged
|
||||
import androidx.compose.ui.platform.LocalDensity
|
||||
import androidx.compose.ui.res.pluralStringResource
|
||||
import androidx.compose.ui.unit.IntOffset
|
||||
import androidx.compose.ui.unit.IntSize
|
||||
import kotlin.math.roundToInt
|
||||
@@ -88,6 +89,9 @@ import com.droiddeck.launcher.HomeApp
|
||||
import androidx.compose.animation.AnimatedVisibility
|
||||
import androidx.compose.animation.animateColorAsState
|
||||
import androidx.compose.animation.core.Spring
|
||||
import com.droiddeck.launcher.core.GameEnvironment
|
||||
import com.droiddeck.launcher.session.ProfileValue
|
||||
import com.droiddeck.launcher.session.SelectedGameProfile
|
||||
import androidx.compose.animation.core.animateFloatAsState
|
||||
import androidx.compose.ui.draw.rotate
|
||||
import androidx.compose.ui.semantics.stateDescription
|
||||
@@ -205,8 +209,8 @@ class DrawerActions(
|
||||
/** The compositor's post chain (gpu/ScreenEffects), changed live. */
|
||||
val effects: ScreenEffects = ScreenEffects.OFF,
|
||||
/** Texture filtering for DirectX 9-11 games (core/TextureFiltering); lands on their next launch. */
|
||||
val textureAnisotropy: Int = 0,
|
||||
val textureLodBias: String = TextureFiltering.LOD_BIAS_OFF,
|
||||
val textureAnisotropy: Int? = 0,
|
||||
val textureLodBias: String? = TextureFiltering.LOD_BIAS_OFF,
|
||||
val secondScreenMode: SecondScreenMode,
|
||||
val secondScreenDisplays: List<SecondScreenDisplay>,
|
||||
val selectedSecondScreenDisplay: Int,
|
||||
@@ -235,8 +239,8 @@ class DrawerActions(
|
||||
val onUpscaler: (Int) -> Unit = {},
|
||||
val onUpscaleSharpness: (Int) -> Unit = {},
|
||||
val onEffects: (ScreenEffects) -> Unit = {},
|
||||
val onTextureAnisotropy: (Int) -> Unit = {},
|
||||
val onTextureLodBias: (String) -> Unit = {},
|
||||
val onTextureAnisotropy: (Int?) -> Unit = {},
|
||||
val onTextureLodBias: (String?) -> Unit = {},
|
||||
val onSecondScreenMode: (SecondScreenMode) -> Unit,
|
||||
val onSecondScreenDisplay: (Int) -> Unit,
|
||||
val onLaunchAndroidApp: (HomeApp.LaunchableApp, Int?) -> Unit,
|
||||
@@ -257,8 +261,22 @@ class DrawerActions(
|
||||
val components: ComponentsManager.Snapshot? = null,
|
||||
/** Re-reads the Protons (and runs swaps that waited for a game to close). */
|
||||
val onComponentsRefresh: () -> Unit = {},
|
||||
/** Installed games available for profile inspection in the session drawer. */
|
||||
val gameProfiles: List<Pair<Long, String>> = emptyList(),
|
||||
/** The selected game profile, or null for the Default profile. */
|
||||
val selectedGameProfileId: Long? = null,
|
||||
val selectedGameProfile: SelectedGameProfile? = null,
|
||||
val gameProfilesLoaded: Boolean = false,
|
||||
val gameProfileRefreshFailed: Boolean = false,
|
||||
val onSelectedGameProfile: (Long?) -> Unit = {},
|
||||
val onGameProfilesPageOpened: () -> Unit = {},
|
||||
val onSelectedGameProfileRefresh: () -> Unit = {},
|
||||
val gameFexPresetSaving: Boolean = false,
|
||||
val onGameFexPreset: (Long, String?) -> Unit = { _, _ -> },
|
||||
/** Swaps [value] ("orig:<build>" or a stored package file) into a Proton's component. */
|
||||
val onComponentSwap: (protonId: String, comp: String, value: String) -> Unit = { _, _, _ -> },
|
||||
/** Saves a stored package for a game, or null to inherit that component from the Default profile. */
|
||||
val onGameComponent: (appId: Long, comp: String, file: String?) -> Unit = { _, _, _ -> },
|
||||
)
|
||||
|
||||
@OptIn(ExperimentalComposeUiApi::class)
|
||||
@@ -286,7 +304,19 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
|
||||
}
|
||||
BackHandler(enabled = open && confirmStop) { confirmStop = false }
|
||||
LaunchedEffect(page) { host.open = null; appToChooseDisplay = null }
|
||||
LaunchedEffect(open, page) { if (open && page == SessionDrawerPage.GAMES) a.onComponentsRefresh() }
|
||||
LaunchedEffect(a.selectedGameProfileId) {
|
||||
if (host.open == "fex") host.open = null
|
||||
}
|
||||
LaunchedEffect(open, page) {
|
||||
if (open && page == SessionDrawerPage.GAMES) {
|
||||
a.onGameProfilesPageOpened()
|
||||
a.onComponentsRefresh()
|
||||
while (true) {
|
||||
a.onSelectedGameProfileRefresh()
|
||||
delay(1_000)
|
||||
}
|
||||
}
|
||||
}
|
||||
LaunchedEffect(open, controllerActive) {
|
||||
if (open && !controllerActive) focusManager.clearFocus(force = true)
|
||||
}
|
||||
@@ -479,14 +509,17 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
|
||||
SecondScreenGroup(host, a) { key -> focus.track(page, key) }
|
||||
}
|
||||
SessionDrawerPage.GAMES -> {
|
||||
if (a.steam) SelectedGameProfileGroup(host, a) { key -> focus.track(page, key) }
|
||||
Text(stringResource(R.string.fex_next_launch), fontSize = 12.sp,
|
||||
color = colors.onSurfaceVariant, modifier = Modifier.padding(horizontal = 14.dp, vertical = 8.dp))
|
||||
TextureFilteringGroup(host, a) { key -> focus.track(page, key) }
|
||||
if (a.steam) SettingsGroup(stringResource(R.string.game_settings_title)) {
|
||||
ChoiceRow(host, "fex", stringResource(R.string.fex_preset_title), null,
|
||||
FexPreset.all.map { it.id to stringResource(it.label) }, a.fexPreset,
|
||||
chipModifier = focus.track(page, "fex"), onPick = a.onFexPreset)
|
||||
GameEnvironmentRow(modifier = focus.track(page, "game-env"), showHint = false)
|
||||
DrawerFexPresetRow(host, a, focus.track(page, "fex"))
|
||||
GameEnvironmentRow(
|
||||
modifier = focus.track(page, "game-env"),
|
||||
showHint = false,
|
||||
initialScope = a.selectedGameProfileId?.toString().orEmpty(),
|
||||
)
|
||||
}
|
||||
ComponentsDrawerPage(host, a) { key -> focus.track(page, key) }
|
||||
}
|
||||
@@ -874,20 +907,187 @@ private fun SecondScreenGroup(host: MenuHost, a: DrawerActions, track: (String)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun DrawerFexPresetRow(host: MenuHost, a: DrawerActions, modifier: Modifier) {
|
||||
val appId = a.selectedGameProfileId
|
||||
val profile = a.selectedGameProfile?.takeIf { it.appId == appId }
|
||||
val inherited = profile?.fexPreset?.inherited == true
|
||||
val hint = if (profile == null) null else stringResource(
|
||||
if (inherited) R.string.comp_game_fex_inherited else R.string.comp_game_fex_override,
|
||||
)
|
||||
SettingsRow(stringResource(R.string.fex_preset_title), hint, highlighted = host.open == "fex") {
|
||||
if (appId != null && profile == null) {
|
||||
ValueChip("-", false, enabled = false, modifier = modifier) {}
|
||||
} else {
|
||||
FexPresetChip(
|
||||
preset = profile?.fexPreset?.value ?: a.fexPreset,
|
||||
inherited = inherited,
|
||||
open = host.open == "fex",
|
||||
enabled = !a.gameFexPresetSaving,
|
||||
onToggle = { host.open = if (host.open == "fex") null else "fex" },
|
||||
onDismiss = { if (host.open == "fex") host.open = null },
|
||||
onPick = { preset ->
|
||||
if (appId == null) {
|
||||
preset?.let(a.onFexPreset)
|
||||
} else {
|
||||
a.onGameFexPreset(appId, preset)
|
||||
}
|
||||
},
|
||||
allowInheritance = appId != null,
|
||||
modifier = modifier,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Texture filtering on the Games page: DXVK options for the next DirectX 9-11 launch. */
|
||||
@Composable
|
||||
private fun TextureFilteringGroup(host: MenuHost, a: DrawerActions, track: (String) -> Modifier) {
|
||||
val inherited = a.selectedGameProfileId != null
|
||||
val anisotropyChoices: List<Pair<Int?, String>> =
|
||||
(if (inherited) listOf(null to stringResource(R.string.comp_game_use_general)) else emptyList()) +
|
||||
SessionPrefs.textureAnisotropyChoices(LocalContext.current).map { (value, label) -> value as Int? to label }
|
||||
val lodBiasChoices: List<Pair<String?, String>> =
|
||||
(if (inherited) listOf(null to stringResource(R.string.comp_game_use_general)) else emptyList()) +
|
||||
SessionPrefs.textureLodBiasChoices(LocalContext.current).map { (value, label) -> value as String? to label }
|
||||
SettingsGroup(stringResource(R.string.drawer_texture)) {
|
||||
ChoiceRow(host, "anisotropy", stringResource(R.string.drawer_anisotropy), null,
|
||||
SessionPrefs.textureAnisotropyChoices(LocalContext.current), a.textureAnisotropy, chipModifier = track("anisotropy"), onPick = a.onTextureAnisotropy)
|
||||
anisotropyChoices, a.textureAnisotropy, chipModifier = track("anisotropy"), onPick = a.onTextureAnisotropy)
|
||||
ChoiceRow(host, "texture-sharpness", stringResource(R.string.drawer_texture_sharpness), null,
|
||||
SessionPrefs.textureLodBiasChoices(LocalContext.current), a.textureLodBias, note = stringResource(R.string.drawer_texture_sharpness_note),
|
||||
lodBiasChoices, a.textureLodBias, note = stringResource(R.string.drawer_texture_sharpness_note),
|
||||
chipModifier = track("texture-sharpness"), onPick = a.onTextureLodBias)
|
||||
}
|
||||
}
|
||||
|
||||
private fun signed(v: Int) = if (v > 0) "+$v" else "$v"
|
||||
|
||||
@Composable
|
||||
private fun SelectedGameProfileGroup(host: MenuHost, a: DrawerActions, track: (String) -> Modifier) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val options: List<Pair<Long?, String>> = listOf(null to stringResource(R.string.comp_scope_general)) +
|
||||
a.gameProfiles.map { (id, name) -> Pair(id, name) }
|
||||
val profile = a.selectedGameProfile
|
||||
SettingsGroup(stringResource(R.string.drawer_selected_profile)) {
|
||||
DrawerStackedChoice(
|
||||
host = host,
|
||||
key = "game-profile",
|
||||
label = stringResource(R.string.comp_profile),
|
||||
hint = if (a.selectedGameProfileId == null) stringResource(R.string.comp_scope_general_detail)
|
||||
else stringResource(R.string.drawer_profile_inspect_hint),
|
||||
options = options,
|
||||
selected = a.selectedGameProfileId,
|
||||
chipModifier = track("game-profile"),
|
||||
onPick = a.onSelectedGameProfile,
|
||||
)
|
||||
if (a.gameProfileRefreshFailed) {
|
||||
Text(
|
||||
stringResource(
|
||||
if (a.gameProfilesLoaded) {
|
||||
R.string.drawer_profile_refresh_failed_stale
|
||||
} else {
|
||||
R.string.drawer_profile_refresh_failed_initial
|
||||
},
|
||||
),
|
||||
fontSize = 13.sp,
|
||||
color = colors.error,
|
||||
modifier = Modifier.padding(horizontal = 14.dp, vertical = 8.dp),
|
||||
)
|
||||
}
|
||||
if (a.selectedGameProfileId == null) return@SettingsGroup
|
||||
if (profile == null) {
|
||||
if (!a.gameProfileRefreshFailed) Text(
|
||||
stringResource(R.string.drawer_selected_profile_none),
|
||||
fontSize = 13.sp,
|
||||
color = colors.onSurfaceVariant,
|
||||
modifier = Modifier.padding(14.dp),
|
||||
)
|
||||
return@SettingsGroup
|
||||
}
|
||||
val hasOverrides = profile.hasOverrides ||
|
||||
a.textureAnisotropy != null ||
|
||||
a.textureLodBias != null
|
||||
Column(modifier = Modifier.fillMaxWidth().padding(horizontal = 14.dp, vertical = 11.dp)) {
|
||||
Text(
|
||||
stringResource(
|
||||
if (hasOverrides) R.string.drawer_profile_custom
|
||||
else R.string.drawer_profile_default,
|
||||
),
|
||||
fontSize = 12.sp,
|
||||
color = colors.onSurfaceVariant,
|
||||
modifier = Modifier.padding(bottom = if (hasOverrides) 5.dp else 0.dp),
|
||||
)
|
||||
if (!profile.fexPreset.inherited) {
|
||||
ProfileSummaryRow(stringResource(R.string.comp_game_fex), fexProfileLabel(profile.fexPreset))
|
||||
}
|
||||
if (!profile.proton.inherited) {
|
||||
ProfileSummaryRow(stringResource(R.string.comp_proton), profileValueLabel(profile.proton))
|
||||
}
|
||||
for (component in ComponentsManager.COMPONENTS) {
|
||||
val value = profile.components.getValue(component)
|
||||
if (!value.inherited) {
|
||||
ProfileSummaryRow(ComponentsManager.LABEL.getValue(component), profileValueLabel(value))
|
||||
}
|
||||
}
|
||||
if (profile.environmentOverrides > 0) {
|
||||
ProfileSummaryRow(
|
||||
stringResource(R.string.game_env_title),
|
||||
pluralStringResource(
|
||||
R.plurals.drawer_profile_environment_overrides,
|
||||
profile.environmentOverrides,
|
||||
profile.environmentOverrides,
|
||||
),
|
||||
)
|
||||
}
|
||||
if (profile.windowsComponentNames.isNotEmpty()) {
|
||||
ProfileSummaryRow(
|
||||
stringResource(R.string.wincomp_title),
|
||||
profile.windowsComponentNames.joinToString(", "),
|
||||
)
|
||||
}
|
||||
a.textureAnisotropy?.let { value ->
|
||||
ProfileSummaryRow(
|
||||
stringResource(R.string.drawer_anisotropy),
|
||||
SessionPrefs.textureAnisotropyChoices(LocalContext.current)
|
||||
.firstOrNull { it.first == value }?.second.orEmpty(),
|
||||
)
|
||||
}
|
||||
a.textureLodBias?.let { value ->
|
||||
ProfileSummaryRow(
|
||||
stringResource(R.string.drawer_texture_sharpness),
|
||||
SessionPrefs.textureLodBiasChoices(LocalContext.current)
|
||||
.firstOrNull { it.first == value }?.second.orEmpty(),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun fexProfileLabel(value: ProfileValue): String {
|
||||
return when (value.value) {
|
||||
GameEnvironment.CUSTOM_FEX_PRESET -> stringResource(R.string.comp_game_fex_custom)
|
||||
else -> stringResource(FexPreset.byId(value.value).label)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun profileValueLabel(value: ProfileValue) =
|
||||
value.value.ifEmpty { stringResource(R.string.comp_no_proton_short) }
|
||||
|
||||
@Composable
|
||||
private fun ProfileSummaryRow(label: String, value: String) {
|
||||
Row(modifier = Modifier.fillMaxWidth().padding(top = 3.dp)) {
|
||||
Text(label, fontSize = 12.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.width(96.dp))
|
||||
Text(
|
||||
value,
|
||||
fontSize = 12.sp,
|
||||
color = MaterialTheme.colorScheme.onBackground,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The Games tab's components: quick swaps between what is already installed, per Proton. A swap
|
||||
* into the Proton a running game uses waits until that game closes; downloading, importing and
|
||||
@@ -903,6 +1103,54 @@ private fun ComponentsDrawerPage(host: MenuHost, a: DrawerActions, track: (Strin
|
||||
}
|
||||
return
|
||||
}
|
||||
val gameProfile = a.selectedGameProfileId?.let { appId ->
|
||||
a.selectedGameProfile?.takeIf { it.appId == appId }
|
||||
}
|
||||
if (a.selectedGameProfileId != null) {
|
||||
if (gameProfile == null) {
|
||||
SettingsGroup(stringResource(R.string.drawer_page_components)) {
|
||||
Text(
|
||||
stringResource(R.string.comp_reading),
|
||||
fontSize = 13.sp,
|
||||
color = colors.onSurfaceVariant,
|
||||
modifier = Modifier.padding(14.dp),
|
||||
)
|
||||
}
|
||||
return
|
||||
}
|
||||
SettingsGroup(stringResource(R.string.drawer_page_components)) {
|
||||
Column(modifier = Modifier.fillMaxWidth().padding(horizontal = 14.dp, vertical = 11.dp)) {
|
||||
ProfileSummaryRow(stringResource(R.string.comp_proton), gameProfile.proton.value)
|
||||
}
|
||||
for (comp in ComponentsManager.COMPONENTS) {
|
||||
val value = gameProfile.components.getValue(comp)
|
||||
val options: List<Pair<String?, String>> =
|
||||
listOf(null to stringResource(R.string.comp_game_use_general)) +
|
||||
snap.packages.filter { it.comp == comp }.map { it.file to it.version }
|
||||
DrawerStackedChoice(
|
||||
host = host,
|
||||
key = "game-cmp-$comp",
|
||||
label = ComponentsManager.LABEL.getValue(comp),
|
||||
hint = if (value.inherited) {
|
||||
stringResource(R.string.drawer_component_inherited, value.value)
|
||||
} else {
|
||||
null
|
||||
},
|
||||
options = options,
|
||||
selected = gameProfile.componentFiles[comp],
|
||||
chipModifier = track("cmp-$comp"),
|
||||
onPick = { file -> a.onGameComponent(gameProfile.appId, comp, file) },
|
||||
)
|
||||
}
|
||||
}
|
||||
Text(
|
||||
stringResource(R.string.drawer_game_components_note, gameProfile.name),
|
||||
fontSize = 12.sp,
|
||||
color = colors.onSurfaceVariant,
|
||||
modifier = Modifier.padding(horizontal = 4.dp, vertical = 12.dp),
|
||||
)
|
||||
return
|
||||
}
|
||||
val running = snap.protons.filter { it.inUseByGame }
|
||||
var pick by rememberSaveable { mutableStateOf<String?>(null) }
|
||||
val view = snap.protons.firstOrNull { it.proton.id == pick } ?: running.firstOrNull() ?: snap.protons.firstOrNull()
|
||||
|
||||
@@ -58,7 +58,7 @@
|
||||
<string name="game_env_save">Save</string>
|
||||
<string name="game_env_remove">Remove</string>
|
||||
<string name="game_env_restore">Inherit again</string>
|
||||
<string name="game_env_reset">Reset this profile</string>
|
||||
<string name="game_env_reset">Clear environment overrides</string>
|
||||
<string name="game_env_unset">Unset for this profile</string>
|
||||
<string name="game_env_empty">No variables set.</string>
|
||||
<string name="game_env_inherited">Inherited</string>
|
||||
@@ -413,6 +413,41 @@
|
||||
<string name="comp_check_nightlies">Check the Nightlies for new packages</string>
|
||||
<string name="comp_proton">Proton</string>
|
||||
<string name="comp_proton_note">The Proton chosen here runs every game that has not picked its own in Steam, and a change made in Steam shows here too. Steam replaces Valve\'s Proton when it updates; originals are kept per build.</string>
|
||||
<string name="comp_scope">Configuration</string>
|
||||
<string name="comp_profile_configure">Configure profile</string>
|
||||
<string name="comp_profile">Profile</string>
|
||||
<string name="comp_scope_general">Default profile</string>
|
||||
<string name="comp_scope_general_detail">Used automatically by games without overrides.</string>
|
||||
<string name="comp_profile_game_detail">Saved settings used automatically when %1$s launches.</string>
|
||||
<string name="comp_game_hint">Choose only the settings this game needs. Everything else continues to use the Default profile.</string>
|
||||
<string name="comp_game_fex">FEX preset</string>
|
||||
<string name="comp_game_fex_inherited">Using the Default profile preset.</string>
|
||||
<string name="comp_game_fex_override">Custom preset saved for this game.</string>
|
||||
<string name="comp_game_fex_custom">Custom FEX variables</string>
|
||||
<string name="comp_game_use_general">Use Default</string>
|
||||
<string name="comp_game_compatibility">Game compatibility</string>
|
||||
<string name="comp_game_environment_hint">Proton, DXVK, VKD3D and synchronization environment options for this game.</string>
|
||||
<string name="comp_game_proton_inherited">Using the Default profile Proton.</string>
|
||||
<string name="comp_game_proton_override">Custom Proton saved for this game through Steam compatibility mapping.</string>
|
||||
<string name="comp_no_proton_short">No Proton</string>
|
||||
<string name="comp_game_dxvk">DXVK</string>
|
||||
<string name="comp_game_vkd3d">VKD3D-Proton</string>
|
||||
<string name="comp_game_component_runtime">Uses the Default profile package from %1$s unless this game selects another package.</string>
|
||||
<string name="comp_game_component_general">Uses the Default profile component package.</string>
|
||||
<string name="comp_game_component_override">Uses %1$s only for this game.</string>
|
||||
<string name="comp_game_runtime_options">Runtime options</string>
|
||||
<string name="comp_game_environment_other_hint">Other per-game Proton, DXVK, VKD3D-Proton and synchronization environment options.</string>
|
||||
<string name="comp_game_saved_next">%1$s\'s profile is saved for the next game launch.</string>
|
||||
<string name="comp_game_proton_live">%1$s\'s Proton choice is saved and available in Steam now.</string>
|
||||
<string name="comp_game_proton_next">%1$s\'s Proton choice is saved. Restart Steam before launching the game.</string>
|
||||
<string name="comp_game_proton_not_runnable">%1$s cannot use the selected Proton on this device.</string>
|
||||
<string name="comp_game_load_failed">Could not load %1$s\'s profile: %2$s</string>
|
||||
<string name="comp_game_save_failed">The game profile could not be saved: %1$s</string>
|
||||
<string name="comp_game_reset">Reset game profile</string>
|
||||
<string name="comp_game_reset_title">Reset %1$s\'s profile?</string>
|
||||
<string name="comp_game_reset_body">Remove this game\'s Proton, FEX, component package, environment, texture filtering, and Windows component overrides? It will use the Default profile.</string>
|
||||
<string name="comp_game_reset_done">%1$s now uses the Default profile.</string>
|
||||
<string name="comp_game_reset_failed">The game profile could not be reset completely: %1$s</string>
|
||||
<string name="comp_default_live">%1$s now runs every game that has not picked its own Proton in Steam.</string>
|
||||
<string name="comp_default_next">%1$s will run every game that has not picked its own Proton, from the next time Steam starts.</string>
|
||||
<string name="comp_default_not_runnable">%1$s cannot start games here, so it cannot be the default.</string>
|
||||
@@ -431,7 +466,7 @@
|
||||
<string name="comp_applies_next_game">Applies the next time a game starts</string>
|
||||
<string name="comp_import_zip">Import .zip</string>
|
||||
<string name="comp_reading">Reading Protons…</string>
|
||||
<string name="comp_no_proton">No Proton installed yet. Start Steam once to download its ARM64 Proton, or add GE-Proton or CachyOS from Setup.</string>
|
||||
<string name="comp_no_proton">No Proton installed yet. Start Steam once to download its ARM64 Proton, or add GE-Proton, CachyOS or DroidDeck-Proton from Setup.</string>
|
||||
<string name="comp_original">Original · %1$s</string>
|
||||
<string name="comp_this_build">%1$s · this build</string>
|
||||
<string name="comp_earlier_build">%1$s · earlier build</string>
|
||||
@@ -576,6 +611,19 @@
|
||||
<string name="drawer_stop_title">Stop session?</string>
|
||||
<string name="drawer_running_now">Running now</string>
|
||||
<string name="drawer_no_game">No game is running on a Proton</string>
|
||||
<string name="drawer_selected_profile">Game profile</string>
|
||||
<string name="drawer_selected_profile_none">Profile details are not available yet.</string>
|
||||
<string name="drawer_profile_refresh_failed_initial">Couldn\'t load game profiles. Retrying automatically.</string>
|
||||
<string name="drawer_profile_refresh_failed_stale">Couldn\'t refresh game profiles. Showing the last available data; retrying automatically.</string>
|
||||
<string name="drawer_profile_inspect_hint">View and edit the saved settings used on the next launch.</string>
|
||||
<string name="drawer_profile_default">Using Default profile</string>
|
||||
<string name="drawer_profile_custom">Custom profile</string>
|
||||
<string name="drawer_component_inherited">Using %1$s from the Default profile.</string>
|
||||
<string name="drawer_game_components_note">Changes are saved to %1$s\'s profile and apply the next time the game launches.</string>
|
||||
<plurals name="drawer_profile_environment_overrides">
|
||||
<item quantity="one">%1$d game override</item>
|
||||
<item quantity="other">%1$d game overrides</item>
|
||||
</plurals>
|
||||
<string name="drawer_no_proton">No Proton is installed yet.</string>
|
||||
<string name="drawer_game_running">game running</string>
|
||||
<string name="drawer_reapplied">re-applied at launch %1$s</string>
|
||||
@@ -1029,6 +1077,13 @@
|
||||
<string name="proton_installed">Installed %1$s</string>
|
||||
<string name="proton_queued">Pending from an earlier request</string>
|
||||
<string name="proton_not_installed">Not installed</string>
|
||||
<!-- %1$s is the newer release's tag -->
|
||||
<string name="proton_update_available">Update available → %1$s</string>
|
||||
<!-- %1$s is the Proton's name (GE-Proton, proton-cachyos, DroidDeck-Proton) -->
|
||||
<string name="proton_remove_older">Remove old %1$s versions</string>
|
||||
<!-- %1$s lists the folders that are removed -->
|
||||
<string name="proton_remove_older_body">Removes %1$s. Games set to these versions must be switched to another Proton.</string>
|
||||
<string name="proton_remove_body">Games set to this version must be switched to another Proton.</string>
|
||||
<string name="proton_install_now">Install now</string>
|
||||
<string name="proton_cancel_queued">Cancel queued</string>
|
||||
<string name="pckb_android">Android keyboard</string>
|
||||
@@ -1250,6 +1305,7 @@
|
||||
<!-- Shown as "Auto (direct)" in the drawer's touch setting -->
|
||||
<string name="session_touch_auto_direct">direct</string>
|
||||
<string name="session_swap_failed">Swap failed: %1$s</string>
|
||||
<string name="session_profile_save_failed">Profile save failed: %1$s</string>
|
||||
<string name="session_desktop_paused">The desktop is paused</string>
|
||||
<!-- %1$s is the program's name -->
|
||||
<string name="session_named_paused">%1$s is paused</string>
|
||||
@@ -1758,7 +1814,7 @@
|
||||
<!-- %1$s is the client's own download progress, as it prints it -->
|
||||
<string name="loadstate_steam_client">Downloading the Steam client · %1$s</string>
|
||||
|
||||
<!-- Installing GE-Proton / proton-cachyos (%1$s is the tool's name, %2$s its release tag) -->
|
||||
<!-- Installing GE-Proton / proton-cachyos / DroidDeck-Proton (%1$s is the tool's name, %2$s its release tag) -->
|
||||
<string name="pextra_busy">A compatibility tool install is already running</string>
|
||||
<string name="pextra_stop_session">Stop the active session before installing compatibility tools</string>
|
||||
<string name="pextra_no_release">Could not find an ARM64 release for %1$s</string>
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
//! Every quirk of the Java reader is kept on purpose (the Java manager stays the reference and
|
||||
//! the two engines must derive the same plan from the same bytes): section skips by declared
|
||||
//! size, `readFString` UTF-16LE/ASCII decoding, duplicate-GUID handling (last value, first
|
||||
//! position), the JSON `Long.parseLong(.., 16)` / `parseInt` fallbacks, and "any exception →
|
||||
//! position), the JSON blob decoding (`blobToNum`) and its fallbacks, and "any exception →
|
||||
//! parse failed".
|
||||
|
||||
use std::collections::HashMap;
|
||||
@@ -445,6 +445,25 @@ fn json_to_string(v: &serde_json::Value) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// `EpicDownloadManager.blobToNum`: a JSON manifest writes every number as a "blob", each byte
|
||||
/// as three decimal digits, least significant first ("013000000000" = 13). Bits past 64 are
|
||||
/// dropped; `None` when a group is not a number (Java: `NumberFormatException`).
|
||||
pub fn blob_to_num(s: &str) -> Option<u64> {
|
||||
let bytes = s.as_bytes();
|
||||
let mut num: u64 = 0;
|
||||
for (i, group) in bytes.chunks(3).enumerate() {
|
||||
if !group.iter().all(u8::is_ascii_digit) {
|
||||
return None;
|
||||
}
|
||||
let byte: u64 = std::str::from_utf8(group).ok()?.parse().ok()?;
|
||||
let shift = i * 8;
|
||||
if shift < 64 {
|
||||
num = num.wrapping_add(byte << shift);
|
||||
}
|
||||
}
|
||||
Some(num)
|
||||
}
|
||||
|
||||
/// `obj.optString(key, fallback)`.
|
||||
fn opt_string(obj: &serde_json::Map<String, serde_json::Value>, key: &str, fallback: &str) -> String {
|
||||
match obj.get(key) {
|
||||
@@ -483,9 +502,8 @@ pub fn parse_json_manifest(bytes: &[u8]) -> Result<Manifest, String> {
|
||||
.as_object()
|
||||
.ok_or_else(|| "JSON manifest: root is not an object".to_string())?;
|
||||
|
||||
let manifest_version: i32 = opt_string(root, "ManifestFileVersion", "0")
|
||||
.parse::<i32>()
|
||||
.unwrap_or(0);
|
||||
let manifest_version: i32 = blob_to_num(&opt_string(root, "ManifestFileVersion", "0"))
|
||||
.map_or(0, |v| v as i32);
|
||||
let chunk_dir = chunk_dir_for_json_version(manifest_version);
|
||||
|
||||
let chunk_hash_list = root
|
||||
@@ -502,19 +520,14 @@ pub fn parse_json_manifest(bytes: &[u8]) -> Result<Manifest, String> {
|
||||
if guid_hex.len() < 32 || !guid_hex.is_char_boundary(32) {
|
||||
continue;
|
||||
}
|
||||
let hash_hex = json_to_string(hash_value);
|
||||
let guid = parse_guid_from_hex(guid_hex)?;
|
||||
let hash = if hash_hex.len() >= 16 && hash_hex.is_char_boundary(16) {
|
||||
u64::from_str_radix(&hash_hex[0..16], 16).unwrap_or(0)
|
||||
} else {
|
||||
0
|
||||
};
|
||||
let hash = blob_to_num(&json_to_string(hash_value)).unwrap_or(0);
|
||||
let group_num = match data_group_list {
|
||||
Some(dgl) => opt_string(dgl, guid_hex, "0").parse::<i32>().unwrap_or(0),
|
||||
Some(dgl) => blob_to_num(&opt_string(dgl, guid_hex, "0")).map_or(0, |v| v as i32),
|
||||
None => 0,
|
||||
};
|
||||
let file_size = match chunk_filesize_list {
|
||||
Some(cfl) => i64::from_str_radix(&opt_string(cfl, guid_hex, "0"), 16).unwrap_or(0),
|
||||
Some(cfl) => blob_to_num(&opt_string(cfl, guid_hex, "0")).map_or(0, |v| v as i64),
|
||||
None => 0,
|
||||
};
|
||||
let c = ChunkInfo {
|
||||
@@ -570,8 +583,8 @@ pub fn parse_json_manifest(bytes: &[u8]) -> Result<Manifest, String> {
|
||||
if part_guid.len() >= 32 && part_guid.is_char_boundary(32) {
|
||||
part.guid = parse_guid_from_hex(&part_guid)?;
|
||||
}
|
||||
part.offset = opt_string(part_obj, "Offset", "0").parse::<i32>().unwrap_or(0);
|
||||
part.size = opt_string(part_obj, "Size", "0").parse::<i32>().unwrap_or(0);
|
||||
part.offset = blob_to_num(&opt_string(part_obj, "Offset", "0")).map_or(0, |v| v as i32);
|
||||
part.size = blob_to_num(&opt_string(part_obj, "Size", "0")).map_or(0, |v| v as i32);
|
||||
fi.parts.push(part);
|
||||
}
|
||||
}
|
||||
@@ -928,17 +941,29 @@ mod tests {
|
||||
assert_eq!(c.fstring().unwrap(), "a\u{FFFD}b");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blob_numbers_are_decimal_bytes_least_significant_first() {
|
||||
assert_eq!(blob_to_num("001000000000"), Some(1));
|
||||
assert_eq!(blob_to_num("000001000000"), Some(0x100));
|
||||
assert_eq!(blob_to_num("001002003004005006007008"), Some(0x0807_0605_0403_0201));
|
||||
assert_eq!(blob_to_num("255255255255255255255255"), Some(u64::MAX));
|
||||
assert_eq!(blob_to_num("7"), Some(7));
|
||||
assert_eq!(blob_to_num(""), Some(0));
|
||||
assert_eq!(blob_to_num("0x1"), None);
|
||||
assert_eq!(blob_to_num("-05"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn json_manifest_parses_like_java() {
|
||||
let json = r#"{
|
||||
"ManifestFileVersion": "013",
|
||||
"ChunkHashList": {
|
||||
"0000000100000002000000030000000ff": "0123456789ABCDEF00",
|
||||
"0000000100000002000000030000000ff": "001002003004005006007008",
|
||||
"short": "00",
|
||||
"DEADBEEFFFFFFFFF0000000080000000": "zz"
|
||||
},
|
||||
"DataGroupList": { "0000000100000002000000030000000ff": "7", "DEADBEEFFFFFFFFF0000000080000000": "x" },
|
||||
"ChunkFilesizeList": { "0000000100000002000000030000000ff": "FF" },
|
||||
"ChunkFilesizeList": { "0000000100000002000000030000000ff": "255" },
|
||||
"FileManifestList": [
|
||||
{ "Filename": "a.bin", "InstallTags": ["German", ""],
|
||||
"FileChunkParts": [ { "Guid": "0000000100000002000000030000000ff", "Offset": "12", "Size": "34" },
|
||||
@@ -951,7 +976,7 @@ mod tests {
|
||||
assert_eq!(m.unique_chunks.len(), 2, "keys shorter than 32 chars are skipped");
|
||||
let c0 = &m.unique_chunks[0];
|
||||
assert_eq!(c0.guid, [1, 2, 3, 0x0000_000F]);
|
||||
assert_eq!(c0.hash, 0x0123_4567_89AB_CDEF);
|
||||
assert_eq!(c0.hash, 0x0807_0605_0403_0201);
|
||||
assert_eq!(c0.group_num, 7);
|
||||
assert_eq!(c0.file_size, 0xFF);
|
||||
assert_eq!(c0.window_size, 0);
|
||||
@@ -968,11 +993,36 @@ mod tests {
|
||||
assert_eq!(m.files[0].parts[0].size, 34);
|
||||
assert_eq!(m.files[0].parts[1].guid, [0; 4]);
|
||||
assert_eq!(m.files[0].parts[1].offset, 0);
|
||||
assert_eq!(m.files[0].parts[1].size, -5);
|
||||
assert_eq!(m.files[0].parts[1].size, 0);
|
||||
assert!(m.files[0].sha1.is_none());
|
||||
assert!(m.files[1].parts.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn json_manifest_uses_blobs() {
|
||||
let json = r#"{
|
||||
"ManifestFileVersion": "006000000000",
|
||||
"ChunkHashList": { "0000000100000002000000030000000F": "001002003004005006007008" },
|
||||
"DataGroupList": { "0000000100000002000000030000000F": "007" },
|
||||
"ChunkFilesizeList": { "0000000100000002000000030000000F": "001002000000000000000000" },
|
||||
"FileManifestList": [
|
||||
{ "Filename": "a.bin",
|
||||
"FileChunkParts": [ { "Guid": "0000000100000002000000030000000F", "Offset": "001000000000", "Size": "000000016000" } ] }
|
||||
]
|
||||
}"#;
|
||||
let m = parse_manifest(json.as_bytes()).expect("json parse");
|
||||
assert_eq!(m.chunk_dir, "ChunksV3");
|
||||
let c = &m.unique_chunks[0];
|
||||
assert_eq!(c.file_size, 0x0201);
|
||||
assert_eq!(
|
||||
c.path(&m.chunk_dir),
|
||||
"ChunksV3/07/0807060504030201_0000000100000002000000030000000F.chunk"
|
||||
);
|
||||
let part = &m.files[0].parts[0];
|
||||
assert_eq!(part.offset, 1);
|
||||
assert_eq!(part.size, 1_048_576);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn json_manifest_failures_match_java_nulls() {
|
||||
assert!(parse_manifest(br#"{"FileManifestList": []}"#).is_err(), "no ChunkHashList");
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
package com.droiddeck.launcher.agent
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Test
|
||||
|
||||
class AgentGuestSelectionTest {
|
||||
private val installedAppIds = setOf(646570L, 3180310L)
|
||||
|
||||
@Test fun focusedInstalledGameIsSelected() {
|
||||
assertEquals(3180310L, AgentGuest.focusedInstalledSteamAppId(3180310L, installedAppIds))
|
||||
}
|
||||
|
||||
@Test fun focusedInstalledGameIsActive() {
|
||||
assertEquals(
|
||||
3180310L,
|
||||
AgentGuest.activeInstalledSteamAppId(3180310L, listOf(769L, 3180310L), installedAppIds),
|
||||
)
|
||||
}
|
||||
|
||||
@Test fun selectedSteamGameWinsOverStaleActiveSteamGame() {
|
||||
assertEquals(
|
||||
646570L,
|
||||
AgentGuest.preferredInstalledSteamAppId(646570L, 3180310L, installedAppIds),
|
||||
)
|
||||
}
|
||||
|
||||
@Test fun validGamescopeGameFallsBackWhenSteamSelectionFails() {
|
||||
assertEquals(
|
||||
3180310L,
|
||||
AgentGuest.selectedOrActiveInstalledSteamAppId(
|
||||
Result.failure(IllegalStateException("agent unavailable")),
|
||||
3180310L,
|
||||
installedAppIds,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test fun absentSelectionAndActiveGameRemainAValidNoSelection() {
|
||||
assertNull(AgentGuest.selectedOrActiveInstalledSteamAppId(Result.success(null), null, installedAppIds))
|
||||
}
|
||||
|
||||
@Test(expected = IllegalStateException::class)
|
||||
fun selectionFailureWithoutGamescopeFallbackRemainsAnError() {
|
||||
AgentGuest.selectedOrActiveInstalledSteamAppId(
|
||||
Result.failure(IllegalStateException("agent unavailable")),
|
||||
null,
|
||||
installedAppIds,
|
||||
)
|
||||
}
|
||||
|
||||
@Test fun soleFocusableInstalledGameRemainsActiveUnderSteamOverlay() {
|
||||
assertEquals(
|
||||
3180310L,
|
||||
AgentGuest.activeInstalledSteamAppId(769L, listOf(3180310L), installedAppIds),
|
||||
)
|
||||
}
|
||||
|
||||
@Test fun ambiguousFocusableGamesAreIgnored() {
|
||||
assertNull(
|
||||
AgentGuest.activeInstalledSteamAppId(769L, listOf(646570L, 3180310L), installedAppIds),
|
||||
)
|
||||
}
|
||||
|
||||
@Test fun soleBaselayerGameResolvesAmbiguousSteamOverlayFocus() {
|
||||
assertEquals(
|
||||
646570L,
|
||||
AgentGuest.activeInstalledSteamAppId(
|
||||
focusedAppId = 769L,
|
||||
focusableAppIds = listOf(646570L, 3180310L),
|
||||
installedAppIds = installedAppIds,
|
||||
baselayerAppIds = listOf(769L, 646570L),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test fun steamClientFocusIsIgnored() {
|
||||
assertNull(AgentGuest.focusedInstalledSteamAppId(769L, installedAppIds))
|
||||
}
|
||||
|
||||
@Test fun unknownGameFocusIsIgnored() {
|
||||
assertNull(AgentGuest.focusedInstalledSteamAppId(42L, installedAppIds))
|
||||
}
|
||||
|
||||
@Test fun missingFocusSnapshotIsIgnored() {
|
||||
assertNull(AgentGuest.focusedInstalledSteamAppId(null, installedAppIds))
|
||||
}
|
||||
}
|
||||
@@ -102,4 +102,24 @@ class GameEnvironmentTest {
|
||||
assertTrue(GameEnvironment.validScope("4294967295"))
|
||||
for (scope in listOf("0", "-1", "01", "+1", "4294967296", "../42")) assertFalse(GameEnvironment.validScope(scope))
|
||||
}
|
||||
|
||||
@Test fun gameFexPresetOverridesGeneralAndCanInheritAgain() {
|
||||
val performance = GameEnvironment.withGameFexPreset(GameEnvironment.Config(), "42", "PERFORMANCE")
|
||||
assertEquals("PERFORMANCE", GameEnvironment.gameFexPreset(performance, "42"))
|
||||
assertEquals("0", GameEnvironment.effective(performance, "STABILITY", "42")["FEX_TSOENABLED"])
|
||||
assertEquals("1", GameEnvironment.effective(performance, "STABILITY", "43")["FEX_TSOENABLED"])
|
||||
|
||||
val inherited = GameEnvironment.withGameFexPreset(performance, "42", null)
|
||||
assertNull(GameEnvironment.gameFexPreset(inherited, "42"))
|
||||
assertFalse(inherited.games.containsKey("42"))
|
||||
}
|
||||
|
||||
@Test fun gameFexPresetPreservesOtherOverridesAndRecognizesCustomValues() {
|
||||
val original = GameEnvironment.Config(games = mapOf("42" to mapOf("CUSTOM" to "value", "FEX_MULTIBLOCK" to "7")))
|
||||
assertEquals(GameEnvironment.CUSTOM_FEX_PRESET, GameEnvironment.gameFexPreset(original, "42"))
|
||||
|
||||
val compatibility = GameEnvironment.withGameFexPreset(original, "42", "COMPATIBILITY")
|
||||
assertEquals("value", compatibility.games.getValue("42")["CUSTOM"])
|
||||
assertEquals("COMPATIBILITY", GameEnvironment.gameFexPreset(compatibility, "42"))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class ComponentsProcessTest {
|
||||
private val guestPath = "/root/.local/share/Steam/steamapps/common/Proton"
|
||||
private val hostPath = "/data/user/0/com.droiddeck.launcher/files/root/root/.local/share/Steam/steamapps/common/Proton"
|
||||
|
||||
@Test
|
||||
fun `running game is recognized through guest path`() {
|
||||
val command = "python3 $guestPath/proton waitforexitandrun game.exe"
|
||||
|
||||
assertTrue(ComponentsManager.processUsesProton(listOf(guestPath, hostPath), command, gameOnly = true))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `running game is recognized through Android host path`() {
|
||||
val command = "python3 $hostPath/proton waitforexitandrun game.exe"
|
||||
|
||||
assertTrue(ComponentsManager.processUsesProton(listOf(guestPath, hostPath), command, gameOnly = true))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `Steam startup Proton process is not reported as a running game`() {
|
||||
val command = "python3 $hostPath/proton run wineboot.exe"
|
||||
|
||||
assertFalse(ComponentsManager.processUsesProton(listOf(guestPath, hostPath), command, gameOnly = true))
|
||||
assertTrue(ComponentsManager.processUsesProton(listOf(guestPath, hostPath), command, gameOnly = false))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `unrelated Proton process is ignored`() {
|
||||
val command = "python3 /other/Proton/proton waitforexitandrun game.exe"
|
||||
|
||||
assertFalse(ComponentsManager.processUsesProton(listOf(guestPath, hostPath), command, gameOnly = true))
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,10 @@ package com.droiddeck.launcher.session
|
||||
|
||||
import android.content.Context
|
||||
import com.droiddeck.launcher.gpu.GpuInfo
|
||||
import com.droiddeck.launcher.core.Hashes
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import com.github.luben.zstd.ZstdOutputStream
|
||||
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import org.junit.Assert.*
|
||||
@@ -89,6 +92,283 @@ class ForcedPackageTest {
|
||||
assertNull(install(gpu(650, GpuInfo.Family.A6XX)))
|
||||
}
|
||||
|
||||
@Test fun gameComponentProfilesReadOnlyKnownComponents() {
|
||||
val state = File(context.filesDir, "components/state.json")
|
||||
state.parentFile!!.mkdirs()
|
||||
state.writeText(JSONObject()
|
||||
.put("active", JSONObject())
|
||||
.put("queued", JSONObject())
|
||||
.put("profiles", JSONObject().put("42", JSONObject()
|
||||
.put("fex", "fex.wcp")
|
||||
.put("dxvk", "dxvk.wcp")
|
||||
.put("unknown", "ignored.wcp")))
|
||||
.toString())
|
||||
|
||||
assertEquals(mapOf("fex" to "fex.wcp", "dxvk" to "dxvk.wcp"), ComponentsManager.gameComponents(context, "42"))
|
||||
assertTrue(ComponentsManager.gameComponents(context, "43").isEmpty())
|
||||
}
|
||||
|
||||
@Test fun removingLastGameOverrideKeepsBundledComponentRestoreRow() {
|
||||
val protonName = "proton-exp"
|
||||
proton(protonName)
|
||||
writeGameProfile("42", "dxvk", "custom-dxvk.wcp")
|
||||
|
||||
ComponentsManager.clearGameComponents(context, "42")
|
||||
|
||||
assertFalse(ComponentsManager.gameComponents(context, "42").containsKey("dxvk"))
|
||||
assertDefaultDxvkRestoreRow(protonName)
|
||||
}
|
||||
|
||||
@Test fun usingDefaultForLastGameOverrideKeepsBundledComponentRestoreRow() {
|
||||
val protonName = "proton-exp"
|
||||
proton(protonName)
|
||||
writeGameProfile("42", "dxvk", "custom-dxvk.wcp")
|
||||
|
||||
ComponentsManager.setGameComponent(context, "42", "dxvk", null)
|
||||
|
||||
assertFalse(ComponentsManager.gameComponents(context, "42").containsKey("dxvk"))
|
||||
assertDefaultDxvkRestoreRow(protonName)
|
||||
}
|
||||
|
||||
@Test fun aNewProtonIsCapturedWhenTheLastOverrideIsReset() {
|
||||
proton("existing")
|
||||
writeGameProfile("42", "dxvk", "custom-dxvk.wcp")
|
||||
ComponentsManager.snapshotAll(context)
|
||||
proton("new-proton")
|
||||
|
||||
ComponentsManager.clearGameComponents(context, "42")
|
||||
|
||||
assertDefaultDxvkRestoreRow("existing")
|
||||
assertDefaultDxvkRestoreRow("new-proton")
|
||||
}
|
||||
|
||||
@Test fun anUpdatedBuildIsCapturedEvenAfterTheLastProfileWasRemoved() {
|
||||
proton("proton-exp")
|
||||
writeGameProfile("42", "dxvk", "custom-dxvk.wcp")
|
||||
ComponentsManager.clearGameComponents(context, "42")
|
||||
proton("proton-exp", "experimental-12")
|
||||
|
||||
ComponentsManager.setGameComponent(context, "43", "dxvk", null)
|
||||
|
||||
assertDefaultDxvkRestoreRow("proton-exp", "experimental-12")
|
||||
assertTrue(original("proton-exp", "experimental-11").isFile)
|
||||
assertTrue(original("proton-exp", "experimental-12").isFile)
|
||||
}
|
||||
|
||||
@Test fun aKnownEmptyComponentHasAnExplicitOriginalBundle() {
|
||||
proton("proton-exp", dxvk = false)
|
||||
writeGameProfile("42", "dxvk", "custom-dxvk.wcp")
|
||||
|
||||
ComponentsManager.clearGameComponents(context, "42")
|
||||
|
||||
assertTrue(original("proton-exp").isFile)
|
||||
val rows = launchState().readLines().map { it.split('\t') }
|
||||
assertEquals(14, rows.size)
|
||||
assertTrue(rows.all { it[3] == "dxvk" && it[5] == "-" && it[6] == "-" })
|
||||
}
|
||||
|
||||
@Test fun missingOriginalsCannotBeRecapturedFromPreviouslyProfiledFiles() {
|
||||
proton("proton-exp")
|
||||
writeGameProfile("42", "dxvk", "custom-dxvk.wcp")
|
||||
val saved = File(context.filesDir, "components/state.json").readText()
|
||||
val prior = "42\tproton-exp\texperimental-11\tdxvk\tfiles/lib/wine/dxvk/aarch64-windows/d3d11.dll\t-\t-\n"
|
||||
launchState().apply { parentFile!!.mkdirs(); writeText(prior) }
|
||||
|
||||
assertThrows(IllegalStateException::class.java) {
|
||||
ComponentsManager.setGameComponent(context, "42", "dxvk", null)
|
||||
}
|
||||
|
||||
assertEquals(saved, File(context.filesDir, "components/state.json").readText())
|
||||
assertEquals(prior, launchState().readText())
|
||||
assertFalse(original("proton-exp").isFile)
|
||||
}
|
||||
|
||||
@Test fun aBrokenOriginalDoesNotPublishDeletionRowsOrRemoveThePreviousStore() {
|
||||
proton("proton-exp")
|
||||
writeGameProfile("42", "dxvk", "custom-dxvk.wcp")
|
||||
val state = File(context.filesDir, "components/state.json")
|
||||
val saved = state.readText()
|
||||
val prior = "*\tother\tbuild\tdxvk\tfiles/old.dll\told-hash\t/old.dll\n"
|
||||
launchState().apply { parentFile!!.mkdirs(); writeText(prior) }
|
||||
val oldSource = File(launchState().parentFile, "store/old/files/old.dll")
|
||||
oldSource.apply { parentFile!!.mkdirs(); writeText("old component") }
|
||||
original("proton-exp").apply { parentFile!!.mkdirs(); writeText("not a bundle") }
|
||||
|
||||
assertThrows(java.io.IOException::class.java) {
|
||||
ComponentsManager.clearGameComponents(context, "42")
|
||||
}
|
||||
|
||||
assertEquals(saved, state.readText())
|
||||
assertEquals(prior, launchState().readText())
|
||||
assertEquals("old component", oldSource.readText())
|
||||
}
|
||||
|
||||
@Test fun anArchiveWithoutAProfileIsNotAKnownEmptyOriginal() {
|
||||
proton("proton-exp")
|
||||
writeGameProfile("42", "dxvk", "custom-dxvk.wcp")
|
||||
val bundle = original("proton-exp")
|
||||
bundle.parentFile!!.mkdirs()
|
||||
TarArchiveOutputStream(ZstdOutputStream(bundle.outputStream())).use { }
|
||||
|
||||
assertThrows(IllegalArgumentException::class.java) {
|
||||
ComponentsManager.clearGameComponents(context, "42")
|
||||
}
|
||||
|
||||
assertFalse(launchState().exists())
|
||||
assertEquals("custom-dxvk.wcp", ComponentsManager.gameComponents(context, "42")["dxvk"])
|
||||
}
|
||||
|
||||
@Test fun aFailedStateCommitIsRecoveredBeforeSelectionsCanBeRead() {
|
||||
proton("proton-exp")
|
||||
writeGameProfile("42", "dxvk", "custom-dxvk.wcp")
|
||||
val state = File(context.filesDir, "components/state.json")
|
||||
val saved = state.readText()
|
||||
val blocked = File(context.filesDir, "components/state.json.tmp")
|
||||
blocked.mkdir()
|
||||
val blocker = File(blocked, "blocker").apply { writeText("keep directory nonempty") }
|
||||
val oldSource = File(launchState().parentFile, "store/old/files/old.dll").apply {
|
||||
parentFile!!.mkdirs()
|
||||
writeText("old component")
|
||||
}
|
||||
|
||||
assertThrows(java.io.IOException::class.java) {
|
||||
ComponentsManager.clearGameComponents(context, "42")
|
||||
}
|
||||
|
||||
assertEquals(saved, state.readText())
|
||||
assertTrue(pendingState().isFile)
|
||||
assertTrue(launchState().isFile)
|
||||
assertEquals(Hashes.sha256(launchState()), JSONObject(pendingState().readText()).getString("launchSha256"))
|
||||
assertEquals("old component", oldSource.readText())
|
||||
assertThrows(java.io.IOException::class.java) {
|
||||
ComponentsManager.gameComponents(context, "42")
|
||||
}
|
||||
assertTrue(pendingState().isFile)
|
||||
|
||||
assertTrue(blocker.delete())
|
||||
assertTrue(blocked.delete())
|
||||
assertTrue(ComponentsManager.gameComponents(context, "42").isEmpty())
|
||||
assertFalse(pendingState().exists())
|
||||
assertDefaultDxvkRestoreRow("proton-exp")
|
||||
assertTrue(ComponentsManager.gameComponents(context, "42").isEmpty())
|
||||
ComponentsManager.snapshotAll(context)
|
||||
assertFalse(oldSource.exists())
|
||||
assertDefaultDxvkRestoreRow("proton-exp")
|
||||
}
|
||||
|
||||
@Test fun aFailedLaunchPublicationRetainsTheOldSelectionsAndStore() {
|
||||
proton("proton-exp")
|
||||
writeGameProfile("42", "dxvk", "custom-dxvk.wcp")
|
||||
val state = File(context.filesDir, "components/state.json")
|
||||
val saved = state.readText()
|
||||
launchState().mkdirs()
|
||||
val blocker = File(launchState(), "blocker").apply { writeText("block rename") }
|
||||
val oldSource = File(launchState().parentFile, "store/old/files/old.dll").apply {
|
||||
parentFile!!.mkdirs()
|
||||
writeText("old component")
|
||||
}
|
||||
|
||||
assertThrows(IllegalStateException::class.java) {
|
||||
ComponentsManager.clearGameComponents(context, "42")
|
||||
}
|
||||
|
||||
assertEquals(saved, state.readText())
|
||||
assertTrue(pendingState().isFile)
|
||||
assertEquals("custom-dxvk.wcp", ComponentsManager.gameComponents(context, "42")["dxvk"])
|
||||
assertFalse(pendingState().exists())
|
||||
assertEquals("old component", oldSource.readText())
|
||||
assertTrue(blocker.delete())
|
||||
assertTrue(launchState().delete())
|
||||
|
||||
ComponentsManager.clearGameComponents(context, "42")
|
||||
|
||||
assertTrue(ComponentsManager.gameComponents(context, "42").isEmpty())
|
||||
assertFalse(oldSource.exists())
|
||||
assertDefaultDxvkRestoreRow("proton-exp")
|
||||
}
|
||||
|
||||
@Test fun interruptionBeforePublicationDiscardsOnlyThePendingSelections() {
|
||||
writeGameProfile("42", "dxvk", "old-dxvk.wcp")
|
||||
val state = File(context.filesDir, "components/state.json")
|
||||
val saved = state.readText()
|
||||
val next = JSONObject(saved).apply {
|
||||
getJSONObject("profiles").getJSONObject("42").put("dxvk", "new-dxvk.wcp")
|
||||
}
|
||||
val staged = File(launchState().parentFile, "desired.tsv.tmp").apply {
|
||||
parentFile!!.mkdirs()
|
||||
writeText("new launch table")
|
||||
}
|
||||
launchState().writeText("old launch table")
|
||||
writePendingState(next, staged)
|
||||
|
||||
assertEquals("old-dxvk.wcp", ComponentsManager.gameComponents(context, "42")["dxvk"])
|
||||
assertEquals(saved, state.readText())
|
||||
assertEquals("old launch table", launchState().readText())
|
||||
assertFalse(pendingState().exists())
|
||||
assertFalse(staged.exists())
|
||||
}
|
||||
|
||||
@Test fun identicalLaunchTablesDoNotCommitUnpublishedSettings() {
|
||||
writeGameProfile("42", "dxvk", "old-dxvk.wcp")
|
||||
val state = File(context.filesDir, "components/state.json")
|
||||
val saved = state.readText()
|
||||
val next = JSONObject(saved).put("queued", JSONObject().put("proton-exp", JSONObject()))
|
||||
val staged = File(launchState().parentFile, "desired.tsv.tmp").apply {
|
||||
parentFile!!.mkdirs()
|
||||
writeText("unchanged launch table")
|
||||
}
|
||||
launchState().writeText(staged.readText())
|
||||
writePendingState(next, staged)
|
||||
|
||||
assertEquals("old-dxvk.wcp", ComponentsManager.gameComponents(context, "42")["dxvk"])
|
||||
assertEquals(saved, state.readText())
|
||||
assertFalse(pendingState().exists())
|
||||
assertFalse(staged.exists())
|
||||
}
|
||||
|
||||
@Test fun interruptionAfterPublicationRecoversAllSelectionsAndIsIdempotent() {
|
||||
writeGameProfile("42", "dxvk", "old-dxvk.wcp")
|
||||
val next = JSONObject()
|
||||
.put("active", JSONObject().put("proton-exp", JSONObject().put("dxvk", JSONObject().put("file", dxvk2))))
|
||||
.put("queued", JSONObject().put("proton-exp", JSONObject().put("fex", JSONObject().put("file", "fex.wcp"))))
|
||||
.put("profiles", JSONObject()
|
||||
.put("42", JSONObject().put("dxvk", "new-dxvk.wcp"))
|
||||
.put("43", JSONObject().put("fex", "fex.wcp")))
|
||||
.put("profiledComponents", JSONArray(listOf("dxvk", "fex")))
|
||||
launchState().apply { parentFile!!.mkdirs(); writeText("published launch table") }
|
||||
writePendingState(next, launchState())
|
||||
|
||||
assertEquals("new-dxvk.wcp", ComponentsManager.gameComponents(context, "42")["dxvk"])
|
||||
assertEquals("fex.wcp", ComponentsManager.gameComponents(context, "43")["fex"])
|
||||
assertEquals(next.toString(2), File(context.filesDir, "components/state.json").readText())
|
||||
assertFalse(pendingState().exists())
|
||||
assertEquals("published launch table", launchState().readText())
|
||||
assertEquals("new-dxvk.wcp", ComponentsManager.gameComponents(context, "42")["dxvk"])
|
||||
}
|
||||
|
||||
@Test fun aPendingTransactionAfterTheStateCommitCanBeRecoveredAgain() {
|
||||
writeGameProfile("42", "dxvk", "new-dxvk.wcp")
|
||||
val state = File(context.filesDir, "components/state.json")
|
||||
val next = JSONObject(state.readText())
|
||||
launchState().apply { parentFile!!.mkdirs(); writeText("published launch table") }
|
||||
writePendingState(next, launchState())
|
||||
|
||||
assertEquals("new-dxvk.wcp", ComponentsManager.gameComponents(context, "42")["dxvk"])
|
||||
assertEquals(next.toString(2), state.readText())
|
||||
assertFalse(pendingState().exists())
|
||||
}
|
||||
|
||||
@Test fun anUnreadableRecoveryRecordDoesNotSilentlyReturnStaleSelections() {
|
||||
writeGameProfile("42", "dxvk", "old-dxvk.wcp")
|
||||
pendingState().writeText("incomplete recovery record")
|
||||
|
||||
assertThrows(org.json.JSONException::class.java) {
|
||||
ComponentsManager.gameComponents(context, "42")
|
||||
}
|
||||
|
||||
assertTrue(pendingState().isFile)
|
||||
}
|
||||
|
||||
@Test fun theSamePackageOnThisProtonBuildIsNotFetchedAgain() {
|
||||
proton("proton-exp")
|
||||
writeState("proton-exp", dxvk2, "experimental-11")
|
||||
@@ -204,11 +484,57 @@ class ForcedPackageTest {
|
||||
|
||||
private fun refuseApply(protonId: String, file: String): String = error("apply $protonId $file")
|
||||
|
||||
private fun proton(name: String, version: String = "experimental-11") {
|
||||
private fun writeGameProfile(scope: String, comp: String, file: String) {
|
||||
val state = File(context.filesDir, "components/state.json")
|
||||
state.parentFile!!.mkdirs()
|
||||
state.writeText(
|
||||
JSONObject()
|
||||
.put("active", JSONObject())
|
||||
.put("queued", JSONObject())
|
||||
.put("profiles", JSONObject().put(scope, JSONObject().put(comp, file)))
|
||||
.toString(),
|
||||
)
|
||||
}
|
||||
|
||||
private fun launchState() = File(LinuxRuntime.rootDir(context), "root/.local/share/droiddeck-components/desired.tsv")
|
||||
|
||||
private fun pendingState() = File(context.filesDir, "components/state.pending.json")
|
||||
|
||||
private fun writePendingState(state: JSONObject, launch: File) {
|
||||
pendingState().writeText(JSONObject()
|
||||
.put("state", state)
|
||||
.put("launchSha256", Hashes.sha256(launch))
|
||||
.toString())
|
||||
}
|
||||
|
||||
private fun original(protonName: String, version: String = "experimental-11") =
|
||||
File(context.filesDir, "components/originals/$protonName/$version/dxvk.wcp")
|
||||
|
||||
private fun assertDefaultDxvkRestoreRow(protonName: String, version: String = "experimental-11") {
|
||||
val row = launchState().readLines().map { it.split('\t') }.single {
|
||||
it.size == 7 && it[0] == "*" && it[1] == protonName && it[2] == version &&
|
||||
it[3] == "dxvk" && it[4].endsWith("/aarch64-windows/d3d11.dll")
|
||||
}
|
||||
assertNotEquals("-", row[6])
|
||||
val source = File(LinuxRuntime.rootDir(context), row[6].removePrefix("/"))
|
||||
assertEquals("bundled DXVK $version", source.readText())
|
||||
assertEquals(Hashes.sha256(source), row[5])
|
||||
assertTrue(original(protonName, version).isFile)
|
||||
val state = JSONObject(File(context.filesDir, "components/state.json").readText())
|
||||
assertEquals(listOf("dxvk"), state.getJSONArray("profiledComponents").let { values ->
|
||||
(0 until values.length()).map(values::getString)
|
||||
})
|
||||
}
|
||||
|
||||
private fun proton(name: String, version: String = "experimental-11", dxvk: Boolean = true) {
|
||||
val dir = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/steamapps/common/$name")
|
||||
File(dir, "files/lib/wine").mkdirs()
|
||||
File(dir, "proton").writeText("#!/bin/sh\n")
|
||||
File(dir, "version").writeText("1 $version\n")
|
||||
if (dxvk) File(dir, "files/lib/wine/dxvk/aarch64-windows/d3d11.dll").apply {
|
||||
parentFile!!.mkdirs()
|
||||
writeText("bundled DXVK $version")
|
||||
}
|
||||
}
|
||||
|
||||
private fun writeState(protonId: String, file: String, protonVersion: String) {
|
||||
|
||||
@@ -69,6 +69,91 @@ class GameEnvironmentStoreTest {
|
||||
SessionState.upscaleRatio = 0f
|
||||
}
|
||||
|
||||
@Test fun changingGameFexPresetPreservesDefaultAndOtherGameSettings() {
|
||||
SessionPrefs.setFexPreset(context, "PERFORMANCE_TSO")
|
||||
val original = GameEnvironment.withGameFexPreset(
|
||||
GameEnvironment.Config(
|
||||
shared = mapOf("PROTON_LOG" to "1"),
|
||||
games = mapOf("42" to mapOf("DXVK_HUD" to "fps")),
|
||||
),
|
||||
"43",
|
||||
"COMPATIBILITY",
|
||||
)
|
||||
GameEnvironmentStore.save(context, original)
|
||||
|
||||
GameEnvironmentStore.setGameFexPreset(context, "42", "STABILITY")
|
||||
|
||||
val saved = GameEnvironmentStore.read(context)
|
||||
assertEquals("STABILITY", GameEnvironment.gameFexPreset(saved, "42"))
|
||||
assertEquals("fps", saved.entries("42")["DXVK_HUD"])
|
||||
assertEquals(original.shared, saved.shared)
|
||||
assertEquals(original.entries("43"), saved.entries("43"))
|
||||
assertEquals("PERFORMANCE_TSO", SessionPrefs.fexPreset(context))
|
||||
val published = GameEnvironmentStore.decode(JSONObject(guest.readText()))
|
||||
assertEquals(saved.games, published.games)
|
||||
assertEquals("0", published.shared["FEX_HALFBARRIERTSOENABLED"])
|
||||
assertEquals("1", published.entries("42")["FEX_HALFBARRIERTSOENABLED"])
|
||||
}
|
||||
|
||||
@Test fun gameFexDefaultsAndInheritanceRemainDistinct() {
|
||||
SessionPrefs.setFexPreset(context, "EXTREME")
|
||||
val original = GameEnvironment.Config(
|
||||
games = mapOf("42" to mapOf("DXVK_HUD" to "fps")),
|
||||
)
|
||||
GameEnvironmentStore.save(context, original)
|
||||
|
||||
GameEnvironmentStore.setGameFexPreset(context, "42", "")
|
||||
|
||||
val explicitDefaults = GameEnvironmentStore.read(context)
|
||||
assertEquals("", GameEnvironment.gameFexPreset(explicitDefaults, "42"))
|
||||
val published = GameEnvironmentStore.decode(JSONObject(guest.readText()))
|
||||
assertTrue(published.entries("42").containsKey("FEX_SMCCHECKS"))
|
||||
assertNull(published.entries("42")["FEX_SMCCHECKS"])
|
||||
|
||||
GameEnvironmentStore.setGameFexPreset(context, "42", null)
|
||||
|
||||
assertEquals(original, GameEnvironmentStore.read(context))
|
||||
val inherited = GameEnvironmentStore.decode(JSONObject(guest.readText()))
|
||||
assertFalse(inherited.entries("42").containsKey("FEX_SMCCHECKS"))
|
||||
assertEquals("none", inherited.shared["FEX_SMCCHECKS"])
|
||||
assertEquals("EXTREME", SessionPrefs.fexPreset(context))
|
||||
}
|
||||
|
||||
@Test fun invalidGamePresetEditsCannotChangeSavedOrPublishedSettings() {
|
||||
val original = GameEnvironment.Config(shared = mapOf("PROTON_LOG" to "1"))
|
||||
GameEnvironmentStore.save(context, original)
|
||||
val published = guest.readText()
|
||||
|
||||
assertThrows(IllegalArgumentException::class.java) {
|
||||
GameEnvironmentStore.setGameFexPreset(context, "", "STABILITY")
|
||||
}
|
||||
assertThrows(IllegalArgumentException::class.java) {
|
||||
GameEnvironmentStore.setGameFexPreset(context, "42", GameEnvironment.CUSTOM_FEX_PRESET)
|
||||
}
|
||||
|
||||
assertEquals(original, GameEnvironmentStore.read(context))
|
||||
assertEquals(published, guest.readText())
|
||||
}
|
||||
|
||||
@Test fun targetedFexUpdateDoesNotRestoreEnvironmentClearedByACompletedReset() {
|
||||
val original = GameEnvironment.withGameFexPreset(
|
||||
GameEnvironment.Config(games = mapOf("42" to mapOf("DXVK_HUD" to "fps"))),
|
||||
"42",
|
||||
"COMPATIBILITY",
|
||||
)
|
||||
GameEnvironmentStore.save(context, original)
|
||||
val staleEditorSnapshot = GameEnvironmentStore.read(context)
|
||||
val resetEnvironment = staleEditorSnapshot.withEntries("42", emptyMap())
|
||||
GameEnvironmentStore.save(context, resetEnvironment)
|
||||
|
||||
GameEnvironmentStore.setGameFexPreset(context, "43", "PERFORMANCE_TSO")
|
||||
|
||||
val saved = GameEnvironmentStore.read(context)
|
||||
assertTrue(saved.entries("42").isEmpty())
|
||||
assertEquals("PERFORMANCE_TSO", GameEnvironment.gameFexPreset(saved, "43"))
|
||||
assertFalse(saved.games.containsKey("42"))
|
||||
}
|
||||
|
||||
@Test fun unchosenFexPresetPublishesPerformanceTso() {
|
||||
GameEnvironmentStore.save(context, GameEnvironment.Config())
|
||||
val shared = JSONObject(guest.readText()).getJSONObject("shared")
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class GameProfileFollowStateTest {
|
||||
@Test fun reopeningGamesPageResumesFollowingSteamAfterManualInspection() {
|
||||
val state = GameProfileFollowState()
|
||||
|
||||
state.selectManually()
|
||||
assertFalse(state.followsSteam)
|
||||
|
||||
state.resumeFollowingSteam()
|
||||
assertTrue(state.followsSteam)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertThrows
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import java.util.concurrent.CountDownLatch
|
||||
import java.util.concurrent.Executors
|
||||
import java.util.concurrent.TimeUnit
|
||||
|
||||
class GameProfileInventoryCacheTest {
|
||||
@Test
|
||||
fun loadsOnlyOncePerRevision() {
|
||||
val cache = GameProfileInventoryCache<String>()
|
||||
var loads = 0
|
||||
|
||||
assertEquals(listOf("one"), cache.get(0) { loads++; listOf("one") })
|
||||
assertEquals(listOf("one"), cache.get(0) { loads++; listOf("two") })
|
||||
assertEquals(1, loads)
|
||||
|
||||
assertEquals(listOf("two"), cache.get(1) { loads++; listOf("two") })
|
||||
assertEquals(2, loads)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun failedLoadIsRetriedInsteadOfCached() {
|
||||
val cache = GameProfileInventoryCache<String>()
|
||||
var loads = 0
|
||||
|
||||
assertThrows(IllegalStateException::class.java) {
|
||||
cache.get(0) { loads++; error("inventory unavailable") }
|
||||
}
|
||||
|
||||
assertEquals(listOf("recovered"), cache.get(0) { loads++; listOf("recovered") })
|
||||
assertEquals(2, loads)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun failedNewRevisionDoesNotReuseThePreviousInventory() {
|
||||
val cache = GameProfileInventoryCache<String>()
|
||||
assertEquals(listOf("old"), cache.get(0) { listOf("old") })
|
||||
|
||||
assertThrows(IllegalStateException::class.java) {
|
||||
cache.get(1) { error("inventory unavailable") }
|
||||
}
|
||||
|
||||
assertEquals(listOf("new"), cache.get(1) { listOf("new") })
|
||||
assertEquals(listOf("new"), cache.get(1) { error("should use cached inventory") })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun emptyInventoryIsCachedUntilTheRevisionChanges() {
|
||||
val cache = GameProfileInventoryCache<String>()
|
||||
|
||||
assertEquals(emptyList<String>(), cache.get(0) { emptyList() })
|
||||
assertEquals(emptyList<String>(), cache.get(0) { error("should use cached inventory") })
|
||||
assertEquals(listOf("installed"), cache.get(1) { listOf("installed") })
|
||||
}
|
||||
|
||||
@Test(timeout = 10_000)
|
||||
fun reopeningDuringAScanQueuesFreshInventoryWithoutWaitingAndRejectsOldResults() {
|
||||
data class Refresh(val appId: Long, val inventoryRevision: Long)
|
||||
|
||||
val cache = GameProfileInventoryCache<String>()
|
||||
val coordinator = LatestRequestCoordinator<Refresh>()
|
||||
val scanStarted = CountDownLatch(1)
|
||||
val finishScan = CountDownLatch(1)
|
||||
val worker = Executors.newSingleThreadExecutor()
|
||||
try {
|
||||
assertTrue(coordinator.submit(Refresh(42, 0)))
|
||||
val first = coordinator.takeLatest()!!
|
||||
val oldInventory = worker.submit<List<String>> {
|
||||
cache.get(first.value.inventoryRevision) {
|
||||
scanStarted.countDown()
|
||||
check(finishScan.await(5, TimeUnit.SECONDS))
|
||||
listOf("old")
|
||||
}
|
||||
}
|
||||
assertTrue(scanStarted.await(5, TimeUnit.SECONDS))
|
||||
|
||||
assertFalse(coordinator.submit(Refresh(42, 1)))
|
||||
assertFalse(oldInventory.isDone)
|
||||
assertFalse(coordinator.isLatest(first))
|
||||
|
||||
finishScan.countDown()
|
||||
assertEquals(listOf("old"), oldInventory.get(5, TimeUnit.SECONDS))
|
||||
assertFalse(coordinator.isLatest(first))
|
||||
val reopened = coordinator.takeLatest()!!
|
||||
val newInventory = worker.submit<List<String>> {
|
||||
cache.get(reopened.value.inventoryRevision) { listOf("new") }
|
||||
}
|
||||
assertEquals(listOf("new"), newInventory.get(5, TimeUnit.SECONDS))
|
||||
assertTrue(coordinator.isLatest(reopened))
|
||||
assertNull(coordinator.takeLatest())
|
||||
} finally {
|
||||
finishScan.countDown()
|
||||
worker.shutdownNow()
|
||||
assertTrue(worker.awaitTermination(5, TimeUnit.SECONDS))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.content.Context
|
||||
import com.droiddeck.launcher.core.GameEnvironment
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import org.json.JSONObject
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertThrows
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.RuntimeEnvironment
|
||||
import org.robolectric.annotation.Config
|
||||
import java.io.File
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [28], manifest = Config.NONE)
|
||||
class GameProfileManagerTest {
|
||||
private lateinit var context: Context
|
||||
|
||||
@Before
|
||||
fun setUp() {
|
||||
context = RuntimeEnvironment.getApplication()
|
||||
context.getSharedPreferences("session", Context.MODE_PRIVATE).edit().clear().commit()
|
||||
File(context.filesDir, "game-environment.json").delete()
|
||||
File(context.filesDir, "wincomponents.json").delete()
|
||||
File(context.filesDir, "components").deleteRecursively()
|
||||
File(LinuxRuntime.rootDir(context), "root/.local/share/droiddeck-compat").deleteRecursively()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun resetClearsOnlyTheSelectedGameProfile() {
|
||||
val game = "42"
|
||||
val other = "43"
|
||||
GameEnvironmentStore.save(
|
||||
context,
|
||||
GameEnvironment.Config(
|
||||
games = mapOf(
|
||||
game to mapOf("DXVK_HUD" to "fps"),
|
||||
other to mapOf("DXVK_HUD" to "compiler"),
|
||||
),
|
||||
),
|
||||
)
|
||||
ProtonDefault.requestGame(context, game, proton("game"))
|
||||
ProtonDefault.requestGame(context, other, proton("other"))
|
||||
seedComponentProfiles(game, other)
|
||||
SessionPrefs.setGameTextureAnisotropy(context, game, 4)
|
||||
SessionPrefs.setGameTextureAnisotropy(context, other, 8)
|
||||
WinComponents.setPicks(context, game, listOf("vcrun2022"))
|
||||
WinComponents.setPicks(context, other, listOf("dotnet48"))
|
||||
|
||||
GameProfileManager.reset(context, game)
|
||||
|
||||
val environment = GameEnvironmentStore.read(context)
|
||||
assertFalse(environment.games.containsKey(game))
|
||||
assertEquals("compiler", environment.entries(other)["DXVK_HUD"])
|
||||
assertNull(ProtonDefault.gameChoice(context, game))
|
||||
assertEquals("other", ProtonDefault.gameChoice(context, other)?.dir)
|
||||
assertEquals(emptyMap<String, String>(), ComponentsManager.gameComponents(context, game))
|
||||
assertEquals("other.wcp", ComponentsManager.gameComponents(context, other)["dxvk"])
|
||||
assertEquals(SessionPrefs.GameTextureFiltering(), SessionPrefs.gameTextureFiltering(context, game))
|
||||
assertEquals(8, SessionPrefs.gameTextureFiltering(context, other).anisotropy)
|
||||
assertEquals(emptyList<String>(), WinComponents.picks(context, game))
|
||||
assertEquals(listOf("dotnet48"), WinComponents.picks(context, other))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun resetRejectsEmptyScopeWithoutChangingSharedSettings() {
|
||||
GameEnvironmentStore.save(
|
||||
context,
|
||||
GameEnvironment.Config(shared = mapOf("DXVK_HUD" to "fps")),
|
||||
)
|
||||
|
||||
assertThrows(IllegalArgumentException::class.java) {
|
||||
GameProfileManager.reset(context, "")
|
||||
}
|
||||
assertEquals("fps", GameEnvironmentStore.read(context).shared["DXVK_HUD"])
|
||||
}
|
||||
|
||||
private fun proton(name: String) = ComponentsManager.Proton(
|
||||
id = name,
|
||||
name = name,
|
||||
dir = File(context.filesDir, name),
|
||||
guestPath = "/proton/$name",
|
||||
version = "1",
|
||||
valve = false,
|
||||
)
|
||||
|
||||
private fun seedComponentProfiles(game: String, other: String) {
|
||||
val components = File(context.filesDir, "components").apply { mkdirs() }
|
||||
File(components, "state.json").writeText(
|
||||
JSONObject().put(
|
||||
"profiles",
|
||||
JSONObject()
|
||||
.put(game, JSONObject().put("dxvk", "game.wcp"))
|
||||
.put(other, JSONObject().put("dxvk", "other.wcp")),
|
||||
).toString(),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class GameProfileRefreshStateTest {
|
||||
@Test
|
||||
fun firstFailureKeepsInitialStateWithoutCachedData() {
|
||||
val state = GameProfileRefreshState<String>().failed()
|
||||
|
||||
assertTrue(state.failed)
|
||||
assertFalse(state.loaded)
|
||||
assertNull(state.data)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun failureAfterSuccessPreservesCachedData() {
|
||||
val state = GameProfileRefreshState<String>().succeeded("cached profiles").failed()
|
||||
|
||||
assertTrue(state.failed)
|
||||
assertTrue(state.loaded)
|
||||
assertEquals("cached profiles", state.data)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun successAfterFailureReplacesCachedDataAndClearsWarning() {
|
||||
val state = GameProfileRefreshState<String>()
|
||||
.succeeded("old profiles")
|
||||
.failed()
|
||||
.succeeded("new profiles")
|
||||
|
||||
assertFalse(state.failed)
|
||||
assertTrue(state.loaded)
|
||||
assertEquals("new profiles", state.data)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun retryingClearsWarningWithoutDiscardingCachedData() {
|
||||
val state = GameProfileRefreshState<String>().succeeded("cached profiles").failed().retrying()
|
||||
|
||||
assertFalse(state.failed)
|
||||
assertTrue(state.loaded)
|
||||
assertEquals("cached profiles", state.data)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class LatestRequestCoordinatorTest {
|
||||
@Test fun coalescesPendingRequestsToTheLatestValue() {
|
||||
val coordinator = LatestRequestCoordinator<String>()
|
||||
|
||||
assertTrue(coordinator.submit("first"))
|
||||
val first = coordinator.takeLatest()!!
|
||||
assertFalse(coordinator.submit("second"))
|
||||
assertFalse(coordinator.submit("third"))
|
||||
|
||||
assertFalse(coordinator.isLatest(first))
|
||||
val latest = coordinator.takeLatest()!!
|
||||
assertEquals("third", latest.value)
|
||||
assertTrue(coordinator.isLatest(latest))
|
||||
assertNull(coordinator.takeLatest())
|
||||
}
|
||||
|
||||
@Test fun requestAfterWorkerBecomesIdleStartsAnotherWorker() {
|
||||
val coordinator = LatestRequestCoordinator<String>()
|
||||
|
||||
assertTrue(coordinator.submit("first"))
|
||||
coordinator.takeLatest()
|
||||
assertNull(coordinator.takeLatest())
|
||||
|
||||
assertTrue(coordinator.submit("second"))
|
||||
assertEquals("second", coordinator.takeLatest()!!.value)
|
||||
}
|
||||
|
||||
@Test fun newerRequestInvalidatesCompletedResultBeforeItIsApplied() {
|
||||
val coordinator = LatestRequestCoordinator<String>()
|
||||
|
||||
assertTrue(coordinator.submit("first"))
|
||||
val completed = coordinator.takeLatest()!!
|
||||
assertFalse(coordinator.submit("second"))
|
||||
|
||||
assertFalse(coordinator.isLatest(completed))
|
||||
assertEquals("second", coordinator.takeLatest()!!.value)
|
||||
}
|
||||
|
||||
@Test fun profileSwitchInvalidatesAnOlderFailedRefresh() {
|
||||
val coordinator = LatestRequestCoordinator<Long?>()
|
||||
|
||||
assertTrue(coordinator.submit(42L))
|
||||
val failedRefresh = coordinator.takeLatest()!!
|
||||
assertFalse(coordinator.submit(43L))
|
||||
|
||||
assertFalse(coordinator.isLatest(failedRefresh))
|
||||
assertEquals(43L, coordinator.takeLatest()!!.value)
|
||||
}
|
||||
|
||||
@Test fun repeatedPollDoesNotInvalidateEquivalentInFlightResult() {
|
||||
val coordinator = LatestRequestCoordinator<String>()
|
||||
|
||||
assertTrue(coordinator.submit("same"))
|
||||
val inFlight = coordinator.takeLatest()!!
|
||||
assertFalse(coordinator.submit("same"))
|
||||
|
||||
assertTrue(coordinator.isLatest(inFlight))
|
||||
assertEquals("same", coordinator.takeLatest()!!.value)
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNull
|
||||
@@ -7,6 +8,7 @@ import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.RuntimeEnvironment
|
||||
import java.io.File
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@@ -59,4 +61,46 @@ class ProtonDefaultTest {
|
||||
assertNull(ProtonDefault.chosen(ProtonDefault.parseState("{"), ProtonDefault.parseRequest("[]")))
|
||||
assertNull(ProtonDefault.parseRequest("""{"seq": 0, "dir": "x"}"""))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun perGameChoicesPreserveCustomizeAndInheritSemantics() {
|
||||
val games = ProtonDefault.parseGames(
|
||||
"""{"version":1,"games":{"42":{"valve":false,"dir":"GE-Proton11-7"},"43":null,"0":null,"bad":{},"44":{"valve":"false","dir":"GE-Proton9-1"}}}""",
|
||||
)
|
||||
assertEquals(ProtonDefault.GameChoice(false, "GE-Proton11-7"), games["42"])
|
||||
assertTrue(games.containsKey("43"))
|
||||
assertNull(games["43"])
|
||||
assertFalse(games.containsKey("0"))
|
||||
assertFalse(games.containsKey("bad"))
|
||||
assertFalse(games.containsKey("44"))
|
||||
assertTrue(ProtonDefault.parseGames("""{"version":2,"games":{"42":null}}""").isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun perGameRequestsPersistCustomizeThenInherit() {
|
||||
val context = RuntimeEnvironment.getApplication()
|
||||
val file = File(LinuxRuntime.rootDir(context), "root/.local/share/droiddeck-compat/games.json")
|
||||
file.parentFile?.deleteRecursively()
|
||||
val selected = proton("GE-Proton11-7", false)
|
||||
|
||||
ProtonDefault.requestGame(context, "42", selected)
|
||||
assertEquals(ProtonDefault.GameChoice(false, "GE-Proton11-7"), ProtonDefault.parseGames(file.readText())["42"])
|
||||
|
||||
ProtonDefault.requestGame(context, "42", null)
|
||||
val inherited = ProtonDefault.parseGames(file.readText())
|
||||
assertTrue(inherited.containsKey("42"))
|
||||
assertNull(inherited["42"])
|
||||
}
|
||||
|
||||
@Test
|
||||
fun missingPerGameProtonIdentityRemainsStoredButUnresolved() {
|
||||
val context = RuntimeEnvironment.getApplication()
|
||||
val file = File(LinuxRuntime.rootDir(context), "root/.local/share/droiddeck-compat/games.json")
|
||||
file.parentFile?.deleteRecursively()
|
||||
ProtonDefault.requestGame(context, "42", proton("GE-Proton9-1", false))
|
||||
|
||||
assertEquals(ProtonDefault.GameChoice(false, "GE-Proton9-1"), ProtonDefault.gameChoice(context, "42"))
|
||||
assertNull(ProtonDefault.gameSelectedId(context, "42", listOf(proton("GE-Proton11-7", false))))
|
||||
assertEquals(ProtonDefault.GameChoice(false, "GE-Proton9-1"), ProtonDefault.parseGames(file.readText())["42"])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.rules.TemporaryFolder
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.RuntimeEnvironment
|
||||
import org.robolectric.annotation.Config
|
||||
import java.io.File
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [28], manifest = Config.NONE)
|
||||
class ProtonExtrasTest {
|
||||
@get:Rule val temp = TemporaryFolder()
|
||||
|
||||
private fun tool(id: String) = ProtonExtras.tools.single { it.id == id }
|
||||
|
||||
private fun asset(name: String, digest: String? = null) = JSONObject()
|
||||
.put("name", name)
|
||||
.put("browser_download_url", "https://github.com/o/r/releases/download/t/$name")
|
||||
.put("size", 625_775_670L)
|
||||
.apply { if (digest != null) put("digest", digest) }
|
||||
|
||||
private fun release(tag: String, vararg assets: JSONObject, prerelease: Boolean = false, draft: Boolean = false) = JSONObject()
|
||||
.put("tag_name", tag).put("prerelease", prerelease).put("draft", draft)
|
||||
.put("assets", JSONArray().apply { assets.forEach { put(it) } })
|
||||
|
||||
private fun droiddeckRelease(ver: String, prerelease: Boolean = false) = release(
|
||||
"DroidDeck-Proton-$ver",
|
||||
asset("DroidDeck-Proton-$ver-aarch64.build-info.json"),
|
||||
asset("DroidDeck-Proton-$ver-aarch64.sha512sum"),
|
||||
asset("DroidDeck-Proton-$ver-aarch64.tar.gz"),
|
||||
prerelease = prerelease,
|
||||
)
|
||||
|
||||
private fun installTool(parent: File, name: String) = File(parent, name).apply {
|
||||
mkdirs()
|
||||
File(this, "toolmanifest.vdf").writeText("\"manifest\" { \"commandline\" \"/proton %verb%\" }")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun theThreeSourcesInOrder() {
|
||||
assertEquals(listOf("ge", "cachyos", "droiddeck"), ProtonExtras.tools.map { it.id })
|
||||
val droiddeck = tool("droiddeck")
|
||||
assertEquals("DroidDeck-Proton", droiddeck.name)
|
||||
assertEquals("DroidDeck-Proton", droiddeck.prefix)
|
||||
assertEquals("The412Banner/DroidDeck-Proton", droiddeck.repo)
|
||||
assertTrue(droiddeck.assetPattern.containsMatchIn("DroidDeck-Proton-11-7.5-aarch64.tar.gz"))
|
||||
assertTrue(droiddeck.assetPattern.containsMatchIn("DroidDeck-Proton-11-8-aarch64.tar.xz"))
|
||||
assertFalse(droiddeck.assetPattern.containsMatchIn("DroidDeck-Proton-11-7.5-aarch64.sha512sum"))
|
||||
assertFalse(droiddeck.assetPattern.containsMatchIn("DroidDeck-Proton-11-7.5-aarch64.build-info.json"))
|
||||
assertFalse(tool("cachyos").assetPattern.containsMatchIn("proton-cachyos-11.0-20261005-slr-x86_64.tar.xz"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun theTarballAndItsSha512FileArePicked() {
|
||||
val picked = ProtonExtras.pickAsset(tool("droiddeck"), JSONArray().put(droiddeckRelease("11-7.5")))!!
|
||||
assertEquals("DroidDeck-Proton-11-7.5", picked.tag)
|
||||
assertEquals("DroidDeck-Proton-11-7.5-aarch64.tar.gz", picked.name)
|
||||
assertEquals("https://github.com/o/r/releases/download/t/DroidDeck-Proton-11-7.5-aarch64.sha512sum", picked.sha512)
|
||||
assertEquals(625_775_670L, picked.size)
|
||||
assertNull(picked.sha256)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun githubsDigestIsKeptBesideTheSha512File() {
|
||||
val sum = "ab".repeat(32)
|
||||
val release = release("GE-Proton11-7", asset("GE-Proton11-7-x86_64.tar.gz"), asset("GE-Proton11-7-aarch64.sha512sum"),
|
||||
asset("GE-Proton11-7-aarch64.tar.gz", "sha256:$sum"))
|
||||
val picked = ProtonExtras.pickAsset(tool("ge"), JSONArray().put(release))!!
|
||||
assertEquals("GE-Proton11-7-aarch64.tar.gz", picked.name)
|
||||
assertEquals(sum, picked.sha256)
|
||||
assertTrue(picked.sha512!!.endsWith("GE-Proton11-7-aarch64.sha512sum"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun prereleasesDraftsAndReleasesWithoutAnArm64BuildAreSkipped() {
|
||||
val releases = JSONArray()
|
||||
.put(droiddeckRelease("11-8", prerelease = true))
|
||||
.put(release("DroidDeck-Proton-11-7.9", asset("DroidDeck-Proton-11-7.9-aarch64.tar.gz"), draft = true))
|
||||
.put(release("DroidDeck-Proton-11-7.8", asset("DroidDeck-Proton-11-7.8-x86_64.tar.gz")))
|
||||
.put(droiddeckRelease("11-7.5"))
|
||||
assertEquals("DroidDeck-Proton-11-7.5", ProtonExtras.pickAsset(tool("droiddeck"), releases)?.tag)
|
||||
assertNull(ProtonExtras.pickAsset(tool("droiddeck"), JSONArray().put(droiddeckRelease("11-8", prerelease = true))))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun versionsCompareByTheirNumbers() {
|
||||
val sorted = listOf("GE-Proton11-10", "GE-Proton10-25", "GE-Proton11-9", "GE-Proton11-1")
|
||||
.sortedWith { a, b -> ProtonExtras.compareVersions(a, b) }
|
||||
assertEquals(listOf("GE-Proton10-25", "GE-Proton11-1", "GE-Proton11-9", "GE-Proton11-10"), sorted)
|
||||
assertTrue(ProtonExtras.compareVersions("DroidDeck-Proton 11-7.5", "DroidDeck-Proton 11-7.10") < 0)
|
||||
assertTrue(ProtonExtras.compareVersions("DroidDeck-Proton 11-7.10", "DroidDeck-Proton 11-8") < 0)
|
||||
assertTrue(ProtonExtras.compareVersions("DroidDeck-Proton 11-7", "DroidDeck-Proton 11-7.1") < 0)
|
||||
assertTrue(ProtonExtras.compareVersions("cachyos-11.0-20260703-slr", "cachyos-11.0-20261005-slr") < 0)
|
||||
assertTrue(ProtonExtras.compareVersions("cachyos-10.0-sunset-slr", "cachyos-11.0-20260601-slr") < 0)
|
||||
// The architecture in a folder name is not part of its version.
|
||||
assertEquals(listOf(11L, 7L), ProtonExtras.versionKey("GE-Proton11-7-aarch64"))
|
||||
assertEquals(listOf(11L, 0L, 20261005L), ProtonExtras.versionKey("proton-cachyos-11.0-20261005-slr-arm64"))
|
||||
assertEquals(listOf(11L, 7L, 5L), ProtonExtras.versionKey("DroidDeck-Proton 11-7.5"))
|
||||
assertEquals(ProtonExtras.versionKey("DroidDeck-Proton-11-7.5"), ProtonExtras.versionKey("DroidDeck-Proton 11-7.5"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun installedBuildsAreFoundByPrefixNewestLast() {
|
||||
val tools = temp.newFolder("compatibilitytools.d")
|
||||
for (name in listOf("GE-Proton11-10", "GE-Proton11-9", "DroidDeck-Proton 11-7.10", "DroidDeck-Proton 11-7.5",
|
||||
"droiddeck-proton-arm64", "droiddeck-proton-11-arm64", "proton-cachyos-11.0-20261005-slr-arm64")) installTool(tools, name)
|
||||
File(tools, "DroidDeck-Proton 11-6").mkdirs() // no manifest: half unpacked, not installed
|
||||
assertEquals(listOf("GE-Proton11-9", "GE-Proton11-10"), ProtonExtras.installedIn(tools, tool("ge")))
|
||||
// Ours, not DroidDeck's own droiddeck-proton-* tools: the prefix is matched with its case.
|
||||
assertEquals(listOf("DroidDeck-Proton 11-7.5", "DroidDeck-Proton 11-7.10"), ProtonExtras.installedIn(tools, tool("droiddeck")))
|
||||
assertEquals(listOf("proton-cachyos-11.0-20261005-slr-arm64"), ProtonExtras.installedIn(tools, tool("cachyos")))
|
||||
assertEquals(emptyList<String>(), ProtonExtras.installedIn(File(tools, "missing"), tool("ge")))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun anUpdateIsANewerReleaseThanTheNewestInstalledBuild() {
|
||||
assertEquals("DroidDeck-Proton-11-7.6", ProtonExtras.updateFor(listOf("DroidDeck-Proton 11-7.5"), "DroidDeck-Proton-11-7.6"))
|
||||
assertEquals("DroidDeck-Proton-11-7.10", ProtonExtras.updateFor(listOf("DroidDeck-Proton-11-7.9"), "DroidDeck-Proton-11-7.10"))
|
||||
assertNull(ProtonExtras.updateFor(listOf("DroidDeck-Proton 11-7.5"), "DroidDeck-Proton-11-7.5"))
|
||||
assertNull(ProtonExtras.updateFor(listOf("DroidDeck-Proton 11-7.5", "DroidDeck-Proton-11-7.6"), "DroidDeck-Proton-11-7.6"))
|
||||
assertNull(ProtonExtras.updateFor(listOf("GE-Proton11-10"), "GE-Proton11-9"))
|
||||
assertNull(ProtonExtras.updateFor(listOf("GE-Proton11-7-aarch64"), "GE-Proton11-7"))
|
||||
assertEquals("GE-Proton11-10", ProtonExtras.updateFor(listOf("GE-Proton11-7-aarch64", "GE-Proton11-9"), "GE-Proton11-10"))
|
||||
assertEquals("cachyos-11.0-20261101-slr", ProtonExtras.updateFor(listOf("proton-cachyos-11.0-20261005-slr-arm64"), "cachyos-11.0-20261101-slr"))
|
||||
assertNull(ProtonExtras.updateFor(listOf("proton-cachyos-11.0-20261005-slr-arm64"), "cachyos-10.0-sunset-slr"))
|
||||
assertNull(ProtonExtras.updateFor(emptyList(), "GE-Proton11-10"))
|
||||
assertNull(ProtonExtras.updateFor(listOf("GE-Proton11-7"), null))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aRecentCheckIsReusedAndComparedWithTheInstalledBuild() {
|
||||
val context = RuntimeEnvironment.getApplication()
|
||||
val tools = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/compatibilitytools.d")
|
||||
installTool(tools, "DroidDeck-Proton 11-7.5")
|
||||
installTool(tools, "GE-Proton11-7")
|
||||
val now = 1_800_000_000_000L
|
||||
val latest = JSONObject()
|
||||
.put("ge", JSONObject().put("tag", "GE-Proton11-7").put("at", now - 60_000))
|
||||
.put("cachyos", JSONObject().put("tag", "cachyos-11.0-20261005-slr").put("at", now - 60_000))
|
||||
.put("droiddeck", JSONObject().put("tag", "DroidDeck-Proton-11-7.6").put("at", now - ProtonExtras.CHECK_EVERY_MS + 60_000))
|
||||
File(context.filesDir, "proton-latest.json").writeText(latest.toString())
|
||||
// Every source was looked up within the last six hours: nothing goes to GitHub.
|
||||
assertFalse(ProtonExtras.checkLatest(context, now = now))
|
||||
assertEquals("DroidDeck-Proton-11-7.6", ProtonExtras.update(context, tool("droiddeck")))
|
||||
assertNull(ProtonExtras.update(context, tool("ge")))
|
||||
assertNull(ProtonExtras.update(context, tool("cachyos")))
|
||||
assertEquals(listOf("DroidDeck-Proton 11-7.5"), ProtonExtras.installedTags(context, tool("droiddeck")))
|
||||
// The tag recorded at install stands for the folder.
|
||||
File(context.filesDir, "proton-extras.json").writeText(JSONObject().put("DroidDeck-Proton 11-7.5", "DroidDeck-Proton-11-7.6").toString())
|
||||
assertEquals(listOf("DroidDeck-Proton-11-7.6"), ProtonExtras.installedTags(context, tool("droiddeck")))
|
||||
assertNull(ProtonExtras.update(context, tool("droiddeck")))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun removingDeletesOneBuildOrEveryOlderOne() {
|
||||
val context = RuntimeEnvironment.getApplication()
|
||||
val tools = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/compatibilitytools.d")
|
||||
for (name in listOf("DroidDeck-Proton 11-7.5", "DroidDeck-Proton 11-7.6", "DroidDeck-Proton 11-7.10", "GE-Proton11-7")) installTool(tools, name)
|
||||
ProtonExtras.remove(context, tool("droiddeck"), "DroidDeck-Proton 11-7.6")
|
||||
assertEquals(listOf("DroidDeck-Proton 11-7.5", "DroidDeck-Proton 11-7.10"), ProtonExtras.installedAll(context, tool("droiddeck")))
|
||||
// A folder of another source is never removed through this one.
|
||||
ProtonExtras.remove(context, tool("droiddeck"), "GE-Proton11-7")
|
||||
assertTrue(File(tools, "GE-Proton11-7").isDirectory)
|
||||
assertEquals(listOf("DroidDeck-Proton 11-7.5", "DroidDeck-Proton 11-7.10"), ProtonExtras.installedAll(context, tool("droiddeck")))
|
||||
ProtonExtras.removeOlder(context, tool("droiddeck"))
|
||||
assertEquals(listOf("DroidDeck-Proton 11-7.10"), ProtonExtras.installedAll(context, tool("droiddeck")))
|
||||
assertEquals("DroidDeck-Proton 11-7.10", ProtonExtras.installed(context, tool("droiddeck")))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.content.Context
|
||||
import android.content.ContextWrapper
|
||||
import com.droiddeck.launcher.runtime.BwrapSpawner
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.RuntimeEnvironment
|
||||
import org.robolectric.annotation.Config
|
||||
import org.robolectric.shadows.ShadowBuild
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [28], manifest = Config.NONE)
|
||||
class QuestExperimentalTest {
|
||||
private val context: Context get() = RuntimeEnvironment.getApplication()
|
||||
|
||||
@Before fun reset() {
|
||||
context.getSharedPreferences("session", Context.MODE_PRIVATE).edit().clear().commit()
|
||||
ShadowBuild.setModel("Phone")
|
||||
ShadowBuild.setDevice("phone")
|
||||
}
|
||||
|
||||
@Test fun otherDevicesAndQuest2KeepTheirSettings() {
|
||||
for (model in listOf("Phone", "Quest 2")) {
|
||||
ShadowBuild.setModel(model)
|
||||
QuestExperimental.initialize(context)
|
||||
assertEquals(SessionPrefs.GPU_DRIVERS_AUTO, SessionPrefs.gpuDriverMode(context))
|
||||
assertEquals("", SessionPrefs.androidDriver(context))
|
||||
assertFalse(SessionPrefs.hdr(context, "steam"))
|
||||
}
|
||||
assertFalse(QuestExperimental.supported("Quest 2", "hollywood", "Oculus"))
|
||||
}
|
||||
|
||||
@Test fun questDefaultsSelectBothCompatibilityPathsAndAreAppliedOnlyOnce() {
|
||||
ShadowBuild.setModel("Quest 3")
|
||||
QuestExperimental.initialize(context)
|
||||
assertEquals(SessionPrefs.GPU_DRIVERS_MANUAL, SessionPrefs.gpuDriverMode(context))
|
||||
assertEquals(QuestExperimental.DRIVER, SessionPrefs.androidDriver(context))
|
||||
assertEquals("", SessionPrefs.linuxDriver(context))
|
||||
assertTrue(SessionPrefs.hdr(context, "steam"))
|
||||
assertTrue(context.filesDir.resolve("quest-startup.txt").readText().contains("model=Quest 3"))
|
||||
SessionPrefs.setAndroidDriver(context, "chosen-driver")
|
||||
SessionPrefs.setHdr(context, "steam", false)
|
||||
QuestExperimental.initialize(context)
|
||||
assertEquals("chosen-driver", SessionPrefs.androidDriver(context))
|
||||
assertFalse(SessionPrefs.hdr(context, "steam"))
|
||||
}
|
||||
|
||||
@Test fun quest3sIsRecognizedByModelOrDevice() {
|
||||
assertTrue(QuestExperimental.supported("Quest 3S", "unknown", "Oculus"))
|
||||
assertTrue(QuestExperimental.supported("unknown", "panther", "Oculus"))
|
||||
assertTrue(QuestExperimental.supported("unknown", "eureka", "Meta"))
|
||||
assertFalse(QuestExperimental.supported("Pixel 7", "panther", "Google"))
|
||||
}
|
||||
|
||||
@Test fun installedPackagesUseSeparateSandboxSockets() {
|
||||
val quest = object : ContextWrapper(context) {
|
||||
override fun getPackageName() = "com.droiddeck.quest"
|
||||
}
|
||||
assertEquals("com.droiddeck.quest.bwrap", BwrapSpawner.socket(quest))
|
||||
assertNotEquals(BwrapSpawner.socket(context), BwrapSpawner.socket(quest))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import com.droiddeck.launcher.core.GameEnvironment
|
||||
import com.droiddeck.launcher.frontend.Library
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import java.io.File
|
||||
|
||||
class SelectedGameProfileTest {
|
||||
private val proton = ComponentsManager.Proton("p1", "Proton 10", File("p1"), "/p1", "10", true)
|
||||
private val snapshot = ComponentsManager.Snapshot(
|
||||
protons = listOf(
|
||||
ComponentsManager.ProtonView(
|
||||
proton = proton,
|
||||
components = mapOf(
|
||||
"fex" to component("FEX General"),
|
||||
"dxvk" to component("DXVK General"),
|
||||
"vkd3d" to component("VKD3D General"),
|
||||
),
|
||||
originals = emptyList(),
|
||||
inUseByGame = false,
|
||||
),
|
||||
),
|
||||
packages = listOf(ComponentsManager.Package("dxvk.wcp", "dxvk", "DXVK Game", "", 1)),
|
||||
)
|
||||
private val game = Library.SteamGame(3180310, "Billies Wheelie", null, "internal")
|
||||
|
||||
@Test fun inheritedValuesUseGeneralProfile() {
|
||||
val profile = resolve()
|
||||
|
||||
assertEquals("Billies Wheelie", profile!!.name)
|
||||
assertEquals("PERFORMANCE_TSO", profile.fexPreset.value)
|
||||
assertTrue(profile.fexPreset.inherited)
|
||||
assertEquals("Proton 10", profile.proton.value)
|
||||
assertTrue(profile.proton.inherited)
|
||||
assertEquals("p1", profile.protonId)
|
||||
assertEquals("DXVK General", profile.components.getValue("dxvk").value)
|
||||
assertTrue(profile.components.getValue("dxvk").inherited)
|
||||
assertEquals(emptyMap<String, String>(), profile.componentFiles)
|
||||
assertEquals(0, profile.environmentOverrides)
|
||||
assertEquals(emptyList<String>(), profile.windowsComponentNames)
|
||||
assertFalse(profile.hasOverrides)
|
||||
}
|
||||
|
||||
@Test fun explicitValuesOverrideGeneralProfile() {
|
||||
val preset = GameEnvironment.withGameFexPreset(GameEnvironment.Config(), game.profileKey, "STABILITY")
|
||||
val environment = preset.withEntries(game.profileKey, preset.entries(game.profileKey) + ("PROTON_LOG" to "1"))
|
||||
val profile = resolve(
|
||||
environment = environment,
|
||||
gameChoice = ProtonDefault.GameChoice(true, "p1"),
|
||||
gameComponents = mapOf("dxvk" to "dxvk.wcp"),
|
||||
)
|
||||
|
||||
assertEquals("STABILITY", profile!!.fexPreset.value)
|
||||
assertFalse(profile.fexPreset.inherited)
|
||||
assertFalse(profile.proton.inherited)
|
||||
assertEquals("DXVK Game", profile.components.getValue("dxvk").value)
|
||||
assertFalse(profile.components.getValue("dxvk").inherited)
|
||||
assertEquals("dxvk.wcp", profile.componentFiles.getValue("dxvk"))
|
||||
assertEquals(1, profile.environmentOverrides)
|
||||
assertTrue(profile.hasOverrides)
|
||||
}
|
||||
|
||||
@Test fun windowsComponentsMakeProfileCustom() {
|
||||
val profile = resolve(gameWindowsComponents = listOf("oalinst_dll", "vcredist2010_dll"))
|
||||
|
||||
assertEquals(listOf("OpenAL", "Visual C++ 2010"), profile!!.windowsComponentNames)
|
||||
assertTrue(profile.hasOverrides)
|
||||
}
|
||||
|
||||
@Test fun unknownSelectedAppIsIgnored() {
|
||||
assertNull(resolve(selectedAppId = 42))
|
||||
}
|
||||
|
||||
@Test fun switchingProfilesResolvesEachGamesFexPresetWithoutChangingSettings() {
|
||||
val other = Library.SteamGame(42, "Other game", null, "internal")
|
||||
val games = listOf(game, other)
|
||||
val environment = GameEnvironment.withGameFexPreset(
|
||||
GameEnvironment.Config(), game.profileKey, "STABILITY",
|
||||
)
|
||||
|
||||
assertEquals(ProfileValue("STABILITY", false),
|
||||
resolve(games = games, environment = environment)!!.fexPreset)
|
||||
assertEquals(ProfileValue("PERFORMANCE_TSO", true),
|
||||
resolve(selectedAppId = 42, games = games, environment = environment)!!.fexPreset)
|
||||
assertEquals(ProfileValue("STABILITY", false),
|
||||
resolve(games = games, environment = environment)!!.fexPreset)
|
||||
assertNull(GameEnvironment.gameFexPreset(environment, other.profileKey))
|
||||
}
|
||||
|
||||
@Test fun customAndExplicitDefaultFexPresetsAreNotShownAsInherited() {
|
||||
val custom = GameEnvironment.Config(
|
||||
games = mapOf(game.profileKey to mapOf("FEX_TSOENABLED" to "0")),
|
||||
)
|
||||
assertEquals(ProfileValue(GameEnvironment.CUSTOM_FEX_PRESET, false),
|
||||
resolve(environment = custom)!!.fexPreset)
|
||||
val defaults = GameEnvironment.withGameFexPreset(custom, game.profileKey, "")
|
||||
assertEquals(ProfileValue("", false), resolve(environment = defaults)!!.fexPreset)
|
||||
val inherited = GameEnvironment.withGameFexPreset(defaults, game.profileKey, null)
|
||||
assertEquals(ProfileValue("PERFORMANCE_TSO", true), resolve(environment = inherited)!!.fexPreset)
|
||||
}
|
||||
|
||||
private fun resolve(
|
||||
selectedAppId: Long = 3180310,
|
||||
games: List<Library.SteamGame> = listOf(game),
|
||||
environment: GameEnvironment.Config = GameEnvironment.Config(),
|
||||
gameChoice: ProtonDefault.GameChoice? = null,
|
||||
gameComponents: Map<String, String> = emptyMap(),
|
||||
gameWindowsComponents: List<String> = emptyList(),
|
||||
) = SelectedGameProfile.resolve(
|
||||
selectedAppId = selectedAppId,
|
||||
games = games,
|
||||
generalFexPreset = "PERFORMANCE_TSO",
|
||||
environment = environment,
|
||||
snapshot = snapshot,
|
||||
generalProtonId = "p1",
|
||||
gameProtonChoice = gameChoice,
|
||||
gameProtonId = "p1",
|
||||
gameComponents = gameComponents,
|
||||
gameWindowsComponents = gameWindowsComponents,
|
||||
)
|
||||
|
||||
private fun component(label: String) =
|
||||
ComponentsManager.Component(label, "", "Changed outside Components", label, null, null)
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.content.Context
|
||||
import com.droiddeck.launcher.core.TextureFiltering
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import org.json.JSONObject
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.RuntimeEnvironment
|
||||
import org.robolectric.annotation.Config
|
||||
import java.io.File
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [28], manifest = Config.NONE)
|
||||
class TextureFilteringPrefsTest {
|
||||
private lateinit var context: Context
|
||||
|
||||
@Before fun setUp() {
|
||||
context = RuntimeEnvironment.getApplication()
|
||||
context.getSharedPreferences("session", Context.MODE_PRIVATE).edit().clear().commit()
|
||||
File(context.filesDir, "game-environment.json").delete()
|
||||
File(LinuxRuntime.rootDir(context), "root/.config/droiddeck/game-environment.json").delete()
|
||||
}
|
||||
|
||||
@Test fun gameChoicesRemainSeparateFromDefaultAndCanInheritAgain() {
|
||||
SessionPrefs.setTextureAnisotropy(context, 16)
|
||||
SessionPrefs.setTextureLodBias(context, TextureFiltering.LOD_BIAS_AUTO)
|
||||
SessionPrefs.setGameTextureAnisotropy(context, "42", 4)
|
||||
SessionPrefs.setGameTextureLodBias(context, "42", "-0.5")
|
||||
|
||||
assertEquals(16, SessionPrefs.textureAnisotropy(context))
|
||||
assertEquals(TextureFiltering.LOD_BIAS_AUTO, SessionPrefs.textureLodBias(context))
|
||||
assertEquals(SessionPrefs.GameTextureFiltering(4, "-0.5"), SessionPrefs.gameTextureFiltering(context, "42"))
|
||||
assertEquals(SessionPrefs.GameTextureFiltering(), SessionPrefs.gameTextureFiltering(context, "43"))
|
||||
|
||||
SessionPrefs.setGameTextureAnisotropy(context, "42", null)
|
||||
SessionPrefs.setGameTextureLodBias(context, "42", null)
|
||||
|
||||
assertEquals(SessionPrefs.GameTextureFiltering(), SessionPrefs.gameTextureFiltering(context, "42"))
|
||||
assertFalse(SessionPrefs.gameTextureFiltering(context).containsKey("42"))
|
||||
}
|
||||
|
||||
@Test fun publishedDxvkOptionsUseGameOverridesWithoutChangingDefault() {
|
||||
SessionPrefs.setTextureAnisotropy(context, 16)
|
||||
SessionPrefs.setGameTextureAnisotropy(context, "42", 0)
|
||||
SessionPrefs.setGameTextureLodBias(context, "42", TextureFiltering.LOD_BIAS_OFF)
|
||||
|
||||
val published = JSONObject(
|
||||
File(LinuxRuntime.rootDir(context), "root/.config/droiddeck/game-environment.json").readText(),
|
||||
)
|
||||
assertTrue(published.getString(GameEnvironmentStore.DXVK_CONFIG).contains("samplerAnisotropy = 16"))
|
||||
assertEquals("", published.getJSONObject(GameEnvironmentStore.DXVK_CONFIG_GAMES).getString("42"))
|
||||
assertNull(SessionPrefs.gameTextureFiltering(context, "43").anisotropy)
|
||||
}
|
||||
|
||||
@Test fun clearingGameChoicesPreservesOtherProfiles() {
|
||||
SessionPrefs.setGameTextureAnisotropy(context, "42", 4)
|
||||
SessionPrefs.setGameTextureLodBias(context, "42", "-0.5")
|
||||
SessionPrefs.setGameTextureAnisotropy(context, "43", 8)
|
||||
|
||||
SessionPrefs.clearGameTextureFiltering(context, "42")
|
||||
|
||||
assertEquals(SessionPrefs.GameTextureFiltering(), SessionPrefs.gameTextureFiltering(context, "42"))
|
||||
assertEquals(8, SessionPrefs.gameTextureFiltering(context, "43").anisotropy)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package com.droiddeck.launcher.stores.epic
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNotNull
|
||||
import org.junit.Assert.assertThrows
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.annotation.Config
|
||||
|
||||
/** The JSON manifest's numbers are blobs; the same values as the Rust engine's manifest tests. */
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [33])
|
||||
class EpicJsonManifestTest {
|
||||
@Test
|
||||
fun blobNumbersAreDecimalBytesLeastSignificantFirst() {
|
||||
assertEquals(1L, EpicDownloadManager.blobToNum("001000000000"))
|
||||
assertEquals(0x100L, EpicDownloadManager.blobToNum("000001000000"))
|
||||
assertEquals(0x0807_0605_0403_0201L, EpicDownloadManager.blobToNum("001002003004005006007008"))
|
||||
assertEquals(-1L, EpicDownloadManager.blobToNum("255255255255255255255255"))
|
||||
assertEquals(7L, EpicDownloadManager.blobToNum("7"))
|
||||
assertEquals(0L, EpicDownloadManager.blobToNum(""))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aBlobIsDigitsOnly() {
|
||||
assertThrows(NumberFormatException::class.java) { EpicDownloadManager.blobToNum("0x1") }
|
||||
assertThrows(NumberFormatException::class.java) { EpicDownloadManager.blobToNum("-05") }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun jsonManifestUsesBlobs() {
|
||||
val json = """{
|
||||
"ManifestFileVersion": "006000000000",
|
||||
"LaunchExeString": "Game\\Binaries\\Game.exe",
|
||||
"ChunkHashList": { "0000000100000002000000030000000F": "001002003004005006007008" },
|
||||
"DataGroupList": { "0000000100000002000000030000000F": "007" },
|
||||
"ChunkFilesizeList": { "0000000100000002000000030000000F": "001002000000000000000000" },
|
||||
"FileManifestList": [
|
||||
{ "Filename": "a.bin",
|
||||
"FileChunkParts": [ { "Guid": "0000000100000002000000030000000F", "Offset": "001000000000", "Size": "000000016000" } ] }
|
||||
]
|
||||
}"""
|
||||
val m = EpicDownloadManager.parseManifest(json.toByteArray())
|
||||
assertNotNull(m)
|
||||
assertEquals("ChunksV3", m.chunkDir)
|
||||
assertEquals("Game/Binaries/Game.exe", m.launchExe)
|
||||
val c = m.uniqueChunks.single()
|
||||
assertEquals(0x0201L, c.fileSize)
|
||||
assertEquals("ChunksV3/07/0807060504030201_0000000100000002000000030000000F.chunk", c.getPath(m.chunkDir))
|
||||
val part = m.files.single().parts.single()
|
||||
assertEquals(1, part.offset)
|
||||
assertEquals(1_048_576, part.size)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.ui.test.onNodeWithText
|
||||
import androidx.compose.ui.test.performClick
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.frontend.Library
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.RuntimeEnvironment
|
||||
import org.robolectric.annotation.Config
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [28])
|
||||
class ComponentsPageProfileTest {
|
||||
@get:Rule val compose = createRobolectricComposeRule()
|
||||
|
||||
@Test fun gameProfilesCoexistWithTheDefaultComponentStack() {
|
||||
val context = RuntimeEnvironment.getApplication()
|
||||
compose.setContent {
|
||||
DroidDeckTheme {
|
||||
ComponentsPage(
|
||||
snapshot = null,
|
||||
catalog = emptyList(),
|
||||
catalogAt = 0,
|
||||
protonId = null,
|
||||
comp = PROTON_TAB,
|
||||
checking = false,
|
||||
busy = null,
|
||||
downloads = emptyMap(),
|
||||
onProton = {},
|
||||
onComp = {},
|
||||
onSwap = {},
|
||||
onRestore = {},
|
||||
onCancelQueued = {},
|
||||
onDeletePackage = {},
|
||||
onDeleteOriginal = {},
|
||||
onDownload = {},
|
||||
onRefresh = {},
|
||||
onImport = {},
|
||||
onBack = {},
|
||||
games = listOf(Library.SteamGame(42, "Game A", null, "internal")),
|
||||
requestInitialFocus = false,
|
||||
)
|
||||
}
|
||||
}
|
||||
val stackHeading = context.getString(R.string.comp_this_proton).uppercase()
|
||||
compose.onNodeWithText(stackHeading).assertExists()
|
||||
compose.onNodeWithText(context.getString(R.string.comp_scope_general)).performClick()
|
||||
compose.onNodeWithText("Game A").performClick()
|
||||
compose.onNodeWithText(context.getString(R.string.comp_game_hint)).assertExists()
|
||||
compose.onNodeWithText(stackHeading).assertDoesNotExist()
|
||||
|
||||
compose.onNodeWithText("Game A").performClick()
|
||||
compose.onNodeWithText(context.getString(R.string.comp_scope_general)).performClick()
|
||||
compose.onNodeWithText(stackHeading).assertExists()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import android.content.Context
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.ui.test.hasText
|
||||
import androidx.compose.ui.test.onAllNodesWithText
|
||||
import androidx.compose.ui.test.onLast
|
||||
import androidx.compose.ui.test.onNodeWithText
|
||||
import androidx.compose.ui.test.performClick
|
||||
import androidx.compose.ui.test.performScrollTo
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.core.GameEnvironment
|
||||
import com.droiddeck.launcher.session.GameEnvironmentStore
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.RuntimeEnvironment
|
||||
import org.robolectric.annotation.Config
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [28])
|
||||
class GameEnvironmentEditorTest {
|
||||
@get:Rule val compose = createRobolectricComposeRule()
|
||||
|
||||
@Test fun backgroundSelectionCannotRetargetAnOpenVariableEdit() {
|
||||
val context: Context = RuntimeEnvironment.getApplication()
|
||||
val variable = "MESA_SHADER_CACHE_MAX_SIZE"
|
||||
GameEnvironmentStore.save(context, GameEnvironment.Config(games = mapOf(
|
||||
"42" to mapOf(variable to "512M"),
|
||||
"43" to mapOf(variable to "2G"),
|
||||
)))
|
||||
val selectedScope = mutableStateOf("42")
|
||||
compose.setContent {
|
||||
DroidDeckTheme { GameEnvironmentRow(initialScope = selectedScope.value) }
|
||||
}
|
||||
compose.onNodeWithText(context.getString(R.string.game_env_edit)).performClick()
|
||||
compose.waitUntil(5_000) {
|
||||
compose.onAllNodes(hasText("512M")).fetchSemanticsNodes().isNotEmpty()
|
||||
}
|
||||
compose.onNodeWithText("512M").performScrollTo().performClick()
|
||||
compose.onNodeWithText(context.getString(R.string.game_env_change)).performClick()
|
||||
compose.onAllNodesWithText("512M").onLast().performClick()
|
||||
compose.onNodeWithText("4G").performClick()
|
||||
|
||||
compose.runOnIdle { selectedScope.value = "43" }
|
||||
compose.onNodeWithText(context.getString(R.string.game_env_save)).performClick()
|
||||
compose.waitUntil(5_000) {
|
||||
GameEnvironmentStore.read(context).entries("42")[variable] == "4G"
|
||||
}
|
||||
assertEquals("2G", GameEnvironmentStore.read(context).entries("43")[variable])
|
||||
compose.onNodeWithText("4G").assertExists()
|
||||
|
||||
compose.onNodeWithText(context.getString(R.string.game_env_done)).performScrollTo().performClick()
|
||||
compose.waitForIdle()
|
||||
compose.onNodeWithText(context.getString(R.string.game_env_edit)).performClick()
|
||||
compose.waitUntil(5_000) {
|
||||
compose.onAllNodes(hasText("2G")).fetchSemanticsNodes().isNotEmpty()
|
||||
}
|
||||
compose.onNodeWithText("2G").assertExists()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import android.content.ComponentName
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.compose.ui.test.junit4.createComposeRule
|
||||
import org.robolectric.RuntimeEnvironment
|
||||
import org.robolectric.Shadows.shadowOf
|
||||
|
||||
fun createRobolectricComposeRule() = createComposeRule().also {
|
||||
val context = RuntimeEnvironment.getApplication()
|
||||
// Register only in Robolectric, without adding a host activity to either APK variant.
|
||||
shadowOf(context.packageManager).addActivityIfNotPresent(
|
||||
ComponentName(context, ComponentActivity::class.java),
|
||||
)
|
||||
}
|
||||
@@ -3,16 +3,52 @@
|
||||
Open **Games → Game environment**, directly below **FEX preset**, in Steam
|
||||
settings or the in-session drawer. Choose all Proton games, an installed game, or enter a Steam app ID. For a
|
||||
non-Steam shortcut, use its numeric `compatdata` directory ID (unsigned 32-bit).
|
||||
The drawer opens the editor on its selected game profile. That editing scope stays
|
||||
fixed if Steam's selected game changes in the background; use the editor's own
|
||||
profile picker to switch deliberately.
|
||||
Changes apply on the next game launch, including when Steam is already running.
|
||||
A running game must be restarted. Native Linux games and Steam itself are outside
|
||||
this editor's scope.
|
||||
|
||||
The Components page also has a **Configuration** dropdown. **Default profile** owns the
|
||||
default Proton and FEX preset. An installed game can inherit those defaults or
|
||||
choose its own Proton and FEX preset. Proton choices are applied through Steam's
|
||||
per-app compatibility mapping, including while Steam is running when its live
|
||||
compatibility helper is attached. A newly installed Proton that the running
|
||||
client has not discovered yet applies when Steam next starts.
|
||||
|
||||
Each game can also override the stored FEX, DXVK and VKD3D-Proton package used
|
||||
by its selected Proton. The launch wrapper applies that game’s component files
|
||||
immediately before Proton starts, removes managed files that are absent from the
|
||||
selection, and restores Default component choices for the next game. **Use
|
||||
Default** removes the game override. Component packages must first be downloaded
|
||||
or imported on the Default Components page.
|
||||
|
||||
Before publishing game component choices, DroidDeck preserves each Proton build's
|
||||
original components, including an explicitly empty bundle when a component is not
|
||||
shipped. Those restore choices remain after the last override is cleared. A missing
|
||||
or unreadable original is an error, not permission to delete the component's files.
|
||||
If an original is missing after a build may already have used a game override,
|
||||
DroidDeck refuses to capture those potentially modified files as originals.
|
||||
|
||||
Component selections and the launch table are saved with a recovery record.
|
||||
Publishing the launch table commits the selection: if the app stops before its
|
||||
settings file is updated, the next component read recovers the matching settings.
|
||||
An interruption before publication leaves the previous selections in place.
|
||||
Unused staged packages are removed only after both files have been saved.
|
||||
|
||||
**Reset game profile** removes all overrides owned by the selected game: Proton,
|
||||
FEX preset, component packages, environment variables, texture filtering and
|
||||
Windows components. The game then inherits the Default profile again.
|
||||
|
||||
The order is inherited process environment, selected FEX preset and built-in
|
||||
settings, shared edits, then game-specific edits. Editor entries therefore win
|
||||
over matching Steam launch-option variables. **Remove** explicitly unsets a
|
||||
variable. **Restore inherited settings** removes the override. **Reset this
|
||||
profile** clears only that profile's overrides. Values are literal strings, with
|
||||
no shell expansion; quotes are only needed when the consuming program expects them.
|
||||
variable. **Restore inherited settings** removes the override. The environment
|
||||
editor's **Clear environment overrides** action clears only the selected
|
||||
environment entries and is intentionally narrower than **Reset game profile**.
|
||||
Values are literal strings, with no shell expansion; quotes are only needed when
|
||||
the consuming program expects them.
|
||||
|
||||
## Defaults and available suggestions
|
||||
|
||||
@@ -71,14 +107,18 @@ wrapper and adopted third-party Proton wrappers execute `droiddeck-game-env`,
|
||||
which reads that snapshot for each real game launch and uses `execvpe` to start
|
||||
Proton. Probe prefix `compatdata/0` and non-launch verbs are unchanged. Malformed
|
||||
configuration falls back to the inherited environment without evaluating its
|
||||
contents. Signed non-Steam prefix IDs are normalized to unsigned IDs.
|
||||
contents. Both component and environment selection normalize signed non-Steam
|
||||
prefix IDs to unsigned IDs.
|
||||
|
||||
The published file also carries a `dxvkConfig` string the app's own file never
|
||||
has: the session menu's texture filtering (Effects page; `core/TextureFiltering`)
|
||||
as `d3d9/d3d11.samplerAnisotropy` and `samplerLodBias` options. The launcher
|
||||
appends it to `DXVK_CONFIG` after the profiles, so a user's own `DXVK_CONFIG`
|
||||
entry keeps its options. "Auto" texture sharpness is `-log2(panel / session)`,
|
||||
derived when the session is sized, and applies from the next launch.
|
||||
The published file also carries generated `dxvkConfig` and `dxvkConfigGames`
|
||||
values the app's own file never has. The session menu's texture filtering
|
||||
(`core/TextureFiltering`) becomes `d3d9/d3d11.samplerAnisotropy` and
|
||||
`samplerLodBias` options. Default choices apply to games without overrides; each
|
||||
game can save either choice independently or return it to **Use Default**. The
|
||||
launcher appends the selected options to `DXVK_CONFIG` after the environment
|
||||
profile, so a user's own `DXVK_CONFIG` entry keeps its options. "Auto" texture
|
||||
sharpness is `-log2(panel / session)`, derived when the session is sized, and
|
||||
applies from the next launch.
|
||||
|
||||
Upstream references: [VKD3D capability parsing](https://github.com/HansKristian-Work/vkd3d-proton/blob/master/libs/vkd3d/device.c),
|
||||
[VKD3D options](https://github.com/HansKristian-Work/vkd3d-proton#environment-variables),
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
# Experimental Quest 3/3S support
|
||||
|
||||
Quest 3/3S runs DroidDeck as a 2D panel. This does not add immersive VR or
|
||||
OpenXR support. Quest 2 is outside the bundled Adreno 7xx driver path.
|
||||
|
||||
The first launch on Quest 3/3S selects manual drivers, the bundled
|
||||
`turnip25.1.0-quest1` Android driver and the default Linux driver. It enables
|
||||
`hdr.steam` to use the existing SurfaceControl presentation workaround from
|
||||
[the Quest report](https://github.com/Droid-Deck/DroidDeck/issues/245).
|
||||
These defaults apply once; subsequent user changes are retained. Colour
|
||||
accuracy and headset performance still need testing.
|
||||
|
||||
Both the Android driver wrapper and the Linux session preload use
|
||||
`tools/quest/kgsl_compat.c`. Successful legacy allocation/free calls are
|
||||
unchanged. Only `EACCES`/`EPERM` failures retry through `GPUOBJ_ALLOC`,
|
||||
`GPUOBJ_INFO` and `GPUOBJ_FREE`. The Android wrapper depends on the original
|
||||
bundled Turnip binary. Unhandled controller ioctls forward to the next
|
||||
preload hook rather than skipping it with a raw syscall.
|
||||
|
||||
`tools/build_local.sh` and CI build the wrapper from source using the pinned
|
||||
Android NDK; the normal preload builds include the shared Linux adapter.
|
||||
Runtime input verification checks the resulting driver archive and invalidates
|
||||
stale prepared assets after compatibility sources change. To rebuild only the
|
||||
Android driver archive:
|
||||
|
||||
```sh
|
||||
python3 tools/quest/build-driver.py "$ANDROID_HOME/ndk/27.3.13750724"
|
||||
```
|
||||
|
||||
The release variant `quest` produces a separate `com.droiddeck.quest` APK
|
||||
with its own app data. All installed packages use their own bwrap socket.
|
||||
The standard APK also applies Quest defaults when running on Quest 3/3S.
|
||||
|
||||
On a headset, check the Steam login panel, sign-in, game installation and
|
||||
then an owned game's rendering/input. Capture the device/OS, session logs,
|
||||
`files/quest-startup.txt` and any `files/quest-last-crash.txt` failure.
|
||||
Host allocation and preload-chain tests do not establish headset operation.
|
||||
@@ -316,6 +316,7 @@ else
|
||||
fi
|
||||
|
||||
cd "${repo_root}"
|
||||
python3 tools/quest/build-driver.py "${NDK}"
|
||||
python3 tools/release/runtime_inputs.py record
|
||||
./gradlew "${gradle_task}" --console=plain -PndkVersion="${ndk_version}" ${gradle_rust_arg}
|
||||
python3 tools/release/check_session_assets.py "app/build/outputs/apk/${build_variant}/app-${build_variant}.apk"
|
||||
|
||||
@@ -453,6 +453,34 @@ def cdp_eval(agent_dir, expression, target=None, await_promise=True, timeout=15)
|
||||
ws.close()
|
||||
|
||||
|
||||
def steam_selection(agent_dir, timeout=5):
|
||||
result = cdp_eval(
|
||||
agent_dir,
|
||||
"""(() => {
|
||||
let node = document.activeElement;
|
||||
while (node) {
|
||||
for (const name of ["data-id", "data-appid"]) {
|
||||
const value = node.getAttribute?.(name);
|
||||
if (/^[1-9][0-9]{0,9}$/.test(value || "")) {
|
||||
const appId = Number(value);
|
||||
if (Number.isSafeInteger(appId) && appId <= 4294967295) return value;
|
||||
}
|
||||
}
|
||||
node = node.parentElement;
|
||||
}
|
||||
return null;
|
||||
})()""",
|
||||
target="Steam Big Picture Mode",
|
||||
timeout=timeout,
|
||||
)
|
||||
value = result.get("value")
|
||||
if value is None:
|
||||
return {"appId": None}
|
||||
if not isinstance(value, str) or not value.isdigit() or not 0 < int(value) <= 4294967295:
|
||||
raise AgentError("INVALID_SELECTION", "Steam returned an invalid selected app id")
|
||||
return {"appId": int(value)}
|
||||
|
||||
|
||||
# --- Game processes ------------------------------------------------------------------------------
|
||||
|
||||
def game_pids(app_id):
|
||||
@@ -624,6 +652,8 @@ def handle(agent_dir, req):
|
||||
raise AgentError("INVALID_REQUEST", "cdp eval needs an expression")
|
||||
return cdp_eval(agent_dir, expression, req.get("target"), bool(req.get("awaitPromise", True)),
|
||||
request_timeout(req, 15))
|
||||
if kind == "steam-selection":
|
||||
return steam_selection(agent_dir, request_timeout(req, 5))
|
||||
if kind == "quit":
|
||||
return quit_game(agent_dir, req.get("appId"), request_timeout(req, 15))
|
||||
raise AgentError("UNKNOWN_REQUEST", "Unknown agent request '%s'" % kind)
|
||||
|
||||
@@ -20,7 +20,7 @@ import socket
|
||||
import struct
|
||||
import sys
|
||||
|
||||
SOCKET = "\0com.droiddeck.launcher.bwrap"
|
||||
SOCKET = "\0" + os.environ.get("DROIDDECK_BWRAP_SOCKET", "com.droiddeck.launcher.bwrap")
|
||||
VERSION = "bubblewrap 0.11.0 (droiddeck)"
|
||||
|
||||
# Options and how many arguments each takes; bwrap(1).
|
||||
|
||||
@@ -168,7 +168,10 @@ def apply_config(env, config, app_id, fixes=None):
|
||||
raise ValueError("invalid environment value")
|
||||
# The app's texture filtering (Display page), as DXVK options appended after the profiles so
|
||||
# a DXVK_CONFIG entry of the user's keeps its own.
|
||||
dxvk = config.get("dxvkConfig")
|
||||
game_dxvk = config.get("dxvkConfigGames", {})
|
||||
if not isinstance(game_dxvk, dict):
|
||||
raise ValueError("invalid game dxvk configuration")
|
||||
dxvk = game_dxvk.get(app_id, config.get("dxvkConfig"))
|
||||
if dxvk is not None:
|
||||
if not isinstance(dxvk, str) or "\0" in dxvk or len(dxvk) > 8192:
|
||||
raise ValueError("invalid dxvk configuration")
|
||||
@@ -255,8 +258,9 @@ EVALUATOR_SCRIPT = re.compile(r"(?:^|[\\/])evaluatorscript_[0-9]+\.vdf$", re.IGN
|
||||
|
||||
def mark_install_scripts(command, env):
|
||||
"""The client is about to run a game's install scripts (iscriptevaluator.exe): mark every process
|
||||
in them as already run first, so no redistributable installer starts - on first launch the
|
||||
shared ones may still be downloading, and on ARM64 Proton the VC++ ones stop with an error."""
|
||||
in them but a Vulkan runtime installer as already run first, so no redistributable installer
|
||||
starts - on first launch the shared ones may still be downloading, and on ARM64 Proton the VC++
|
||||
ones stop with an error."""
|
||||
if not any(arg.lower().replace("\\", "/").endswith("iscriptevaluator.exe") for arg in command):
|
||||
return
|
||||
root = env.get("STEAM_COMPAT_CLIENT_INSTALL_PATH") or str(Path.home() / ".local/share/Steam")
|
||||
|
||||
@@ -0,0 +1,230 @@
|
||||
#!/usr/bin/python3
|
||||
"""Holds a game launcher's hidden web interface on one slow core while something else has focus.
|
||||
|
||||
Rockstar's launcher keeps drawing its Chromium interface (SocialClubHelper.exe: a renderer, and a
|
||||
GPU process compositing through DXVK) for as long as it runs, hidden behind the game too, and at a
|
||||
higher priority than the game's (Wine passes Chromium's on: the GPU process ran at nice -10). With
|
||||
Red Dead Redemption 2 in front on the RedMagic that was 1.3 to 2.5 cores under FEX, on a phone
|
||||
already held back by its temperature, for a page nobody sees. Held, riding at the throttle limit
|
||||
went from 46.5 to 48.7 fps, 1% lows from 27.5 to 32.6. So while the focused window belongs to
|
||||
anything but the launcher, every helper thread runs on one core of the slowest cluster at nice 19;
|
||||
when the launcher's own window has focus again (signing in, the game closed) each thread gets its
|
||||
own mask and priority back. Stopping the helpers instead would not hold: proot, the tracer of every
|
||||
guest process, resumes a stopped tracee.
|
||||
|
||||
Focus comes from droiddeck-agent's focus.json (the path is the argument), which the agent rewrites
|
||||
whenever gamescope's focus changes. droiddeck-session starts this for Steam sessions;
|
||||
BL_LAUNCHER_CORES=0 leaves the launchers alone."""
|
||||
import json
|
||||
import os
|
||||
import signal
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
# Image paths (lower case, backslashes), matched at the end: the helpers held back, and the
|
||||
# programs whose window having focus means the user is looking at the launcher.
|
||||
HELPERS = ("\\rockstar games\\social club\\socialclubhelper.exe",)
|
||||
FRONTS = HELPERS + ("\\rockstar games\\launcher\\launcher.exe",)
|
||||
NICE = 19
|
||||
POLL = 2.0
|
||||
# How often a held launcher is looked over again: for a helper the unheld Launcher.exe started
|
||||
# since, and for threads the program has moved back.
|
||||
RESCAN = 10.0
|
||||
STEAM_CLIENT = 769
|
||||
|
||||
|
||||
def log(message):
|
||||
print("droiddeck-launcher-cores: " + message, flush=True)
|
||||
|
||||
|
||||
def image(proc, pid):
|
||||
"""A process's program as Wine names it (argv[0]), lower case with backslashes, or None."""
|
||||
try:
|
||||
with open(proc / str(pid) / "cmdline", "rb") as stream:
|
||||
first = stream.read(4096).split(b"\0", 1)[0]
|
||||
except OSError:
|
||||
return None
|
||||
return first.decode("utf-8", "replace").lower().replace("/", "\\")
|
||||
|
||||
|
||||
def is_one_of(path, suffixes):
|
||||
return path is not None and path.endswith(suffixes)
|
||||
|
||||
|
||||
def tasks(proc, pid):
|
||||
try:
|
||||
return [int(tid) for tid in os.listdir(proc / str(pid) / "task") if tid.isdigit()]
|
||||
except OSError:
|
||||
return []
|
||||
|
||||
|
||||
class Cores:
|
||||
"""The kernel calls, apart so a test can stand in for them."""
|
||||
|
||||
def own(self):
|
||||
return os.sched_getaffinity(0)
|
||||
|
||||
def get(self, tid):
|
||||
return os.sched_getaffinity(tid), os.getpriority(os.PRIO_PROCESS, tid)
|
||||
|
||||
def set(self, tid, cpus, nice):
|
||||
try:
|
||||
os.sched_setaffinity(tid, cpus)
|
||||
except OSError:
|
||||
# A mask outside the app's cpuset now (Android shrinks it in the background) is
|
||||
# EINVAL; the session's own is always allowed.
|
||||
os.sched_setaffinity(tid, self.own())
|
||||
os.setpriority(os.PRIO_PROCESS, tid, nice)
|
||||
|
||||
|
||||
class Holder:
|
||||
def __init__(self, proc=Path("/proc"), cpufreq=Path("/sys/devices/system/cpu"), cores=None):
|
||||
self.proc = proc
|
||||
self.cpufreq = cpufreq
|
||||
self.cores = cores or Cores()
|
||||
self.held = {} # pid -> {tid: (cpus, nice) before the hold}
|
||||
self.core = None
|
||||
|
||||
def slow_core(self):
|
||||
"""The last core of the slowest cluster the session has - not of the game's cores, which
|
||||
the launcher inherits when BL_GAME_CPUS is set: the core the game misses least."""
|
||||
def top(cpu):
|
||||
try:
|
||||
return int((self.cpufreq / f"cpu{cpu}/cpufreq/cpuinfo_max_freq").read_text())
|
||||
except (OSError, ValueError):
|
||||
return 0
|
||||
cpus = self.cores.own()
|
||||
slowest = min(top(cpu) for cpu in cpus)
|
||||
return max(cpu for cpu in cpus if top(cpu) == slowest)
|
||||
|
||||
def helpers(self):
|
||||
for name in os.listdir(self.proc):
|
||||
if name.isdigit() and is_one_of(image(self.proc, name), HELPERS):
|
||||
yield int(name)
|
||||
|
||||
def hold(self):
|
||||
"""Every helper thread onto the slow core at NICE: new ones, and held ones the program has
|
||||
moved since (Chromium sets its threads' priorities, and Wine passes that on)."""
|
||||
if self.core is None:
|
||||
self.core = self.slow_core()
|
||||
hold = ({self.core}, NICE)
|
||||
for pid in self.helpers():
|
||||
before = self.held.setdefault(pid, {})
|
||||
for tid in tasks(self.proc, pid):
|
||||
try:
|
||||
now = self.cores.get(tid)
|
||||
if now != hold:
|
||||
self.cores.set(tid, *hold)
|
||||
except OSError:
|
||||
continue # the thread ended
|
||||
if tid not in before:
|
||||
# A thread that already has the hold inherited it from a held parent: it gets
|
||||
# what its process had, or the helpers' first.
|
||||
before[tid] = now if now != hold else before.get(pid) or self.first() or now
|
||||
for pid in [pid for pid in self.held if not (self.proc / str(pid)).exists()]:
|
||||
del self.held[pid]
|
||||
|
||||
def first(self):
|
||||
for before in self.held.values():
|
||||
for state in before.values():
|
||||
if state != ({self.core}, NICE):
|
||||
return state
|
||||
return None
|
||||
|
||||
def release(self):
|
||||
"""Every held thread back to its own mask and priority; one started during the hold gets
|
||||
what its process had."""
|
||||
for pid, before in self.held.items():
|
||||
default = before.get(pid) or self.first()
|
||||
for tid in tasks(self.proc, pid):
|
||||
state = before.get(tid, default)
|
||||
if state is None:
|
||||
continue
|
||||
try:
|
||||
self.cores.set(tid, *state)
|
||||
except OSError:
|
||||
pass
|
||||
self.held.clear()
|
||||
|
||||
|
||||
def focused(snapshot):
|
||||
"""(app id, pid) of the window gamescope has focused, from droiddeck-agent's snapshot."""
|
||||
window = snapshot.get("focusedWindow")
|
||||
for entry in snapshot.get("focusableWindows") or []:
|
||||
if entry.get("window") == window:
|
||||
return snapshot.get("focusedApp"), entry.get("pid")
|
||||
return snapshot.get("focusedApp"), None
|
||||
|
||||
|
||||
class Governor:
|
||||
def __init__(self, focus_path, holder=None, clock=time.monotonic):
|
||||
self.focus_path = Path(focus_path)
|
||||
self.holder = holder or Holder()
|
||||
self.clock = clock
|
||||
self.seen = None
|
||||
self.app = self.pid = None
|
||||
self.scanned = None
|
||||
self.reported = None
|
||||
|
||||
def read_focus(self):
|
||||
try:
|
||||
stamp = self.focus_path.stat().st_mtime_ns
|
||||
except OSError:
|
||||
return False
|
||||
if stamp == self.seen:
|
||||
return False
|
||||
try:
|
||||
self.app, self.pid = focused(json.loads(self.focus_path.read_text()))
|
||||
except (OSError, ValueError, AttributeError):
|
||||
return False
|
||||
self.seen = stamp
|
||||
return True
|
||||
|
||||
def tick(self):
|
||||
changed = self.read_focus()
|
||||
if self.pid is None:
|
||||
return
|
||||
launcher_in_front = is_one_of(image(self.holder.proc, self.pid), FRONTS)
|
||||
if launcher_in_front:
|
||||
if self.holder.held:
|
||||
self.holder.release()
|
||||
self.report("released: the launcher has focus")
|
||||
return
|
||||
# Nothing to look for until a game has had focus: launchers only run for one, and a launcher
|
||||
# left running after its game stays held through the Steam client's own focus.
|
||||
if self.app in (None, 0, STEAM_CLIENT) and not self.holder.held:
|
||||
return
|
||||
now = self.clock()
|
||||
if changed or self.scanned is None or now - self.scanned >= RESCAN:
|
||||
self.scanned = now
|
||||
self.holder.hold()
|
||||
if self.holder.held:
|
||||
self.report(f"{len(self.holder.held)} SocialClubHelper process(es) on core {self.holder.core} "
|
||||
f"at nice {NICE} while the launcher is hidden")
|
||||
|
||||
def report(self, message):
|
||||
if message != self.reported:
|
||||
self.reported = message
|
||||
log(message)
|
||||
|
||||
def stop(self, *_):
|
||||
self.holder.release()
|
||||
sys.exit(0)
|
||||
|
||||
|
||||
def main(argv):
|
||||
if len(argv) != 1:
|
||||
print("usage: droiddeck-launcher-cores <agent focus.json>", file=sys.stderr)
|
||||
return 2
|
||||
governor = Governor(argv[0])
|
||||
signal.signal(signal.SIGTERM, governor.stop)
|
||||
signal.signal(signal.SIGHUP, governor.stop)
|
||||
signal.signal(signal.SIGINT, governor.stop)
|
||||
while True:
|
||||
governor.tick()
|
||||
time.sleep(POLL)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main(sys.argv[1:]))
|
||||
@@ -4,14 +4,15 @@
|
||||
#
|
||||
# droiddeck-proton-extra <steam root> ge [--tag GE-Proton11-7]
|
||||
# droiddeck-proton-extra <steam root> cachyos [--tag cachyos-11.0-20260703-slr]
|
||||
# droiddeck-proton-extra <steam root> droiddeck [--tag DroidDeck-Proton-11-7.5]
|
||||
# droiddeck-proton-extra <steam root> <url of an aarch64 tarball>
|
||||
# droiddeck-proton-extra <steam root> /path/to/an/aarch64/tarball
|
||||
# droiddeck-proton-extra <steam root> --list what is installed now
|
||||
#
|
||||
# Both projects publish native ARM64 builds - GloriousEggroll as "*-aarch64.tar.gz", CachyOS as
|
||||
# "*-arm64.tar.xz" - and both are ordinary Proton trees: a python entry point beside a files/
|
||||
# directory holding Wine, DXVK and VKD3D. That is the same shape as the depot the Steam client
|
||||
# downloads, so the runtime can run them the same way.
|
||||
# All three projects publish native ARM64 builds - GloriousEggroll and DroidDeck-Proton as
|
||||
# "*-aarch64.tar.gz", CachyOS as "*-arm64.tar.xz" - and all are ordinary Proton trees: a python
|
||||
# entry point beside a files/ directory holding Wine, DXVK and VKD3D. That is the same shape as the
|
||||
# depot the Steam client downloads, so the runtime can run them the same way.
|
||||
#
|
||||
# What it cannot use is their toolmanifest. Like Valve's ARM64 depot they declare
|
||||
# require_tool_appid, which makes Steam stack pressure-vessel underneath - and pressure-vessel
|
||||
@@ -30,11 +31,12 @@ import urllib.request
|
||||
|
||||
RELEASES = "https://api.github.com/repos/%s/releases"
|
||||
# Each source: the GitHub repo, and how its ARM64 asset is named. Ordered newest-release-first by
|
||||
# the API, so "latest usable" is the first release that actually carries an ARM64 asset - the
|
||||
# the API, so "latest usable" is the first full release that actually carries an ARM64 asset - the
|
||||
# projects do not build one for every tag.
|
||||
SOURCES = {
|
||||
"ge": ("GloriousEggroll/proton-ge-custom", re.compile(r"aarch64\.tar\.(gz|xz)$")),
|
||||
"cachyos": ("CachyOS/proton-cachyos", re.compile(r"arm64\.tar\.(gz|xz)$")),
|
||||
"droiddeck": ("The412Banner/DroidDeck-Proton", re.compile(r"aarch64\.tar\.(gz|xz)$")),
|
||||
}
|
||||
USER_AGENT = "droiddeck-proton-extra"
|
||||
# Room for the tarball and the tree it unpacks to. GE-Proton's aarch64 build is ~650 MB packed and
|
||||
@@ -54,10 +56,10 @@ def fetch_json(url):
|
||||
|
||||
|
||||
def pick_asset(source):
|
||||
"""(release tag, asset url, sha512 url or None) for the newest release with an ARM64 build."""
|
||||
"""(release tag, asset url, sha512 url or None) for the newest full release with an ARM64 build."""
|
||||
repo, pattern = SOURCES[source]
|
||||
for release in fetch_json(RELEASES % repo + "?per_page=15"):
|
||||
if release.get("draft"):
|
||||
if release.get("draft") or release.get("prerelease"):
|
||||
continue
|
||||
assets = {a["name"]: a["browser_download_url"] for a in release.get("assets", ())}
|
||||
for name in sorted(assets):
|
||||
@@ -144,7 +146,7 @@ def installed(tools):
|
||||
def main():
|
||||
argv = sys.argv[1:]
|
||||
if not argv:
|
||||
raise SystemExit(__doc__ or "usage: droiddeck-proton-extra <steam root> ge|cachyos|<url>")
|
||||
raise SystemExit(__doc__ or "usage: droiddeck-proton-extra <steam root> ge|cachyos|droiddeck|<url>")
|
||||
steam_root = argv.pop(0)
|
||||
tools = os.path.join(steam_root, "compatibilitytools.d")
|
||||
os.makedirs(tools, exist_ok=True)
|
||||
@@ -176,7 +178,7 @@ def main():
|
||||
log("using %s" % what)
|
||||
else:
|
||||
raise SystemExit(
|
||||
"droiddeck-proton-extra: expected ge, cachyos, a URL or a tarball path, got %r" % what)
|
||||
"droiddeck-proton-extra: expected ge, cachyos, droiddeck, a URL or a tarball path, got %r" % what)
|
||||
|
||||
free = shutil.disk_usage(tools).free
|
||||
if free < NEED_BYTES:
|
||||
|
||||
@@ -17,6 +17,11 @@
|
||||
# 2015-2022 runtime is recorded as installed the way Microsoft's installers look for it: on ARM64
|
||||
# Proton the x64 bundle otherwise stops with "Microsoft Visual C++ 2015-2022 Redistributable (arm64)
|
||||
# is required", while Proton's own msvcp140/vcruntime140 already serve the game.
|
||||
#
|
||||
# A Vulkan runtime installer is the one left to run. Proton has no stand-in for it: for a game whose
|
||||
# Steam compat config says nativevulkanloader (Red Dead Redemption 2) it loads vulkan-1.dll native
|
||||
# only, and Khronos' loader is in the prefix only once that installer has run - without it the game
|
||||
# exits with STATUS_DLL_NOT_FOUND before it opens a window. The installer finishes in a second.
|
||||
set -u
|
||||
steam_root=${1:?steam root}
|
||||
LIBRARIES=${DROIDDECK_LIBRARIES-/mnt/droiddeck /mnt/droiddeck-sd}
|
||||
@@ -25,14 +30,15 @@ redist="$steam_root/steamapps/common/Steamworks Shared/_CommonRedist"
|
||||
|
||||
# Every process an install script would run, as the registry key and value the client writes once
|
||||
# it has run it. Names sit one level inside "Run Process", the key they share a level further in.
|
||||
read_scripts() { xargs -0 -r awk '
|
||||
# "read_scripts vulkan" lists only the Vulkan runtime installers, which the plain call leaves out.
|
||||
read_scripts() { xargs -0 -r awk -v want="${1:-redists}" '
|
||||
# A block whose HasRunKey is set is one process; its name is the key the block opened under, at
|
||||
# whatever depth - an install script nests it under "Run Process", the client'"'"'s evaluator script
|
||||
# for a game wraps the same blocks once more.
|
||||
FNR == 1 { depth = 0; pending = "" }
|
||||
/^[[:space:]]*\{/ { depth++; name[depth] = pending; key[depth] = ""; pending = ""; next }
|
||||
/^[[:space:]]*\{/ { depth++; name[depth] = pending; key[depth] = ""; vulkan[depth] = 0; pending = ""; next }
|
||||
/^[[:space:]]*\}/ {
|
||||
if (depth > 0 && key[depth] != "" && name[depth] != "")
|
||||
if (depth > 0 && key[depth] != "" && name[depth] != "" && vulkan[depth] == (want == "vulkan"))
|
||||
printf "%s\t%s\n", key[depth], name[depth]
|
||||
if (depth > 0) depth--
|
||||
next
|
||||
@@ -40,6 +46,12 @@ read_scripts() { xargs -0 -r awk '
|
||||
{
|
||||
n = split($0, part, "\"")
|
||||
if (n >= 5 && tolower(part[2]) == "hasrunkey") { key[depth] = part[4]; next }
|
||||
if (n >= 5 && tolower(part[2]) ~ /^process [0-9]+$/) {
|
||||
program = tolower(part[4])
|
||||
sub(/.*[\\\/]/, "", program)
|
||||
if (program ~ /vulkan/) vulkan[depth] = 1
|
||||
next
|
||||
}
|
||||
if (n == 3) pending = part[2]
|
||||
}
|
||||
'; }
|
||||
@@ -84,13 +96,17 @@ if [ "$(head -n 1 "$cache" 2>/dev/null)" != "$sig" ]; then
|
||||
done <<<"$libraries" | sort -u
|
||||
} >"$cache.tmp" && mv -f "$cache.tmp" "$cache"
|
||||
fi
|
||||
game_pairs=$(tail -n +2 "$cache" 2>/dev/null | tr '\n' '\0' | read_scripts)
|
||||
# DROIDDECK_SEED_SCRIPTS: more scripts, one path a line - droiddeck-game-env passes the client's
|
||||
# evaluator script for the game about to run its installers, read before the client looks.
|
||||
if [ -n "${DROIDDECK_SEED_SCRIPTS:-}" ]; then
|
||||
game_pairs=$(printf '%s\n%s\n' "$game_pairs" "$(printf '%s\n' "$DROIDDECK_SEED_SCRIPTS" | tr '\n' '\0' | read_scripts)")
|
||||
fi
|
||||
game_scripts() { { tail -n +2 "$cache" 2>/dev/null; printf '%s\n' "${DROIDDECK_SEED_SCRIPTS:-}"; } | sed '/^$/d' | tr '\n' '\0'; }
|
||||
game_pairs=$(game_scripts | read_scripts)
|
||||
[ -n "$(printf '%s' "$game_pairs" | tr -d '[:space:]')" ] && pairs=$(printf '%s\n%s\n' "$pairs" "$game_pairs" | sort -u | sed '/^$/d')
|
||||
# A Vulkan runtime installer marked as run by an earlier seeding still has its marker: those come out
|
||||
# again below, so the client runs the installer on the game's next launch.
|
||||
declare -A vulkan=()
|
||||
while IFS= read -r line; do
|
||||
[[ $line == *$'\t'* ]] && vulkan[$line]=1
|
||||
done < <(game_scripts | read_scripts vulkan)
|
||||
|
||||
# The VC++ 2015-2022 runtime as its installers check for it, for each architecture and both registry
|
||||
# views. The version is the newest the scripts above know, so any 2015-2022 bundle finds itself
|
||||
@@ -138,6 +154,38 @@ block_for() { printf '%s\n' "$@" | awk -F'\t' -v now="$now" '
|
||||
for line; do [[ $line == vcrt$'\t'* ]] && vcrt "$now"; done
|
||||
}
|
||||
|
||||
# Takes the given markers out of a registry file again, in both views, keeping its date.
|
||||
unseed() {
|
||||
local reg=$1 out
|
||||
shift
|
||||
out=$(mktemp "${reg%/*}/.system.reg.XXXXXX") || return 1
|
||||
if printf '%s\n' "$@" | awk -F'\t' '
|
||||
NR == FNR {
|
||||
path = $1
|
||||
sub(/^HKEY_LOCAL_MACHINE\\\\/, "", path)
|
||||
if (path == $1)
|
||||
next
|
||||
path = tolower(path)
|
||||
drop["[" path "]" SUBSEP tolower($2)] = 1
|
||||
if (substr(path, 1, 10) == "software\\\\")
|
||||
drop["[software\\\\wow6432node\\\\" substr(path, 11) "]" SUBSEP tolower($2)] = 1
|
||||
next
|
||||
}
|
||||
/^\[/ { section = tolower(substr($0, 1, index($0, "]"))) }
|
||||
/^"/ {
|
||||
value = substr($0, 2)
|
||||
value = tolower(substr(value, 1, index(value, "\"=") - 1))
|
||||
if ((section SUBSEP value) in drop)
|
||||
next
|
||||
}
|
||||
{ print }
|
||||
' - "$reg" >"$out" && touch -r "$reg" "$out" && mv -f "$out" "$reg"; then
|
||||
return 0
|
||||
fi
|
||||
rm -f "$out"
|
||||
return 1
|
||||
}
|
||||
|
||||
# Proton builds a new prefix from its template, and the client runs the install scripts in that
|
||||
# prefix moments later, so the template carries the markers too. Its date is kept: Proton reads a
|
||||
# changed one as a new template and upgrades every prefix made from the old.
|
||||
@@ -158,6 +206,16 @@ for reg in "$steam_root"/steamapps/common/Proton*/files/share/default_pfx*/syste
|
||||
if [ -f "$seeded" ]; then
|
||||
while IFS= read -r line; do [[ $line == *$'\t'* ]] && had[$line]=1; done <"$seeded"
|
||||
fi
|
||||
stale=() kept=()
|
||||
for line in "${!had[@]}"; do
|
||||
if [ -n "${vulkan[$line]:-}" ]; then stale+=("$line"); else kept+=("$line"); fi
|
||||
done
|
||||
if [ ${#stale[@]} -gt 0 ] && unseed "$reg" "${stale[@]}"; then
|
||||
had=()
|
||||
for line in "${kept[@]}"; do had[$line]=1; done
|
||||
printf '%s\n' "${kept[@]}" >"$seeded"
|
||||
echo "== took Vulkan runtime markers out of $reg"
|
||||
fi
|
||||
missing=()
|
||||
for line in "${want[@]}"; do [ -n "${had[$line]:-}" ] || missing+=("$line"); done
|
||||
[ ${#missing[@]} -eq 0 ] && continue
|
||||
|
||||
@@ -50,6 +50,37 @@ prepare_locale() {
|
||||
}
|
||||
[ -z "${BL_INSIDE:-}" ] && prepare_locale
|
||||
|
||||
# What earlier sessions left in /tmp. The guest's /tmp is a directory in the rootfs, never emptied
|
||||
# by a boot, and Android ends sessions by killing them: each left its mangoapp config, the client's
|
||||
# temporary directories and shared-memory sockets, Chromium's singleton directory (the web
|
||||
# helper's, an Electron app's), a session bus socket per run and a run's start stamp - 1,400
|
||||
# entries on a device after a few weeks. Each kind is swept while nothing that could own one runs,
|
||||
# with one find for the lot.
|
||||
clear_stale_tmp() {
|
||||
local running names=() n
|
||||
running=$(pgrep -af 'steamwebhelper|steamrtarm64/steam|--type=|droiddeck-appimage-run|dbus-run-session|dbus-daemon.*--session|dbus-launch|kwin|plasmashell' 2>/dev/null)
|
||||
case $running in
|
||||
*steamwebhelper* | *steamrtarm64/steam*) ;;
|
||||
*) names+=(-o -name 'mangohud.????????' -o -name '.com.valvesoftware.Steam.??????'
|
||||
-o -name 'steam_chrome_shmem_uid*' -o \( -type d -empty -name 'steam??????' \)) ;;
|
||||
esac
|
||||
case $running in *--type=*) ;; *) names+=(-o \( -type d -name 'scoped_dir??????' \)) ;; esac
|
||||
case $running in *droiddeck-appimage-run*) ;; *) names+=(-o -name 'droiddeck-appimage.??????') ;; esac
|
||||
case $running in
|
||||
*dbus-run-session* | *dbus-daemon*--session* | *dbus-launch*) ;;
|
||||
*) names+=(-o \( -type s -name 'dbus-??????????' \)) ;;
|
||||
esac
|
||||
case $running in
|
||||
*kwin* | *plasmashell*) ;;
|
||||
*) names+=(-o \( -type d -empty -name 'plasma-csd-generator.??????' \)) ;;
|
||||
esac
|
||||
[ ${#names[@]} -gt 0 ] || return 0
|
||||
n=$(find /tmp -mindepth 1 -maxdepth 1 \( "${names[@]:1}" \) -print -exec rm -rf {} + 2>/dev/null | wc -l)
|
||||
[ "$n" -gt 0 ] && echo "== /tmp: cleared $n entries earlier sessions left"
|
||||
return 0
|
||||
}
|
||||
[ -z "${BL_INSIDE:-}" ] && clear_stale_tmp
|
||||
|
||||
# Until the runtime is stable, Steam's own logs are copied beside the session log at exit so a
|
||||
# failed launch can be handed over as one folder.
|
||||
collect_steam_logs() {
|
||||
@@ -271,7 +302,8 @@ if [ -z "${BL_INSIDE:-}" ]; then
|
||||
# BL_MANGOAPP=0 turns it off (one community build found Valve's mangoapp crashing on Turnip).
|
||||
if [ "$mode" = steam ] && [ "${BL_MANGOAPP:-1}" = 1 ] \
|
||||
&& [ "${BL_STEAM_UI:-}" != desktop ] && command -v mangoapp >/dev/null 2>&1; then
|
||||
MANGOHUD_CONFIGFILE=$(mktemp /tmp/mangohud.XXXXXXXX)
|
||||
# One fixed file, rewritten each session: a mktemp name per session was never removed.
|
||||
MANGOHUD_CONFIGFILE=/tmp/droiddeck-mangohud.conf
|
||||
echo no_display > "$MANGOHUD_CONFIGFILE"
|
||||
export MANGOHUD_CONFIGFILE STEAM_USE_MANGOAPP=1 STEAM_MANGOAPP_PRESETS_SUPPORTED=1 STEAM_MANGOAPP_HORIZONTAL_SUPPORTED=1
|
||||
args+=(--mangoapp)
|
||||
@@ -376,9 +408,9 @@ case $mode in
|
||||
# its main library already - and the ARM64 Proton that lets it launch the Windows ones.
|
||||
# A request left in ~/.bl-proton-extra installs a third-party Proton before the client starts,
|
||||
# so it is in the Compatibility dropdown the first time the user looks. One per line, each the
|
||||
# arguments to droiddeck-proton-extra: "ge", "cachyos", "ge --tag GE-Proton11-7", or a URL.
|
||||
# Hundreds of megabytes each, so it is only ever done on request, and the line is dropped once
|
||||
# it has succeeded - a failed download stays and is retried next session.
|
||||
# arguments to droiddeck-proton-extra: "ge", "cachyos", "droiddeck", "ge --tag GE-Proton11-7",
|
||||
# or a URL. Hundreds of megabytes each, so it is only ever done on request, and the line is
|
||||
# dropped once it has succeeded - a failed download stays and is retried next session.
|
||||
if [ -s "$HOME/.bl-proton-extra" ]; then
|
||||
_bl_left=$HOME/.bl-proton-extra.left
|
||||
: > "$_bl_left"
|
||||
@@ -434,6 +466,13 @@ case $mode in
|
||||
done
|
||||
) &
|
||||
fi
|
||||
# Rockstar's launcher keeps drawing its hidden web interface for as long as a game of theirs
|
||||
# runs; droiddeck-launcher-cores holds it on one slow core while it is out of sight, from
|
||||
# gamescope's focus as the agent publishes it. BL_LAUNCHER_CORES=0 leaves launchers alone.
|
||||
if [ "${BL_LAUNCHER_CORES:-1}" != 0 ] && [ -n "${BL_LAUNCH_DIR:-}" ] && [ -z "${BL_DESKTOP:-}" ] \
|
||||
&& [ "${BL_STEAM_UI:-}" != desktop ] && [ -x /usr/local/bin/droiddeck-launcher-cores ]; then
|
||||
/usr/local/bin/droiddeck-launcher-cores "$BL_LAUNCH_DIR/agent/focus.json" 2>&1 &
|
||||
fi
|
||||
|
||||
step "registering the app's game library with Steam"
|
||||
droiddeck-steam-library "$steam_root" || true
|
||||
|
||||
@@ -447,10 +447,15 @@ class Helper:
|
||||
self.installed = installed
|
||||
picks = COMPAT["valve_picks"](self.steam_root)
|
||||
apps = sorted(set(installed) | set(picks) | set(state.get("auto", {})), key=COMPAT["app_order"])
|
||||
overrides = COMPAT["requested_games"](
|
||||
COMPAT["game_requests"](), catalog, [t["name"] for t in live])
|
||||
apps = sorted(set(apps) | set(overrides), key=COMPAT["app_order"])
|
||||
current = dict(page.compat("many(%s)" % json.dumps(apps)) or {})
|
||||
current["0"] = top["selected"]
|
||||
native = COMPAT["native_targets"](self.steam_root, installed)
|
||||
changes, auto = COMPAT["plan_mapping"](current, installed, [t["name"] for t in live], default, COMPAT["followers"](state, current), native, picks)
|
||||
changes, auto = COMPAT["plan_mapping"](
|
||||
current, installed, [t["name"] for t in live], default,
|
||||
COMPAT["followers"](state, current), native, picks, overrides)
|
||||
for app, tool in sorted(changes.items(), key=lambda item: COMPAT["app_order"](item[0])):
|
||||
page.compat("set(%d, %s)" % (int(app), json.dumps(tool)))
|
||||
say("%s -> %s" % ("default" if app == "0" else "app %s" % app, tool))
|
||||
@@ -489,7 +494,7 @@ class Helper:
|
||||
if self.page.ws in ready:
|
||||
due = any(called(e, BINDING) for e in self.drain())
|
||||
if (watcher in ready or watcher.fileno() < 0) and watcher.changed():
|
||||
due = self.installed != COMPAT["installed_apps"](self.steam_root) or self.request_waiting()
|
||||
due = True
|
||||
if due:
|
||||
time.sleep(0.3)
|
||||
if watcher.fileno() >= 0 and select.select([watcher], [], [], 0)[0]:
|
||||
@@ -519,7 +524,8 @@ def main():
|
||||
say("no devtools port for this session; the client's mapping is kept through config.vdf")
|
||||
return 0
|
||||
os.makedirs(COMPAT["COMPAT_DIR"], exist_ok=True)
|
||||
watcher = Watcher([COMPAT["state_path"]("request.json")] + [os.path.join(lib, "steamapps", "libraryfolders.vdf") for lib in (steam_root, COMPAT["LIBRARY"] + "-sd")])
|
||||
watcher = Watcher([COMPAT["state_path"]("request.json"), COMPAT["state_path"]("games.json")] +
|
||||
[os.path.join(lib, "steamapps", "libraryfolders.vdf") for lib in (steam_root, COMPAT["LIBRARY"] + "-sd")])
|
||||
# The client has its own SteamOS manager when started as SteamOS (droiddeck-session's Deck mode).
|
||||
steamos = os.environ.get("BL_STEAMDECK") == "1" and os.environ.get("BL_STEAM_UI") != "desktop"
|
||||
helper = Helper(steam_root, port, steamos)
|
||||
|
||||
@@ -1,10 +1,16 @@
|
||||
#!/usr/bin/python3
|
||||
"""Initialize Steam's own Gamescope display settings once; subsequent choices belong to Steam.
|
||||
"""Initialize Steam's own display settings once; subsequent choices belong to Steam.
|
||||
|
||||
The UI scale, and native resolution: the client treats our gamescope as an external display and,
|
||||
unless "Enable Native Resolution on External Displays" is on, draws itself at 1920x1080 on any
|
||||
larger output - a 2340x1080 session came up as 16:9 with bars. The session's size is already the
|
||||
user's Resolution choice, so the client should use all of it."""
|
||||
user's Resolution choice, so the client should use all of it.
|
||||
|
||||
And the screensaver over a running game. The client's defaults (steamui.so's settings descriptor)
|
||||
show screensavers while a game runs, after 300 s on AC power with no button pressed - and a stick or
|
||||
trigger held is no press. Red Dead Redemption 2's cutscenes run longer than that: the slideshow
|
||||
covered the game, and the button that woke it reached the game as well (B asked to quit to the
|
||||
desktop). Customization > Screensaver > "Show screensavers when playing a game" still turns it on."""
|
||||
import math
|
||||
import os
|
||||
from pathlib import Path
|
||||
@@ -15,6 +21,8 @@ import tempfile
|
||||
|
||||
DISPLAY = "External: gamescope|||Windowed"
|
||||
NATIVE_RESOLUTION = "EnableSteamNativeExternalResolution"
|
||||
# screensaver_while_ingame: kept in config.vdf like the Gamescope settings, under this path.
|
||||
SCREENSAVER_IN_GAME = ("Customization", "Screensaver", "WhileInGame")
|
||||
TOKEN = re.compile(r'\s+|//[^\n]*|"(?:\\.|[^"\\])*"|[{}]')
|
||||
|
||||
|
||||
@@ -108,25 +116,43 @@ def seed_text(text, scale):
|
||||
return text[:at] + insertion + text[at:], True
|
||||
|
||||
|
||||
def seed_native_resolution(text):
|
||||
def seed_value(text, path, value):
|
||||
"""InstallConfigStore/<path> = value, unless the client already has a value there (the
|
||||
user's), adding only the blocks that are missing."""
|
||||
root = parse(text).get('InstallConfigStore')
|
||||
if not isinstance(root, Block):
|
||||
raise ValueError("missing InstallConfigStore")
|
||||
gamescope = root.get('Gamescope')
|
||||
if gamescope is not None and not isinstance(gamescope, Block):
|
||||
raise ValueError("invalid Gamescope settings")
|
||||
if gamescope is not None and gamescope.get(NATIVE_RESOLUTION) is not None:
|
||||
*sections, name = path
|
||||
block, depth = root, 1
|
||||
while sections:
|
||||
child = block.get(sections[0])
|
||||
if child is None:
|
||||
break
|
||||
if not isinstance(child, Block):
|
||||
raise ValueError(f"invalid {sections[0]} settings")
|
||||
block, depth = child, depth + 1
|
||||
sections.pop(0)
|
||||
if not sections and block.get(name) is not None:
|
||||
return text, False
|
||||
entry = f'"{NATIVE_RESOLUTION}" "1"'
|
||||
if gamescope is not None:
|
||||
at, indent = gamescope.end, 2
|
||||
else:
|
||||
entry = '"Gamescope"\n{\n' + entry + '\n}'
|
||||
at, indent = root.end, 1
|
||||
insertion = '\n' + '\n'.join('\t' * indent + line for line in entry.splitlines()) + '\n'
|
||||
lines = [(len(sections), f'"{name}"\t\t"{value}"')]
|
||||
for level, section in reversed(list(enumerate(sections))):
|
||||
lines = [(level, f'"{section}"'), (level, '{')] + lines + [(level, '}')]
|
||||
insertion = ''.join('\t' * (depth + level) + line + '\n' for level, line in lines)
|
||||
# Before the line the block closes on, when it has one of its own; else beside the brace.
|
||||
at = text.rfind('\n', 0, block.end) + 1
|
||||
if text[at:block.end].strip():
|
||||
at, insertion = block.end, '\n' + insertion
|
||||
return text[:at] + insertion + text[at:], True
|
||||
|
||||
|
||||
def seed_native_resolution(text):
|
||||
return seed_value(text, ('Gamescope', NATIVE_RESOLUTION), '1')
|
||||
|
||||
|
||||
def seed_no_screensaver_in_game(text):
|
||||
return seed_value(text, SCREENSAVER_IN_GAME, '0')
|
||||
|
||||
|
||||
def atomic_write(path, text):
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
fd, temporary = tempfile.mkstemp(prefix='.' + path.name, dir=path.parent)
|
||||
@@ -140,31 +166,36 @@ def atomic_write(path, text):
|
||||
|
||||
|
||||
def initialize(steam_root, width, height):
|
||||
scale = initial_scale(width, height)
|
||||
return seed_once(steam_root, 'droiddeck-ui-scale-initialized', lambda text: seed_text(text, scale),
|
||||
f'== steam: initial handheld UI scale {scale:.3f}')
|
||||
|
||||
|
||||
def seed_once(steam_root, marker_name, seed, message):
|
||||
"""Applies seed to config.vdf the first time only: the marker keeps a later choice - including
|
||||
a return to the client's own default, which the client may store by dropping the key - the
|
||||
user's."""
|
||||
config = Path(steam_root) / 'config/config.vdf'
|
||||
marker = config.with_name('droiddeck-ui-scale-initialized')
|
||||
marker = config.with_name(marker_name)
|
||||
if marker.exists():
|
||||
return False
|
||||
text = config.read_text() if config.exists() else '"InstallConfigStore"\n{\n}\n'
|
||||
updated, changed = seed_text(text, initial_scale(width, height))
|
||||
updated, changed = seed(text)
|
||||
if changed:
|
||||
atomic_write(config, updated)
|
||||
print(f'== steam: initial handheld UI scale {initial_scale(width, height):.3f}')
|
||||
print(message)
|
||||
atomic_write(marker, '1\n')
|
||||
return changed
|
||||
|
||||
|
||||
def initialize_native_resolution(steam_root):
|
||||
config = Path(steam_root) / 'config/config.vdf'
|
||||
marker = config.with_name('droiddeck-native-resolution-initialized')
|
||||
if marker.exists():
|
||||
return False
|
||||
text = config.read_text() if config.exists() else '"InstallConfigStore"\n{\n}\n'
|
||||
updated, changed = seed_native_resolution(text)
|
||||
if changed:
|
||||
atomic_write(config, updated)
|
||||
print('== steam: native resolution on the session display')
|
||||
atomic_write(marker, '1\n')
|
||||
return changed
|
||||
return seed_once(steam_root, 'droiddeck-native-resolution-initialized', seed_native_resolution,
|
||||
'== steam: native resolution on the session display')
|
||||
|
||||
|
||||
def initialize_screensaver(steam_root):
|
||||
return seed_once(steam_root, 'droiddeck-screensaver-initialized', seed_no_screensaver_in_game,
|
||||
'== steam: no screensaver over a running game')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
@@ -174,9 +205,10 @@ if __name__ == '__main__':
|
||||
except (OSError, ValueError, RecursionError) as error:
|
||||
print('== steam: left UI scale unchanged: ' + str(error), file=sys.stderr)
|
||||
status = 1
|
||||
try:
|
||||
initialize_native_resolution(sys.argv[1])
|
||||
except (OSError, ValueError, RecursionError) as error:
|
||||
print('== steam: left native resolution unchanged: ' + str(error), file=sys.stderr)
|
||||
status = 1
|
||||
for what, step in (('native resolution', initialize_native_resolution), ('screensaver', initialize_screensaver)):
|
||||
try:
|
||||
step(sys.argv[1])
|
||||
except (OSError, ValueError, RecursionError) as error:
|
||||
print(f'== steam: left {what} unchanged: {error}', file=sys.stderr)
|
||||
status = 1
|
||||
sys.exit(status)
|
||||
@@ -92,10 +92,12 @@ TOOL_MANIFEST_VDF = """"manifest"
|
||||
# relies on compatdata/0 itself. The launch-time check below is the protection instead.
|
||||
|
||||
# The Components page's choices, enforced in the one place every game launch passes: the app keeps
|
||||
# desired.tsv (tool dir, Proton build, component, file, sha256, source copy) and an unpacked copy of
|
||||
# each package in use. A file that no longer matches - whatever changed it - is put back before
|
||||
# Proton starts. Only for the Proton build the choice was made for: after a Steam update the build
|
||||
# differs and the Proton's own new files are left alone until the user chooses again.
|
||||
# desired.tsv (scope, tool dir, Proton build, component, file, sha256, source copy) and an unpacked
|
||||
# copy of each package in use. A game's rows replace General rows for that component. A `-` source
|
||||
# removes a managed file absent from the selected package, so one game's package cannot leak into
|
||||
# the next game. A file that no longer matches - whatever changed it - is put back before Proton
|
||||
# starts. Only the matching Proton build is changed; after a Steam update the build differs and the
|
||||
# Proton's own new files are left alone until the user chooses again.
|
||||
# A store game (GOG, Epic, Amazon) is started through the launcher .bat DroidDeck wrote beside it.
|
||||
# An Epic game needs a fresh sign-in code, which only the app can mint: droiddeck-store-launch asks
|
||||
# for it and the app writes it into the game's folder, so a launch from the client's own Play
|
||||
@@ -149,21 +151,56 @@ bl_components() {
|
||||
[ "${verb:-}" = waitforexitandrun ] || return 0
|
||||
case "${STEAM_COMPAT_DATA_PATH:-}" in ''|*/compatdata/0|*/compatdata/0/|*/compatdata/0-*) return 0 ;; esac
|
||||
[ -f "$cm_list" ] || return 0
|
||||
cm_app=${STEAM_COMPAT_DATA_PATH%/}
|
||||
cm_app=${STEAM_COMPAT_DATA_PATH}
|
||||
while [[ "$cm_app" == */ ]]; do cm_app=${cm_app%/}; done
|
||||
cm_app=${cm_app##*/}
|
||||
if [[ "$cm_app" =~ ^(-?)([0-9]+)$ ]]; then
|
||||
cm_sign=${BASH_REMATCH[1]}
|
||||
cm_digits=${BASH_REMATCH[2]}
|
||||
while [[ ${#cm_digits} -gt 1 && "$cm_digits" == 0* ]]; do cm_digits=${cm_digits#0}; done
|
||||
if [[ ${#cm_digits} -le 10 ]]; then
|
||||
cm_app=$((10#$cm_digits))
|
||||
[ "$cm_sign" = "-" ] && cm_app=$((-cm_app))
|
||||
if (( cm_app >= -2147483648 && cm_app <= 4294967295 && cm_app != 0 )); then
|
||||
(( cm_app < 0 )) && cm_app=$((cm_app + 4294967296))
|
||||
else
|
||||
cm_app=""
|
||||
fi
|
||||
else
|
||||
cm_app=""
|
||||
fi
|
||||
else
|
||||
cm_app=""
|
||||
fi
|
||||
if [ -z "$cm_app" ]; then
|
||||
echo "droiddeck-proton: components: invalid game prefix, left as it is" >&2
|
||||
return 0
|
||||
fi
|
||||
cm_tool=${base##*/}
|
||||
cm_build=$(awk 'NR == 1 { print $2 }' "$base/version" 2>/dev/null)
|
||||
cm_fixed=0
|
||||
cm_checked=0
|
||||
cm_selected=$(awk -F '\\t' -v app="$cm_app" -v tool="$cm_tool" -v build="$cm_build" '
|
||||
$2 == tool && $3 == build {
|
||||
rows[++count] = $0
|
||||
scopes[count] = $1
|
||||
comps[count] = $4
|
||||
if ($1 == app) specific[$4] = 1
|
||||
}
|
||||
END {
|
||||
for (i = 1; i <= count; i++)
|
||||
if (scopes[i] == app || (scopes[i] == "*" && !specific[comps[i]])) print rows[i]
|
||||
}
|
||||
' "$cm_list")
|
||||
# One sha256sum for every file: each program started here pays a dozen traced library lookups
|
||||
# under the game's search path before it does anything.
|
||||
local cm_rows=() cm_files=() row h p
|
||||
local -A cm_sums=()
|
||||
while IFS=$'\\t' read -r t want comp rel sum src; do
|
||||
[ "$t" = "$cm_tool" ] && [ "$want" = "$cm_build" ] || continue
|
||||
while IFS=$'\\t' read -r scope t want comp rel sum src; do
|
||||
[ -n "$scope" ] || continue
|
||||
cm_rows+=("$comp"$'\\t'"$rel"$'\\t'"$sum"$'\\t'"$src")
|
||||
[ -f "$base/$rel" ] && cm_files+=("$base/$rel")
|
||||
done < "$cm_list"
|
||||
[ "$src" != "-" ] && [ -f "$base/$rel" ] && cm_files+=("$base/$rel")
|
||||
done <<< "$cm_selected"
|
||||
if [ ${#cm_files[@]} -gt 0 ]; then
|
||||
while read -r h p; do cm_sums["$p"]=$h; done < <(sha256sum -- "${cm_files[@]}" 2>/dev/null)
|
||||
fi
|
||||
@@ -171,6 +208,10 @@ bl_components() {
|
||||
IFS=$'\\t' read -r comp rel sum src <<< "$row"
|
||||
cm_checked=$((cm_checked + 1))
|
||||
f="$base/$rel"
|
||||
if [ "$src" = "-" ]; then
|
||||
if [ -e "$f" ]; then rm -f "$f" && cm_fixed=$((cm_fixed + 1)); fi
|
||||
continue
|
||||
fi
|
||||
if [ -f "$f" ] && [ "${cm_sums[$f]:-}" = "$sum" ]; then continue; fi
|
||||
if [ ! -f "$src" ]; then
|
||||
echo "droiddeck-proton: components: $comp source missing ($src), left as it is" >&2
|
||||
@@ -985,16 +1026,30 @@ def app_order(app):
|
||||
return (len(app), app)
|
||||
|
||||
|
||||
def plan_mapping(current, installed, runnable, default, auto, native=None, picks=()):
|
||||
DEFERRED_GAME_TOOL = object()
|
||||
|
||||
|
||||
def plan_mapping(current, installed, runnable, default, auto, native=None, picks=(), overrides=None):
|
||||
runnable = {n.lower() for n in runnable}
|
||||
installed = set(installed)
|
||||
picks = set(picks)
|
||||
native = native or {}
|
||||
overrides = overrides or {}
|
||||
changes, kept = {}, {}
|
||||
if current.get("0", "") != default:
|
||||
changes["0"] = default
|
||||
for app in sorted((set(current) | installed | picks | set(auto)) - {"0"}, key=app_order):
|
||||
for app in sorted((set(current) | installed | picks | set(auto) | set(overrides)) - {"0"}, key=app_order):
|
||||
name = current.get(app, "")
|
||||
if app in overrides:
|
||||
target = overrides[app]
|
||||
if target is DEFERRED_GAME_TOOL:
|
||||
continue
|
||||
target = target or default
|
||||
if name != target:
|
||||
changes[app] = target
|
||||
if overrides[app] is None:
|
||||
kept[app] = target
|
||||
continue
|
||||
mine = auto.get(app)
|
||||
target = native.get(app, default)
|
||||
stale = unrunnable(name, runnable) or (app in native and linux_runtime_tool(name))
|
||||
@@ -1053,6 +1108,34 @@ def requested_tool(request, catalog):
|
||||
return None
|
||||
|
||||
|
||||
def game_requests(directory=None):
|
||||
value = read_json(state_path("games.json", directory))
|
||||
if value.get("version") != 1 or not isinstance(value.get("games"), dict):
|
||||
return {}
|
||||
return value["games"]
|
||||
|
||||
|
||||
def requested_games(requests, catalog, runnable=None):
|
||||
"""App id -> requested tool, None for inherit, or DEFERRED_GAME_TOOL while unavailable."""
|
||||
runnable = None if runnable is None else set(runnable)
|
||||
resolved = {}
|
||||
for app, request in requests.items():
|
||||
if not isinstance(app, str) or not re.fullmatch(r"[1-9][0-9]*", app) or int(app) > 0xFFFFFFFF:
|
||||
continue
|
||||
if request is None:
|
||||
resolved[app] = None
|
||||
continue
|
||||
if (not isinstance(request, dict) or not isinstance(request.get("dir"), str) or
|
||||
not request["dir"] or not isinstance(request.get("valve"), bool)):
|
||||
continue
|
||||
tool = requested_tool(request, catalog)
|
||||
if tool is None or runnable is not None and tool not in runnable:
|
||||
resolved[app] = DEFERRED_GAME_TOOL
|
||||
else:
|
||||
resolved[app] = tool
|
||||
return resolved
|
||||
|
||||
|
||||
def now_ms():
|
||||
import time
|
||||
return int(time.time() * 1000)
|
||||
@@ -1174,7 +1257,9 @@ def register_default(config_path, apps=(), protect=(), default=None, catalog=Non
|
||||
else:
|
||||
default = state.get("default") if state.get("default") in names else TOOL
|
||||
steam_root = os.path.dirname(os.path.dirname(os.path.abspath(config_path)))
|
||||
changes, auto = plan_mapping(current, apps, names, default, followers(state, current), native_targets(steam_root, apps), picks)
|
||||
overrides = requested_games(game_requests(directory), catalog)
|
||||
changes, auto = plan_mapping(
|
||||
current, apps, names, default, followers(state, current), native_targets(steam_root, apps), picks, overrides)
|
||||
for app, tool in changes.items():
|
||||
set_mapping(tokens, mapping, app, tool)
|
||||
text = serialize(tokens)
|
||||
|
||||
@@ -421,6 +421,7 @@ static int is_link_query(unsigned long request) {
|
||||
}
|
||||
|
||||
void bl_kgsl_chip_id_fixup(unsigned long request, void *arg, int rc); /* kgslid.c */
|
||||
#include "../../quest/kgsl_compat.h"
|
||||
int bl_kgsl_poll(int (*real)(int, unsigned long, void *), int fd, unsigned long request,
|
||||
void *arg, int *rc) __attribute__((visibility("hidden")));
|
||||
int bl_ntsync_ioctl(int fd, unsigned long request, void *arg, int *rc) __attribute__((visibility("hidden")));
|
||||
@@ -440,7 +441,7 @@ int ioctl(int fd, unsigned long request, ...) {
|
||||
if (bl_ntsync_ioctl(fd, request, arg, &rc)) return rc;
|
||||
if (bl_drm_gem_close(fd, request, arg, &rc)) return rc;
|
||||
if (real == NULL) real = (ioctl_fn) dlsym(RTLD_NEXT, "ioctl");
|
||||
if (!bl_kgsl_poll(real, fd, request, arg, &rc)) rc = real(fd, request, arg);
|
||||
if (!bl_kgsl_poll(real, fd, request, arg, &rc)) rc = quest_kgsl_ioctl(real, fd, request, arg);
|
||||
bl_kgsl_chip_id_fixup(request, arg, rc);
|
||||
if (arg == NULL || !is_link_query(request)) return rc;
|
||||
int saved = errno;
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
/* SPDX-License-Identifier: GPL-3.0-or-later */
|
||||
/* Shared with the Android driver wrapper so the two translation paths cannot drift. */
|
||||
#include "../../quest/kgsl_compat.c"
|
||||
@@ -0,0 +1,26 @@
|
||||
/* SPDX-License-Identifier: GPL-3.0-or-later
|
||||
* Loaded as the AdrenoTools driver; DT_NEEDED points to the original Turnip.
|
||||
* Vulkan/HAL symbols are resolved from that dependency. Its ioctl calls resolve here.
|
||||
*/
|
||||
#define _GNU_SOURCE
|
||||
#include "kgsl_compat.h"
|
||||
#include <dlfcn.h>
|
||||
#include <pthread.h>
|
||||
#include <stdarg.h>
|
||||
#include <sys/syscall.h>
|
||||
#include <unistd.h>
|
||||
|
||||
static int (*next_ioctl)(int, int, ...);
|
||||
static pthread_once_t once = PTHREAD_ONCE_INIT;
|
||||
static void resolve_ioctl(void) { next_ioctl = dlsym(RTLD_NEXT, "ioctl"); }
|
||||
static int forward(int fd, unsigned long request, void *arg) {
|
||||
pthread_once(&once, resolve_ioctl);
|
||||
return next_ioctl ? next_ioctl(fd, (int)request, arg) : (int)syscall(SYS_ioctl, fd, request, arg);
|
||||
}
|
||||
__attribute__((visibility("default"))) int ioctl(int fd, int request, ...) {
|
||||
va_list ap;
|
||||
va_start(ap, request);
|
||||
void *arg = va_arg(ap, void *);
|
||||
va_end(ap);
|
||||
return quest_kgsl_ioctl(forward, fd, (unsigned int)request, arg);
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Build the Quest allocation adapter around the unchanged bundled Android Turnip."""
|
||||
import io
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import tarfile
|
||||
import tempfile
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
OUTPUT = ROOT / 'app/build/prepared-assets/graphics_driver/adrenotools-turnip25.1.0-quest1.tzst'
|
||||
|
||||
|
||||
def build(ndk, output=OUTPUT):
|
||||
hosts = list((Path(ndk) / 'toolchains/llvm/prebuilt').glob('*'))
|
||||
if len(hosts) != 1:
|
||||
raise ValueError('Expected one NDK host toolchain')
|
||||
llvm = hosts[0] / 'bin'
|
||||
original = ROOT / 'app/src/main/assets/graphics_driver/adrenotools-turnip25.1.0.tzst'
|
||||
data = subprocess.run(['zstd', '-dc', str(original)], capture_output=True, check=True).stdout
|
||||
with tempfile.TemporaryDirectory(prefix='quest-driver-') as folder:
|
||||
work = Path(folder)
|
||||
with tarfile.open(fileobj=io.BytesIO(data)) as archive:
|
||||
# Only read the known driver entry; no archive paths are extracted.
|
||||
driver = archive.extractfile('vulkan.ad07xx.so').read()
|
||||
(work / 'vulkan.ad07xx.so').write_bytes(driver)
|
||||
wrapper = work / 'libquest_turnip.so'
|
||||
subprocess.run([
|
||||
str(llvm / 'aarch64-linux-android26-clang'), '-shared', '-fPIC', '-O2',
|
||||
'-Wall', '-Wextra', '-Werror', '-fvisibility=hidden',
|
||||
'-Wl,-z,max-page-size=16384', '-Wl,-soname,libquest_turnip.so',
|
||||
'-Wl,--no-as-needed', str(work / 'vulkan.ad07xx.so'), '-Wl,--as-needed',
|
||||
str(ROOT / 'tools/quest/android_wrapper.c'), str(ROOT / 'tools/quest/kgsl_compat.c'),
|
||||
'-ldl', '-llog', '-o', str(wrapper),
|
||||
], check=True)
|
||||
subprocess.run([str(llvm / 'llvm-strip'), '--strip-unneeded', str(wrapper)], check=True)
|
||||
metadata = json.dumps({
|
||||
'libraryName': 'libquest_turnip.so',
|
||||
'name': 'Turnip Adreno 7xx - Quest GPUOBJ experimental',
|
||||
'description': 'Bundled A7xx driver with the experimental Quest 3/3S allocation adapter.',
|
||||
'driverVersion': 'Bundled Mesa + Quest GPUOBJ v1',
|
||||
}, indent=2).encode() + b'\n'
|
||||
stream = io.BytesIO()
|
||||
with tarfile.open(fileobj=stream, mode='w', format=tarfile.USTAR_FORMAT) as archive:
|
||||
for name, content in [('meta.json', metadata), ('libquest_turnip.so', wrapper.read_bytes()),
|
||||
('vulkan.ad07xx.so', driver)]:
|
||||
entry = tarfile.TarInfo(name)
|
||||
entry.size = len(content)
|
||||
entry.mode = 0o644
|
||||
archive.addfile(entry, io.BytesIO(content))
|
||||
compressed = subprocess.run(['zstd', '-q', '-19', '-c'], input=stream.getvalue(),
|
||||
capture_output=True, check=True).stdout
|
||||
output.parent.mkdir(parents=True, exist_ok=True)
|
||||
output.write_bytes(compressed)
|
||||
print(output)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
build(sys.argv[1])
|
||||
@@ -0,0 +1,78 @@
|
||||
/* SPDX-License-Identifier: GPL-3.0-or-later
|
||||
* Quest experimental build, 2026-10-11.
|
||||
* Horizon permits GPUOBJ allocation, but rejects the legacy GPUMEM alloc/free calls.
|
||||
* Retry only those two calls after EACCES/EPERM. No change to device permissions.
|
||||
*/
|
||||
#include "kgsl_compat.h"
|
||||
#include <errno.h>
|
||||
#include <limits.h>
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#ifdef __ANDROID__
|
||||
#include <android/log.h>
|
||||
#endif
|
||||
|
||||
#if __SIZEOF_POINTER__ == 8
|
||||
_Static_assert(sizeof(struct kgsl_gpumem_alloc_id) == 48, "KGSL alloc ABI");
|
||||
_Static_assert(sizeof(struct kgsl_gpuobj_alloc) == 48, "GPUOBJ alloc ABI");
|
||||
_Static_assert(sizeof(struct kgsl_gpuobj_free) == 32, "GPUOBJ free ABI");
|
||||
_Static_assert(sizeof(struct kgsl_gpuobj_info) == 48, "GPUOBJ info ABI");
|
||||
#endif
|
||||
|
||||
static void report(const char *operation, int error) {
|
||||
static unsigned successes, failures;
|
||||
unsigned *counter = error ? &failures : &successes;
|
||||
/* Log the first success and at most eight failures per process. */
|
||||
if (__atomic_fetch_add(counter, 1, __ATOMIC_RELAXED) >= (error ? 8u : 1u)) return;
|
||||
int saved = errno;
|
||||
#ifdef __ANDROID__
|
||||
__android_log_print(error ? ANDROID_LOG_ERROR : ANDROID_LOG_INFO, "QuestKGSL",
|
||||
"%s: GPUOBJ compatibility path, errno=%d", operation, error);
|
||||
#else
|
||||
fprintf(stderr, "[QuestKGSL] %s: GPUOBJ compatibility path, errno=%d\n", operation, error);
|
||||
#endif
|
||||
errno = saved;
|
||||
}
|
||||
|
||||
int quest_kgsl_ioctl(quest_ioctl_fn real, int fd, unsigned long request, void *arg) {
|
||||
int rc = real(fd, request, arg);
|
||||
if (rc != -1 || (errno != EACCES && errno != EPERM) || arg == NULL) return rc;
|
||||
|
||||
if (request == IOCTL_KGSL_GPUMEM_ALLOC_ID) {
|
||||
struct kgsl_gpumem_alloc_id *old = arg;
|
||||
struct kgsl_gpuobj_alloc alloc = {.size = old->size, .flags = old->flags};
|
||||
rc = real(fd, IOCTL_KGSL_GPUOBJ_ALLOC, &alloc);
|
||||
if (rc != 0) { report("alloc failed", errno); return rc; }
|
||||
struct kgsl_gpuobj_info info = {.id = alloc.id};
|
||||
rc = real(fd, IOCTL_KGSL_GPUOBJ_INFO, &info);
|
||||
int error = errno;
|
||||
if (rc == 0 && (info.size > SIZE_MAX || alloc.mmapsize > SIZE_MAX ||
|
||||
info.gpuaddr > ULONG_MAX || info.flags > UINT_MAX)) {
|
||||
rc = -1;
|
||||
error = EOVERFLOW;
|
||||
}
|
||||
if (rc != 0) {
|
||||
/* The caller never receives this allocation, so clean it up on an INFO failure. */
|
||||
struct kgsl_gpuobj_free release = {.id = alloc.id};
|
||||
if (real(fd, IOCTL_KGSL_GPUOBJ_FREE, &release) != 0)
|
||||
report("cleanup failed", errno);
|
||||
errno = error;
|
||||
report("info failed", error);
|
||||
return rc;
|
||||
}
|
||||
old->id = alloc.id;
|
||||
old->flags = (unsigned int)info.flags;
|
||||
old->size = info.size;
|
||||
old->mmapsize = alloc.mmapsize;
|
||||
old->gpuaddr = info.gpuaddr;
|
||||
report("allocation succeeded", 0);
|
||||
return 0;
|
||||
}
|
||||
if (request == IOCTL_KGSL_GPUMEM_FREE_ID) {
|
||||
const struct kgsl_gpumem_free_id *old = arg;
|
||||
struct kgsl_gpuobj_free release = {.id = old->id};
|
||||
rc = real(fd, IOCTL_KGSL_GPUOBJ_FREE, &release);
|
||||
if (rc != 0) report("free failed", errno);
|
||||
}
|
||||
return rc;
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
/* SPDX-License-Identifier: GPL-3.0-or-later */
|
||||
#ifndef DROIDDECK_QUEST_KGSL_COMPAT_H
|
||||
#define DROIDDECK_QUEST_KGSL_COMPAT_H
|
||||
|
||||
/* Use the vendored Qualcomm UAPI, including its architecture-dependent ioctl sizes. */
|
||||
#ifndef __user
|
||||
#define __user
|
||||
#endif
|
||||
#include "../../app/src/main/cpp/adrenotools/src/hook/kgsl.h"
|
||||
|
||||
typedef int (*quest_ioctl_fn)(int, unsigned long, void *);
|
||||
__attribute__((visibility("hidden")))
|
||||
int quest_kgsl_ioctl(quest_ioctl_fn real, int fd, unsigned long request, void *arg);
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,77 @@
|
||||
/* SPDX-License-Identifier: GPL-3.0-or-later */
|
||||
#include "kgsl_compat.h"
|
||||
#include <assert.h>
|
||||
#include <errno.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
|
||||
static unsigned long calls[8];
|
||||
static int count, old_error, alloc_error, info_error, free_error;
|
||||
static unsigned long address;
|
||||
static int mock(int fd, unsigned long request, void *arg) {
|
||||
assert(fd == 42 && count < 8);
|
||||
calls[count++] = request;
|
||||
if (request == IOCTL_KGSL_GPUMEM_ALLOC_ID || request == IOCTL_KGSL_GPUMEM_FREE_ID) {
|
||||
if (old_error) { errno = old_error; return -1; }
|
||||
return 0;
|
||||
}
|
||||
if (request == IOCTL_KGSL_GPUOBJ_ALLOC) {
|
||||
if (alloc_error) { errno = alloc_error; return -1; }
|
||||
struct kgsl_gpuobj_alloc *p = arg;
|
||||
assert(p->size == 123 && p->flags == 0x10000 && !p->metadata && !p->metadata_len);
|
||||
p->id = 77; p->size = 4096; p->mmapsize = 8192;
|
||||
return 0;
|
||||
}
|
||||
if (request == IOCTL_KGSL_GPUOBJ_INFO) {
|
||||
struct kgsl_gpuobj_info *p = arg;
|
||||
assert(p->id == 77);
|
||||
if (info_error) { errno = info_error; return -1; }
|
||||
p->gpuaddr = address; p->flags = 0x20000; p->size = 4096;
|
||||
return 0;
|
||||
}
|
||||
if (request == IOCTL_KGSL_GPUOBJ_FREE) {
|
||||
struct kgsl_gpuobj_free *p = arg;
|
||||
assert(p->id == 77 && !p->flags && !p->priv && !p->type && !p->len);
|
||||
if (free_error) { errno = free_error; return -1; }
|
||||
return 0;
|
||||
}
|
||||
errno = EACCES;
|
||||
return -1;
|
||||
}
|
||||
static struct kgsl_gpumem_alloc_id reset(void) {
|
||||
count = old_error = alloc_error = info_error = free_error = 0;
|
||||
address = 0x100000;
|
||||
return (struct kgsl_gpumem_alloc_id){.size = 123, .flags = 0x10000};
|
||||
}
|
||||
int main(void) {
|
||||
struct kgsl_gpumem_alloc_id p = reset();
|
||||
assert(quest_kgsl_ioctl(mock, 42, IOCTL_KGSL_GPUMEM_ALLOC_ID, &p) == 0 && count == 1);
|
||||
p = reset(); old_error = EACCES;
|
||||
assert(quest_kgsl_ioctl(mock, 42, IOCTL_KGSL_GPUMEM_ALLOC_ID, &p) == 0);
|
||||
assert(count == 3 && p.id == 77 && p.size == 4096 && p.mmapsize == 8192);
|
||||
assert(p.flags == 0x20000 && p.gpuaddr == address);
|
||||
p = reset(); old_error = EPERM; address = 0;
|
||||
assert(quest_kgsl_ioctl(mock, 42, IOCTL_KGSL_GPUMEM_ALLOC_ID, &p) == 0 && p.gpuaddr == 0);
|
||||
p = reset(); old_error = ENOMEM;
|
||||
assert(quest_kgsl_ioctl(mock, 42, IOCTL_KGSL_GPUMEM_ALLOC_ID, &p) == -1 && errno == ENOMEM && count == 1);
|
||||
p = reset(); old_error = EACCES; alloc_error = ENOMEM;
|
||||
assert(quest_kgsl_ioctl(mock, 42, IOCTL_KGSL_GPUMEM_ALLOC_ID, &p) == -1 && errno == ENOMEM && count == 2);
|
||||
assert(p.id == 0 && p.size == 123);
|
||||
p = reset(); old_error = EACCES; info_error = EIO;
|
||||
assert(quest_kgsl_ioctl(mock, 42, IOCTL_KGSL_GPUMEM_ALLOC_ID, &p) == -1 && errno == EIO);
|
||||
assert(count == 4 && calls[3] == IOCTL_KGSL_GPUOBJ_FREE && p.id == 0);
|
||||
p = reset(); old_error = EACCES; info_error = EIO; free_error = ENOSPC;
|
||||
assert(quest_kgsl_ioctl(mock, 42, IOCTL_KGSL_GPUMEM_ALLOC_ID, &p) == -1 && errno == EIO && count == 4);
|
||||
p = reset(); old_error = EACCES;
|
||||
assert(quest_kgsl_ioctl(mock, 42, IOCTL_KGSL_GPUMEM_ALLOC_ID, NULL) == -1 && count == 1);
|
||||
p = reset(); old_error = EACCES;
|
||||
assert(quest_kgsl_ioctl(mock, 42, 0x1234, &p) == -1 && errno == EACCES && count == 1);
|
||||
struct kgsl_gpumem_free_id release = {.id = 77};
|
||||
reset(); old_error = EACCES;
|
||||
assert(quest_kgsl_ioctl(mock, 42, IOCTL_KGSL_GPUMEM_FREE_ID, &release) == 0 && count == 2);
|
||||
reset(); old_error = EPERM; free_error = EIO;
|
||||
assert(quest_kgsl_ioctl(mock, 42, IOCTL_KGSL_GPUMEM_FREE_ID, &release) == -1 && errno == EIO && count == 2);
|
||||
reset();
|
||||
assert(quest_kgsl_ioctl(mock, 42, IOCTL_KGSL_GPUMEM_FREE_ID, &release) == 0 && count == 1);
|
||||
puts("PASS: 12 GPUOBJ translation, passthrough, failure and cleanup scenarios");
|
||||
}
|
||||
@@ -16,7 +16,9 @@ SOURCE_PATHS = ['app/build.gradle', 'app/src/main/cpp/fakeinput_steam.cpp', 'app
|
||||
'tools/linuxfs', 'tools/proot', 'tools/aaudio-sink', 'tools/directaudio',
|
||||
'tools/gamescope/release.env', 'tools/droiddeck-esync/release.env',
|
||||
'tools/mangoapp', 'tools/msitools', 'tools/build_local.sh',
|
||||
'tools/release/runtime_inputs.py', 'app/src/main/assets/desktop-removal']
|
||||
'tools/release/runtime_inputs.py', 'app/src/main/assets/desktop-removal',
|
||||
'tools/quest', 'app/src/main/cpp/adrenotools/src/hook/kgsl.h',
|
||||
'app/src/main/assets/graphics_driver/adrenotools-turnip25.1.0.tzst']
|
||||
|
||||
|
||||
def digest(path):
|
||||
@@ -48,11 +50,14 @@ def outputs(root):
|
||||
for library in ['libproot.so', 'libproot-loader.so', 'libdirectaudiorelay.so']:
|
||||
result['lib/arm64-v8a/' + library] = 'app/src/main/jniLibs/arm64-v8a/' + library
|
||||
result['assets/pulseaudio.tzst'] = 'app/build/prepared-assets/pulseaudio.tzst'
|
||||
result['assets/graphics_driver/adrenotools-turnip25.1.0-quest1.tzst'] = \
|
||||
'app/build/prepared-assets/graphics_driver/adrenotools-turnip25.1.0-quest1.tzst'
|
||||
return result
|
||||
|
||||
|
||||
def required():
|
||||
paths = ['assets/linuxfs/' + name for name in ['libfakeinput.so', 'libblsession.so',
|
||||
paths = ['assets/graphics_driver/adrenotools-turnip25.1.0-quest1.tzst']
|
||||
paths += ['assets/linuxfs/' + name for name in ['libfakeinput.so', 'libblsession.so',
|
||||
'libblfastpath.so', 'libssbs.so', 'usr/local/bin/droiddeck-clipboard',
|
||||
'usr/local/bin/gamescope', 'usr/local/lib/droiddeck/uruntime']]
|
||||
for arch in ['x86_64', 'i386']:
|
||||
|
||||
@@ -7,3 +7,4 @@ standard com.droiddeck.launcher -
|
||||
pubg com.tencent.ig -pubg
|
||||
antutu com.antutu.benchmark.full -antutu
|
||||
ludashi com.ludashi.benchmark -ludashi
|
||||
quest com.droiddeck.quest -quest
|
||||
@@ -208,6 +208,22 @@ class AgentTest(unittest.TestCase):
|
||||
missing = self.ask({"kind": "cdp", "expression": "1", "target": "Nope"})
|
||||
self.assertEqual("NO_TARGET", missing["error"]["code"])
|
||||
|
||||
def test_steam_selection(self):
|
||||
with patch.object(agent, "cdp_eval", return_value={"value": "3180310"}) as evaluate:
|
||||
answer = self.ask({"kind": "steam-selection"})
|
||||
self.assertEqual(3180310, answer["appId"])
|
||||
self.assertIn("document.activeElement", evaluate.call_args.args[1])
|
||||
self.assertEqual("Steam Big Picture Mode", evaluate.call_args.kwargs["target"])
|
||||
|
||||
def test_steam_selection_allows_no_highlight(self):
|
||||
with patch.object(agent, "cdp_eval", return_value={"value": None}):
|
||||
self.assertIsNone(self.ask({"kind": "steam-selection"})["appId"])
|
||||
|
||||
def test_steam_selection_rejects_invalid_app_id(self):
|
||||
with patch.object(agent, "cdp_eval", return_value={"value": "4294967296"}):
|
||||
answer = self.ask({"kind": "steam-selection"})
|
||||
self.assertEqual("INVALID_SELECTION", answer["error"]["code"])
|
||||
|
||||
def test_cdp_exception(self):
|
||||
server = FakeDevTools({"result": {"result": {"type": "object"}, "exceptionDetails": {
|
||||
"text": "Uncaught", "exception": {"description": "ReferenceError: SteamClient is not defined"}}}})
|
||||
|
||||
@@ -746,6 +746,16 @@ class SelectTest(SyncTestCase):
|
||||
self.assertFalse((root / "wanted.tsv").exists())
|
||||
self.assertFalse((root / "dist").exists())
|
||||
|
||||
def test_droiddeck_proton_has_esync_built_in(self):
|
||||
root = self.store()
|
||||
tool = make_tool(self.tools, "DroidDeck-Proton 11-7.5", "1791000000 DroidDeck-Proton-11-7.5", builtin=True, ge=True, fsync=True)
|
||||
command, env, said = self.select(tool, self.env())
|
||||
self.assertEqual(command[0], str(tool / "proton"))
|
||||
self.assertNotIn("BL_SYNC_PACK", env)
|
||||
self.assertEqual(said, "droiddeck-esync: DroidDeck-Proton 11-7.5 has esync built in\n")
|
||||
self.assertFalse((root / "wanted.tsv").exists())
|
||||
self.assertFalse((root / "dist").exists())
|
||||
|
||||
def test_wanted_rows_are_deduplicated(self):
|
||||
root = self.store()
|
||||
tool = make_tool(self.tools, "GE-Proton11-7", GE_LINE, ge=True)
|
||||
@@ -906,6 +916,15 @@ class ReconcileTest(SyncTestCase):
|
||||
self.assertTrue(self.dist_of("ge-GE-Proton11-7-r1", ge).is_dir())
|
||||
self.assertIn("ge-GE-Proton11-7-r1", (root / "tools.tsv").read_text())
|
||||
|
||||
def test_droiddeck_proton_is_scanned_but_our_own_tools_are_not(self):
|
||||
steam = self.tmp / "steam"
|
||||
tools = steam / "compatibilitytools.d"
|
||||
ours = make_tool(tools, "DroidDeck-Proton 11-7.5", "1791000000 DroidDeck-Proton-11-7.5", salt=b"dd", builtin=True, ge=True)
|
||||
make_tool(tools, "droiddeck-proton-arm64", salt=b"own")
|
||||
make_tool(tools, "droiddeck-proton-11-arm64", salt=b"own11")
|
||||
with mock.patch.dict(GLOBALS, {"SD_LIBRARY": str(self.tmp / "sd")}):
|
||||
self.assertEqual(SYNC["find_tools"](str(steam)), [str(ours)])
|
||||
|
||||
def test_steam_compatibility_reports_sync(self):
|
||||
steam = self.tmp / "steam"
|
||||
make_tool(steam / "steamapps/common", "Proton Experimental (ARM64)")
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
SOURCE = Path(__file__).resolve().parents[2] / "app/src/main/cpp/fakeinput_steam.cpp"
|
||||
|
||||
PROGRAM = r"""
|
||||
#include <assert.h>
|
||||
#include <errno.h>
|
||||
#include <stdarg.h>
|
||||
#include <sys/ioctl.h>
|
||||
#include <termios.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#ifdef BACKEND
|
||||
int ioctl(int fd, unsigned long request, ...) {
|
||||
va_list ap;
|
||||
va_start(ap, request);
|
||||
int *value = va_arg(ap, int *);
|
||||
va_end(ap);
|
||||
assert(fd == -1 && request == 0x12345678 && value);
|
||||
*value = 0x51;
|
||||
errno = EACCES;
|
||||
return -1;
|
||||
}
|
||||
#else
|
||||
int main(int argc, char **argv) {
|
||||
if (argc > 1) {
|
||||
int value = 0;
|
||||
assert(ioctl(-1, 0x12345678, &value) == -1);
|
||||
assert(value == 0x51 && errno == EACCES);
|
||||
} else {
|
||||
int fds[2];
|
||||
assert(pipe(fds) == 0);
|
||||
struct termios term;
|
||||
assert(ioctl(fds[0], TCGETS, &term) == -1 && errno == ENOTTY);
|
||||
close(fds[0]);
|
||||
close(fds[1]);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
#endif
|
||||
"""
|
||||
|
||||
|
||||
@unittest.skipUnless(sys.platform == "linux" and shutil.which("gcc") and shutil.which("g++"),
|
||||
"needs Linux, gcc and g++")
|
||||
class FakeinputIoctlTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.tmp = tempfile.TemporaryDirectory()
|
||||
cls.addClassCleanup(cls.tmp.cleanup)
|
||||
cls.path = Path(cls.tmp.name)
|
||||
source = cls.path / "program.c"
|
||||
source.write_text(PROGRAM)
|
||||
subprocess.run(["gcc", "-o", str(cls.path / "program"), str(source)], check=True)
|
||||
subprocess.run(["gcc", "-shared", "-fPIC", "-DBACKEND", "-o",
|
||||
str(cls.path / "backend.so"), str(source)], check=True)
|
||||
subprocess.run(["g++", "-shared", "-fPIC", "-O2", "-Wno-attributes", "-pthread",
|
||||
"-std=c++17", "-static-libstdc++", "-static-libgcc",
|
||||
"-Wl,--exclude-libs,ALL", "-o", str(cls.path / "libfakeinput.so"),
|
||||
str(SOURCE), "-ldl"], check=True)
|
||||
|
||||
def run_program(self, backend=False):
|
||||
preload = str(self.path / "libfakeinput.so")
|
||||
args = [str(self.path / "program")]
|
||||
if backend:
|
||||
preload += ":" + str(self.path / "backend.so")
|
||||
args.append("backend")
|
||||
subprocess.run(args, env=dict(os.environ, LD_PRELOAD=preload), check=True, timeout=10)
|
||||
|
||||
def test_later_interposer_receives_arguments_and_returns_errno(self):
|
||||
self.run_program(backend=True)
|
||||
|
||||
def test_libc_passthrough_retains_kernel_error(self):
|
||||
self.run_program()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1,3 +1,4 @@
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
@@ -52,6 +53,72 @@ class GameEnvironmentTest(unittest.TestCase):
|
||||
self.assertEqual(env["REMOVE"], "inherited")
|
||||
self.assertEqual(MODULE["apply_config"](env, config, "43")["CUSTOM"], "shared")
|
||||
|
||||
def test_component_profiles_override_general_and_restore_it_for_the_next_game(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
home = root / "home"
|
||||
component_dir = home / ".local/share/droiddeck-components"
|
||||
base = root / "proton"
|
||||
target = base / "files/lib/wine/dxvk/aarch64-windows/d3d11.dll"
|
||||
leftover = target.with_name("d3d8.dll")
|
||||
component_dir.mkdir(parents=True)
|
||||
target.parent.mkdir(parents=True)
|
||||
(base / "version").write_text("1 build-1\n")
|
||||
general = root / "general.dll"
|
||||
game = root / "game.dll"
|
||||
general.write_text("general")
|
||||
game.write_text("game")
|
||||
target.write_text("old")
|
||||
leftover.write_text("old")
|
||||
digest = lambda path: hashlib.sha256(path.read_bytes()).hexdigest()
|
||||
(component_dir / "desired.tsv").write_text(
|
||||
"*\tproton\tbuild-1\tdxvk\tfiles/lib/wine/dxvk/aarch64-windows/d3d11.dll\t%s\t%s\n"
|
||||
"42\tproton\tbuild-1\tdxvk\tfiles/lib/wine/dxvk/aarch64-windows/d3d11.dll\t%s\t%s\n"
|
||||
"42\tproton\tbuild-1\tdxvk\tfiles/lib/wine/dxvk/aarch64-windows/d3d8.dll\t-\t-\n"
|
||||
% (digest(general), general, digest(game), game)
|
||||
)
|
||||
script = COMPAT["BL_COMPONENTS_SETUP"] + '\nverb=waitforexitandrun; bl_components "$1"\n'
|
||||
env = dict(os.environ, HOME=str(home), STEAM_COMPAT_DATA_PATH="/steam/compatdata/42")
|
||||
subprocess.run(["bash", "-c", script, "test", str(base)], env=env, check=True)
|
||||
self.assertEqual(target.read_text(), "game")
|
||||
self.assertFalse(leftover.exists())
|
||||
|
||||
env["STEAM_COMPAT_DATA_PATH"] = "/steam/compatdata/43"
|
||||
subprocess.run(["bash", "-c", script, "test", str(base)], env=env, check=True)
|
||||
self.assertEqual(target.read_text(), "general")
|
||||
|
||||
def test_component_scope_matches_environment_scope_for_shortcut_ids(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
component_dir = root / ".local/share/droiddeck-components"
|
||||
base = root / "proton"
|
||||
target = base / "files/lib/wine/dxvk/aarch64-windows/d3d11.dll"
|
||||
component_dir.mkdir(parents=True)
|
||||
target.parent.mkdir(parents=True)
|
||||
(base / "version").write_text("1 build-1\n")
|
||||
rows = []
|
||||
for scope in ("*", "42", "4294967295", "2147483648"):
|
||||
source = root / ("default" if scope == "*" else scope)
|
||||
source.write_text(scope)
|
||||
rows.append("%s\tproton\tbuild-1\tdxvk\t%s\t%s\t%s\n" % (
|
||||
scope, target.relative_to(base),
|
||||
hashlib.sha256(source.read_bytes()).hexdigest(), source,
|
||||
))
|
||||
(component_dir / "desired.tsv").write_text("".join(rows))
|
||||
script = COMPAT["BL_COMPONENTS_SETUP"] + '\nverb=waitforexitandrun; bl_components "$1"\n'
|
||||
for value in (
|
||||
"42", "00042", "43", "-1", "-0001", "4294967295", "-2147483648",
|
||||
"2147483648", "-1///", "0", "-0", "000", "-2147483649", "4294967296",
|
||||
"999999999999999999999999999", "not-an-id", "1+1", "",
|
||||
):
|
||||
with self.subTest(prefix=value):
|
||||
env = dict(os.environ, HOME=str(root), STEAM_COMPAT_DATA_PATH="/steam/compatdata/" + value)
|
||||
target.write_text("untouched")
|
||||
subprocess.run(["bash", "-c", script, "test", str(base)], env=env, check=True, capture_output=True)
|
||||
scope = MODULE["game_id"](env)
|
||||
expected = "untouched" if scope is None else scope if scope in {"42", "4294967295", "2147483648"} else "*"
|
||||
self.assertEqual(target.read_text(), expected)
|
||||
|
||||
def test_engine_fixes_follow_the_games_files(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
game = Path(tmp) / "Godot Game"
|
||||
@@ -109,6 +176,22 @@ class GameEnvironmentTest(unittest.TestCase):
|
||||
with self.assertRaises(ValueError):
|
||||
MODULE["apply_config"]({}, {**config, "dxvkConfig": bad}, "42")
|
||||
|
||||
def test_game_texture_filtering_overrides_default_without_leaking(self):
|
||||
default = "d3d9.samplerAnisotropy = 16"
|
||||
game = "d3d9.samplerAnisotropy = 4"
|
||||
config = {
|
||||
"version": 1,
|
||||
"shared": {},
|
||||
"games": {},
|
||||
"dxvkConfig": default,
|
||||
"dxvkConfigGames": {"42": game, "43": ""},
|
||||
}
|
||||
self.assertEqual(MODULE["apply_config"]({}, config, "42")["DXVK_CONFIG"], game)
|
||||
self.assertNotIn("DXVK_CONFIG", MODULE["apply_config"]({}, config, "43"))
|
||||
self.assertEqual(MODULE["apply_config"]({}, config, "44")["DXVK_CONFIG"], default)
|
||||
with self.assertRaises(ValueError):
|
||||
MODULE["apply_config"]({}, {**config, "dxvkConfigGames": []}, "42")
|
||||
|
||||
def test_game_ids_and_probes(self):
|
||||
for prefix in ("", "/compatdata/0", "/compatdata/0-123", "/compatdata/nope", "/compatdata/4294967296"):
|
||||
self.assertIsNone(MODULE["game_id"]({"STEAM_COMPAT_DATA_PATH": prefix}))
|
||||
@@ -257,6 +340,40 @@ class GameEnvironmentTest(unittest.TestCase):
|
||||
self.assertIn('"$here/proton"', (extra / COMPAT["EXTRA_WRAPPER"]).read_text())
|
||||
self.assertIn("GE-Proton11-7", [entry["name"] for entry in COMPAT["tool_catalog"](str(home), None)])
|
||||
|
||||
def test_droiddeck_proton_is_adopted_and_labelled_like_any_other_extra(self):
|
||||
# Its folder has a space ("DroidDeck-Proton 11-7.5") and its internal name starts with
|
||||
# "DroidDeck-Proton-", which lower-cases to our own tools' prefix: neither may matter.
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
home = Path(tmp)
|
||||
(home / "label").write_text("Compatible\n")
|
||||
COMPAT["display_name"].__globals__["LABEL_FILE"] = str(home / "label")
|
||||
tools = home / "compatibilitytools.d"
|
||||
extra = tools / "DroidDeck-Proton 11-7.5"
|
||||
extra.mkdir(parents=True)
|
||||
(extra / "proton").write_text("")
|
||||
(extra / "toolmanifest.vdf").write_text('"manifest" { "version" "2" "commandline" "/proton %verb%" "require_tool_appid" "4185400" }')
|
||||
(extra / "compatibilitytool.vdf").write_text(
|
||||
'"compatibilitytools" { "compat_tools" { "DroidDeck-Proton-11-7.5" { "install_path" "." '
|
||||
'"display_name" "DroidDeck-Proton 11-7.5" "from_oslist" "windows" "to_oslist" "linux" } } }')
|
||||
COMPAT["build_tool"](str(tools / COMPAT["TOOL"]), None)
|
||||
protect = COMPAT["adopt_extras"](str(tools))
|
||||
self.assertEqual(protect, {"DroidDeck-Proton-11-7.5": "DroidDeck-Proton 11-7.5"})
|
||||
compat = (extra / "compatibilitytool.vdf").read_text()
|
||||
self.assertIn('"DroidDeck-Proton-11-7.5"', compat)
|
||||
self.assertIn('"display_name" "DroidDeck-Proton 11-7.5 (Compatible)"', compat)
|
||||
self.assertNotIn("require_tool_appid", (extra / "toolmanifest.vdf").read_text())
|
||||
self.assertIn('"$here/proton"', (extra / COMPAT["EXTRA_WRAPPER"]).read_text())
|
||||
catalog = COMPAT["tool_catalog"](str(home), None)
|
||||
self.assertIn({"name": "DroidDeck-Proton-11-7.5", "display": "DroidDeck-Proton 11-7.5 (Compatible)",
|
||||
"dir": "DroidDeck-Proton 11-7.5", "valve": False}, catalog)
|
||||
config = home / "config.vdf"
|
||||
config.write_text(config_text([("0", COMPAT["TOOL"]), ("42", "DroidDeck-Proton-11-7.5")]))
|
||||
COMPAT["register_default"](str(config), ["42", "43"], protect=protect)
|
||||
self.assertEqual(mapping_of(config.read_text()), {"0": COMPAT["TOOL"], "42": "DroidDeck-Proton-11-7.5", "43": COMPAT["TOOL"]})
|
||||
# Once removed it is no longer runnable, and its games go back to the default.
|
||||
changes, _ = COMPAT["plan_mapping"]({"0": COMPAT["TOOL"], "42": "DroidDeck-Proton-11-7.5"}, ["42"], [COMPAT["TOOL"]], COMPAT["TOOL"], {})
|
||||
self.assertEqual(changes, {"42": COMPAT["TOOL"]})
|
||||
|
||||
def test_both_proton_wrappers_call_environment_launcher(self):
|
||||
for script in (COMPAT["LAUNCHER_SH"], COMPAT["EXTRA_WRAPPER_SH"] % "proton"):
|
||||
subprocess.run(["bash", "-n"], input=script, text=True, check=True)
|
||||
@@ -319,6 +436,57 @@ class ProtonDefaultTest(unittest.TestCase):
|
||||
changes, auto = self.plan({"0": self.TOOL}, [], self.TOOL, {"10": self.TOOL})
|
||||
self.assertEqual((changes, auto), ({}, {}))
|
||||
|
||||
def test_per_game_proton_override_and_inherit_follow_steam_mappings(self):
|
||||
current = {"0": self.TOOL, "10": self.TOOL, "11": "GE-Proton11-7", "12": self.TOOL}
|
||||
overrides = {"10": "GE-Proton11-7", "11": None}
|
||||
changes, auto = COMPAT["plan_mapping"](
|
||||
current, ["10", "11", "12"], self.NAMES, COMPAT["TOOL_11"],
|
||||
{"10": self.TOOL, "12": self.TOOL}, overrides=overrides)
|
||||
self.assertEqual(changes, {"0": COMPAT["TOOL_11"], "10": "GE-Proton11-7", "11": COMPAT["TOOL_11"], "12": COMPAT["TOOL_11"]})
|
||||
self.assertEqual(auto, {"11": COMPAT["TOOL_11"], "12": COMPAT["TOOL_11"]})
|
||||
|
||||
def test_per_game_requests_resolve_identity_and_defer_a_new_live_tool(self):
|
||||
requests = {
|
||||
"10": {"valve": False, "dir": "GE-Proton11-7"},
|
||||
"11": None,
|
||||
"12": {"valve": True, "dir": "Proton 11.0 (ARM64)"},
|
||||
"0": None,
|
||||
}
|
||||
self.assertEqual(
|
||||
COMPAT["requested_games"](requests, self.CATALOG),
|
||||
{"10": "GE-Proton11-7", "11": None, "12": COMPAT["TOOL_11"]},
|
||||
)
|
||||
self.assertEqual(
|
||||
COMPAT["requested_games"](requests, self.CATALOG, [self.TOOL, COMPAT["TOOL_11"]]),
|
||||
{"10": COMPAT["DEFERRED_GAME_TOOL"], "11": None, "12": COMPAT["TOOL_11"]},
|
||||
)
|
||||
|
||||
def test_missing_per_game_proton_is_preserved_during_default_registration(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
config = Path(tmp) / "config.vdf"
|
||||
config.write_text(config_text([
|
||||
("0", self.TOOL),
|
||||
("10", "GE-Proton9-1"),
|
||||
("11", self.TOOL),
|
||||
]))
|
||||
(Path(tmp) / "games.json").write_text(json.dumps({
|
||||
"version": 1,
|
||||
"games": {
|
||||
"10": {"valve": False, "dir": "GE-Proton9-1"},
|
||||
},
|
||||
}))
|
||||
|
||||
COMPAT["register_default"](
|
||||
str(config), ["10", "11"], default=COMPAT["TOOL_11"],
|
||||
catalog=self.CATALOG, directory=tmp,
|
||||
)
|
||||
|
||||
self.assertEqual(mapping_of(config.read_text()), {
|
||||
"0": COMPAT["TOOL_11"],
|
||||
"10": "GE-Proton9-1",
|
||||
"11": COMPAT["TOOL_11"],
|
||||
})
|
||||
|
||||
def test_the_last_side_to_change_wins(self):
|
||||
state = {"default": self.TOOL, "applied": 5}
|
||||
default, state = COMPAT["choose_default"]("GE-Proton11-7", state, {"seq": 5, "dir": "Proton 11.0 (ARM64)", "valve": True}, self.CATALOG, now=100)
|
||||
|
||||
@@ -0,0 +1,220 @@
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import runpy
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
|
||||
BIN = Path(__file__).resolve().parents[1] / 'linuxfs/overlay/usr/local/bin'
|
||||
MODULE = runpy.run_path(str(BIN / 'droiddeck-launcher-cores'))
|
||||
Holder = MODULE['Holder']
|
||||
Governor = MODULE['Governor']
|
||||
NICE = MODULE['NICE']
|
||||
|
||||
HELPER = 'C:\\Program Files\\Rockstar Games\\Social Club\\SocialClubHelper.exe'
|
||||
LAUNCHER = 'C:\\Program Files\\Rockstar Games\\Launcher\\Launcher.exe'
|
||||
GAME = 'S:\\steamapps\\common\\Red Dead Redemption 2\\RDR2.exe'
|
||||
ALL = set(range(8))
|
||||
|
||||
|
||||
class FakeCores:
|
||||
"""Per-thread masks and priorities, with every change recorded."""
|
||||
|
||||
def __init__(self):
|
||||
self.state = {}
|
||||
self.calls = []
|
||||
|
||||
def own(self):
|
||||
return set(ALL)
|
||||
|
||||
def get(self, tid):
|
||||
if tid not in self.state:
|
||||
raise ProcessLookupError(tid)
|
||||
return self.state[tid]
|
||||
|
||||
def set(self, tid, cpus, nice):
|
||||
if tid not in self.state:
|
||||
raise ProcessLookupError(tid)
|
||||
self.calls.append((tid, set(cpus), nice))
|
||||
self.state[tid] = (set(cpus), nice)
|
||||
|
||||
|
||||
class LauncherCoresTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(temp.cleanup)
|
||||
self.root = Path(temp.name)
|
||||
self.proc = self.root / 'proc'
|
||||
self.proc.mkdir()
|
||||
cpufreq = self.root / 'cpu'
|
||||
for cpu in ALL: # 0-5 one cluster, 6-7 the fast one
|
||||
(cpufreq / f'cpu{cpu}/cpufreq').mkdir(parents=True)
|
||||
(cpufreq / f'cpu{cpu}/cpufreq/cpuinfo_max_freq').write_text('3532800\n' if cpu < 6 else '4320000\n')
|
||||
self.cores = FakeCores()
|
||||
self.holder = Holder(self.proc, cpufreq, self.cores)
|
||||
self.focus = self.root / 'focus.json'
|
||||
self.now = 0.0
|
||||
self.governor = Governor(self.focus, self.holder, clock=lambda: self.now)
|
||||
|
||||
def process(self, pid, argv0, threads=(), cpus=ALL, nice=0):
|
||||
directory = self.proc / str(pid)
|
||||
(directory / 'task').mkdir(parents=True)
|
||||
(directory / 'cmdline').write_bytes(argv0.encode() + b'\0--type=renderer\0')
|
||||
for tid in (pid, *threads):
|
||||
self.thread(pid, tid, cpus, nice)
|
||||
|
||||
def thread(self, pid, tid, cpus=ALL, nice=0):
|
||||
(self.proc / str(pid) / 'task' / str(tid)).mkdir()
|
||||
self.cores.state[tid] = (set(cpus), nice)
|
||||
|
||||
def end(self, pid):
|
||||
for tid in os.listdir(self.proc / str(pid) / 'task'):
|
||||
self.cores.state.pop(int(tid), None)
|
||||
(self.proc / str(pid) / 'task' / tid).rmdir()
|
||||
(self.proc / str(pid) / 'task').rmdir()
|
||||
(self.proc / str(pid) / 'cmdline').unlink()
|
||||
(self.proc / str(pid)).rmdir()
|
||||
|
||||
def focus_on(self, pid, app=1174180):
|
||||
stamp = getattr(self, 'stamp', 1_000_000_000) + 1_000_000_000
|
||||
self.stamp = stamp
|
||||
self.focus.write_text(json.dumps({
|
||||
'focusedApp': app, 'focusedWindow': 0x200001,
|
||||
'focusableWindows': [{'window': 0x100001, 'appId': 769, 'pid': 9},
|
||||
{'window': 0x200001, 'appId': app, 'pid': pid}]}))
|
||||
os.utime(self.focus, ns=(stamp, stamp))
|
||||
|
||||
def held(self, tid):
|
||||
return self.cores.state[tid] == ({5}, NICE)
|
||||
|
||||
def test_helpers_held_on_the_slow_clusters_last_core_while_the_game_has_focus(self):
|
||||
self.process(100, LAUNCHER, (101,))
|
||||
self.process(200, HELPER, (201, 202), nice=-2)
|
||||
self.process(300, HELPER, (301,))
|
||||
self.process(400, GAME, (401,))
|
||||
self.focus_on(400)
|
||||
self.governor.tick()
|
||||
for tid in (200, 201, 202, 300, 301):
|
||||
self.assertTrue(self.held(tid), tid)
|
||||
for tid in (100, 101, 400, 401):
|
||||
self.assertEqual((ALL, 0), self.cores.state[tid])
|
||||
|
||||
def test_launcher_focus_gives_each_thread_its_own_mask_and_priority_back(self):
|
||||
self.process(100, LAUNCHER)
|
||||
self.process(200, HELPER, (201,), cpus={0, 1, 2, 3}, nice=-2)
|
||||
self.cores.state[201] = ({6, 7}, 4)
|
||||
self.process(400, GAME)
|
||||
self.focus_on(400)
|
||||
self.governor.tick()
|
||||
self.assertTrue(self.held(201))
|
||||
self.focus_on(100)
|
||||
self.governor.tick()
|
||||
self.assertEqual(({0, 1, 2, 3}, -2), self.cores.state[200])
|
||||
self.assertEqual(({6, 7}, 4), self.cores.state[201])
|
||||
self.assertEqual({}, self.holder.held)
|
||||
|
||||
def test_nothing_is_touched_before_a_game_has_focus(self):
|
||||
self.process(100, LAUNCHER)
|
||||
self.process(200, HELPER)
|
||||
self.process(9, '/root/.local/share/Steam/steamrtarm64/steam')
|
||||
self.governor.tick() # no focus file yet
|
||||
self.focus_on(9, app=769)
|
||||
self.governor.tick()
|
||||
self.focus_on(100)
|
||||
self.governor.tick()
|
||||
self.assertEqual([], self.cores.calls)
|
||||
|
||||
def test_a_launcher_left_after_its_game_stays_held_behind_the_client(self):
|
||||
self.process(200, HELPER)
|
||||
self.process(400, GAME)
|
||||
self.process(9, '/root/.local/share/Steam/steamrtarm64/steam')
|
||||
self.focus_on(400)
|
||||
self.governor.tick()
|
||||
self.end(400)
|
||||
self.focus_on(9, app=769)
|
||||
self.governor.tick()
|
||||
self.assertTrue(self.held(200))
|
||||
|
||||
def test_a_thread_inheriting_the_hold_is_released_to_what_its_process_had(self):
|
||||
self.process(200, HELPER, cpus={0, 1, 2, 3, 4, 5}, nice=1)
|
||||
self.process(400, GAME)
|
||||
self.focus_on(400)
|
||||
self.governor.tick()
|
||||
# A new thread, and a new helper process the held one started: both born held.
|
||||
self.thread(200, 203, {5}, NICE)
|
||||
self.process(500, HELPER, (501,), cpus={5}, nice=NICE)
|
||||
self.now += 10
|
||||
self.governor.tick()
|
||||
self.focus_on(200)
|
||||
self.governor.tick()
|
||||
for tid in (200, 203, 500, 501):
|
||||
self.assertEqual(({0, 1, 2, 3, 4, 5}, 1), self.cores.state[tid], tid)
|
||||
|
||||
def test_a_held_thread_the_program_moves_back_is_held_again_on_the_next_look(self):
|
||||
self.process(200, HELPER, (201,))
|
||||
self.process(400, GAME)
|
||||
self.focus_on(400)
|
||||
self.governor.tick()
|
||||
self.cores.state[201] = (ALL, -5) # the program raised a thread's priority itself
|
||||
self.now += 5
|
||||
self.governor.tick()
|
||||
self.assertFalse(self.held(201)) # not looked at again before the rescan
|
||||
self.now += 5
|
||||
self.governor.tick()
|
||||
self.assertTrue(self.held(201))
|
||||
self.focus_on(200)
|
||||
self.governor.tick()
|
||||
self.assertEqual((ALL, 0), self.cores.state[201]) # its first state, not the program's
|
||||
|
||||
def test_a_steady_hold_is_not_rewritten(self):
|
||||
self.process(200, HELPER, (201,))
|
||||
self.process(400, GAME)
|
||||
self.focus_on(400)
|
||||
self.governor.tick()
|
||||
calls = len(self.cores.calls)
|
||||
for _ in range(5):
|
||||
self.now += 10
|
||||
self.governor.tick()
|
||||
self.assertEqual(calls, len(self.cores.calls))
|
||||
|
||||
def test_threads_that_end_are_skipped_and_ended_helpers_forgotten(self):
|
||||
self.process(200, HELPER, (201,))
|
||||
self.process(300, HELPER)
|
||||
self.process(400, GAME)
|
||||
del self.cores.state[201] # ended between the listing and the call
|
||||
self.focus_on(400)
|
||||
self.governor.tick()
|
||||
self.assertNotIn(201, self.holder.held[200])
|
||||
self.end(300)
|
||||
self.now += 10
|
||||
self.governor.tick()
|
||||
self.assertEqual([200], list(self.holder.held))
|
||||
|
||||
def test_stop_releases(self):
|
||||
self.process(200, HELPER)
|
||||
self.process(400, GAME)
|
||||
self.focus_on(400)
|
||||
self.governor.tick()
|
||||
with self.assertRaises(SystemExit):
|
||||
self.governor.stop()
|
||||
self.assertEqual((ALL, 0), self.cores.state[200])
|
||||
|
||||
def test_unreadable_focus_is_ignored(self):
|
||||
self.process(200, HELPER)
|
||||
self.focus.write_text('{"focusedApp": 1174')
|
||||
self.governor.tick()
|
||||
self.focus.write_text('[]')
|
||||
os.utime(self.focus, ns=(5, 5))
|
||||
self.governor.tick()
|
||||
self.assertEqual([], self.cores.calls)
|
||||
|
||||
def test_window_without_a_pid_is_left_alone(self):
|
||||
self.process(200, HELPER)
|
||||
self.focus.write_text(json.dumps({'focusedApp': 1174180, 'focusedWindow': 7, 'focusableWindows': []}))
|
||||
self.governor.tick()
|
||||
self.assertEqual([], self.cores.calls)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,107 @@
|
||||
import contextlib
|
||||
import hashlib
|
||||
import io
|
||||
import os
|
||||
from pathlib import Path
|
||||
import runpy
|
||||
import subprocess
|
||||
import tarfile
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest import mock
|
||||
|
||||
BIN = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin"
|
||||
EXTRA = runpy.run_path(str(BIN / "droiddeck-proton-extra"))
|
||||
GLOBALS = EXTRA["pick_asset"].__globals__
|
||||
|
||||
|
||||
def asset(name):
|
||||
return {"name": name, "browser_download_url": "https://github.com/o/r/releases/download/t/" + name}
|
||||
|
||||
|
||||
def droiddeck_release(ver, prerelease=False, draft=False):
|
||||
stem = "DroidDeck-Proton-%s-aarch64" % ver
|
||||
return {"tag_name": "DroidDeck-Proton-" + ver, "prerelease": prerelease, "draft": draft,
|
||||
"assets": [asset(stem + ".build-info.json"), asset(stem + ".sha512sum"), asset(stem + ".tar.gz")]}
|
||||
|
||||
|
||||
class ProtonExtraTest(unittest.TestCase):
|
||||
def test_sources_and_their_arm64_assets(self):
|
||||
self.assertEqual(list(EXTRA["SOURCES"]), ["ge", "cachyos", "droiddeck"])
|
||||
repo, pattern = EXTRA["SOURCES"]["droiddeck"]
|
||||
self.assertEqual(repo, "The412Banner/DroidDeck-Proton")
|
||||
self.assertTrue(pattern.search("DroidDeck-Proton-11-7.5-aarch64.tar.gz"))
|
||||
self.assertTrue(pattern.search("DroidDeck-Proton-11-8-aarch64.tar.xz"))
|
||||
self.assertFalse(pattern.search("DroidDeck-Proton-11-7.5-aarch64.sha512sum"))
|
||||
self.assertFalse(pattern.search("DroidDeck-Proton-11-7.5-aarch64.build-info.json"))
|
||||
|
||||
def test_the_newest_full_release_with_its_sha512_file(self):
|
||||
releases = [droiddeck_release("11-8", prerelease=True), droiddeck_release("11-7.9", draft=True), droiddeck_release("11-7.5")]
|
||||
with mock.patch.dict(GLOBALS, {"fetch_json": lambda url: releases}):
|
||||
tag, url, sums = EXTRA["pick_asset"]("droiddeck")
|
||||
self.assertEqual(tag, "DroidDeck-Proton-11-7.5")
|
||||
self.assertTrue(url.endswith("/DroidDeck-Proton-11-7.5-aarch64.tar.gz"))
|
||||
self.assertTrue(sums.endswith("/DroidDeck-Proton-11-7.5-aarch64.sha512sum"))
|
||||
with mock.patch.dict(GLOBALS, {"fetch_json": lambda url: [droiddeck_release("11-8", prerelease=True)]}):
|
||||
self.assertEqual(EXTRA["pick_asset"]("droiddeck"), (None, None, None))
|
||||
|
||||
def test_a_tagged_release_is_fetched_by_its_tag(self):
|
||||
asked = []
|
||||
with mock.patch.dict(GLOBALS, {"fetch_json": lambda url: asked.append(url) or droiddeck_release("11-7.5")}):
|
||||
tag, url, sums = EXTRA["release_asset"]("droiddeck", "DroidDeck-Proton-11-7.5")
|
||||
self.assertEqual(asked, ["https://api.github.com/repos/The412Banner/DroidDeck-Proton/releases/tags/DroidDeck-Proton-11-7.5"])
|
||||
self.assertTrue(url.endswith(".tar.gz") and sums.endswith(".sha512sum"))
|
||||
|
||||
def test_a_ge_style_sha512_file_verifies_the_download(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
tarball = Path(tmp) / "DroidDeck-Proton-11-7.5-aarch64.tar.gz"
|
||||
tarball.write_bytes(b"tarball")
|
||||
line = "%s %s\n" % (hashlib.sha512(b"tarball").hexdigest(), tarball.name)
|
||||
|
||||
class Reply(io.BytesIO):
|
||||
def __exit__(self, *exc):
|
||||
return False
|
||||
|
||||
with mock.patch.object(GLOBALS["urllib"].request, "urlopen", lambda req, timeout: Reply(line.encode())), \
|
||||
contextlib.redirect_stdout(io.StringIO()) as said:
|
||||
EXTRA["verify"](str(tarball), "https://example/sums")
|
||||
self.assertIn("checksum ok", said.getvalue())
|
||||
self.assertTrue(tarball.exists())
|
||||
bad = "%s %s\n" % ("0" * 128, tarball.name)
|
||||
with mock.patch.object(GLOBALS["urllib"].request, "urlopen", lambda req, timeout: Reply(bad.encode())), \
|
||||
contextlib.redirect_stdout(io.StringIO()), self.assertRaises(SystemExit):
|
||||
EXTRA["verify"](str(tarball), "https://example/sums")
|
||||
self.assertFalse(tarball.exists())
|
||||
|
||||
def test_a_top_folder_with_a_space_is_installed_under_its_own_name(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
src = Path(tmp) / "src" / "DroidDeck-Proton 11-7.5"
|
||||
(src / "files/bin").mkdir(parents=True)
|
||||
(src / "proton").write_text("#!/usr/bin/python3\n")
|
||||
(src / "toolmanifest.vdf").write_text('"manifest" { "commandline" "/proton %verb%" }')
|
||||
(src / "compatibilitytool.vdf").write_text(
|
||||
'"compatibilitytools" { "compat_tools" { "DroidDeck-Proton-11-7.5" { "install_path" "." '
|
||||
'"display_name" "DroidDeck-Proton 11-7.5" } } }')
|
||||
(src / "version").write_text("1791000000 DroidDeck-Proton-11-7.5\n")
|
||||
tarball = Path(tmp) / "DroidDeck-Proton-11-7.5-aarch64.tar.gz"
|
||||
with tarfile.open(tarball, "w:gz") as tar:
|
||||
tar.add(src, arcname=src.name)
|
||||
steam = Path(tmp) / "Steam"
|
||||
adopted = []
|
||||
real = subprocess.call
|
||||
# tar runs for real; steam-compatibility (the adoption step) is only recorded.
|
||||
fake = lambda args, **kw: adopted.append(args) or 0 if args[0] == "steam-compatibility" else real(args, **kw)
|
||||
with mock.patch.object(GLOBALS["subprocess"], "call", fake), contextlib.redirect_stdout(io.StringIO()) as said:
|
||||
with mock.patch.object(GLOBALS["sys"], "argv", ["droiddeck-proton-extra", str(steam), str(tarball)]):
|
||||
EXTRA["main"]()
|
||||
tools = steam / "compatibilitytools.d"
|
||||
self.assertEqual(sorted(os.listdir(tools)), [".droiddeck-download", "DroidDeck-Proton 11-7.5"])
|
||||
self.assertTrue((tools / "DroidDeck-Proton 11-7.5" / "toolmanifest.vdf").is_file())
|
||||
self.assertEqual(adopted, [["steam-compatibility", str(steam)]])
|
||||
# The app reads the folder from this line, space and all.
|
||||
self.assertIn("droiddeck-proton-extra: installed DroidDeck-Proton 11-7.5\n", said.getvalue())
|
||||
self.assertEqual(EXTRA["installed"](str(tools)), ["DroidDeck-Proton 11-7.5"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,23 @@
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
QUEST = Path(__file__).resolve().parents[1] / 'quest'
|
||||
|
||||
|
||||
@unittest.skipUnless(sys.platform == 'linux' and shutil.which('gcc'), 'needs Linux and gcc')
|
||||
class QuestKgslTest(unittest.TestCase):
|
||||
def test_allocation_passthrough_translation_and_cleanup(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
binary = str(Path(folder) / 'test-kgsl')
|
||||
subprocess.run(['gcc', '-Wall', '-Wextra', '-Werror', '-O2', '-o', binary,
|
||||
str(QUEST / 'test_kgsl_compat.c'), str(QUEST / 'kgsl_compat.c')], check=True)
|
||||
result = subprocess.run([binary], capture_output=True, text=True, check=True, timeout=10)
|
||||
self.assertIn('PASS: 12 GPUOBJ', result.stdout)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -55,6 +55,20 @@ class RuntimeInputsTest(unittest.TestCase):
|
||||
with self.assertRaisesRegex(ValueError, 'sources changed'):
|
||||
runtime.verify(self.root)
|
||||
|
||||
def test_changed_quest_source_rejects_old_outputs(self):
|
||||
source = self.root / 'tools/quest/kgsl_compat.c'
|
||||
source.parent.mkdir(parents=True)
|
||||
source.write_text('old compatibility code')
|
||||
runtime.record(self.root)
|
||||
source.write_text('new compatibility code')
|
||||
with self.assertRaisesRegex(ValueError, 'sources changed'):
|
||||
runtime.verify(self.root)
|
||||
|
||||
def test_missing_quest_driver_cannot_be_attested(self):
|
||||
(self.root / 'app/build/prepared-assets/graphics_driver/adrenotools-turnip25.1.0-quest1.tzst').unlink()
|
||||
with self.assertRaisesRegex(ValueError, 'quest1.tzst'):
|
||||
runtime.record(self.root)
|
||||
|
||||
def test_modified_prebuilt_binary_is_rejected(self):
|
||||
runtime.record(self.root)
|
||||
(self.root / 'app/src/main/jniLibs/arm64-v8a/libproot.so').write_bytes(b'old APK binary')
|
||||
|
||||
@@ -22,6 +22,30 @@ GAME_SCRIPT = r'''"InstallScript"
|
||||
}
|
||||
'''
|
||||
|
||||
# Red Dead Redemption 2's own script: Proton needs Khronos' vulkan-1.dll for it, which only the
|
||||
# Vulkan runtime installer puts in the prefix.
|
||||
VULKAN_SCRIPT = r'''"InstallScript"
|
||||
{
|
||||
"Run Process"
|
||||
{
|
||||
"Vulkan111080"
|
||||
{
|
||||
"HasRunKey" "HKEY_LOCAL_MACHINE\\Software\\Valve\\Steam\\Apps\\1174180"
|
||||
"process 1" "%INSTALLDIR%\\Redistributables\\VulkanRT-1.1.108.0-Installer.exe"
|
||||
"command 1" "/S"
|
||||
"NoCleanUp" "0"
|
||||
}
|
||||
"RockstarLauncher"
|
||||
{
|
||||
"HasRunKey" "HKEY_LOCAL_MACHINE\\Software\\Rockstar Games\\Steam\\Launcher"
|
||||
"process 1" "%INSTALLDIR%\\Redistributables\\Rockstar-Games-Launcher.exe"
|
||||
"command 1" "/s /t"
|
||||
"NoCleanUp" "0"
|
||||
}
|
||||
}
|
||||
}
|
||||
'''
|
||||
|
||||
|
||||
class SeedRedistsTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
@@ -91,6 +115,45 @@ class SeedRedistsTest(unittest.TestCase):
|
||||
self.run_seed()
|
||||
self.assertEqual(int(self.reg.stat().st_mtime), 1_000_000_000)
|
||||
|
||||
def rdr2(self):
|
||||
path = self.steam / "steamapps/common/Red Dead Redemption 2/installscript.vdf"
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(VULKAN_SCRIPT)
|
||||
(self.steam / "steamapps/appmanifest_1174180.acf").write_text('"AppState" { "installdir" "Red Dead Redemption 2" }')
|
||||
|
||||
def test_a_vulkan_runtime_installer_is_left_to_run(self):
|
||||
self.rdr2()
|
||||
self.run_seed()
|
||||
reg = self.reg.read_text()
|
||||
self.assertNotIn("Vulkan111080", reg)
|
||||
self.assertIn('"RockstarLauncher"=dword:00000001', reg)
|
||||
self.assertNotIn("Vulkan111080", (self.reg.parent / ".droiddeck-redists").read_text())
|
||||
|
||||
def test_a_vulkan_marker_an_earlier_seeding_wrote_comes_out_once(self):
|
||||
self.rdr2()
|
||||
marker = "HKEY_LOCAL_MACHINE\\\\Software\\\\Valve\\\\Steam\\\\Apps\\\\1174180\tVulkan111080"
|
||||
self.reg.write_text(
|
||||
"WINE REGISTRY Version 2\n"
|
||||
"\n[Software\\\\Valve\\\\Steam\\\\Apps\\\\1174180] 1791729070\n#time=1dd598d29161f72\n"
|
||||
'"Other"=dword:00000001\n"Vulkan111080"=dword:00000001\n'
|
||||
"\n[Software\\\\Wow6432Node\\\\Valve\\\\Steam\\\\Apps\\\\1174180] 1791729070\n"
|
||||
'"Vulkan111080"=dword:00000001\n'
|
||||
"\n[Software\\\\Valve\\\\Steam\\\\Apps\\\\22380] 1791311644\n"
|
||||
'"Vulkan111080"=dword:00000001\n')
|
||||
(self.reg.parent / ".droiddeck-redists").write_text(marker + "\n")
|
||||
os.utime(self.reg, (1_000_000_000, 1_000_000_000))
|
||||
self.run_seed()
|
||||
reg = self.reg.read_text()
|
||||
self.assertEqual(reg.count('"Vulkan111080"'), 1, "only the other app's value stays")
|
||||
self.assertIn('"Other"=dword:00000001', reg)
|
||||
self.assertNotIn("Vulkan111080", (self.reg.parent / ".droiddeck-redists").read_text())
|
||||
self.assertEqual(int(self.reg.stat().st_mtime), 1_000_000_000)
|
||||
# The client writes the marker itself once the installer has run; that one is left alone.
|
||||
with self.reg.open("a") as out:
|
||||
out.write('\n[Software\\\\Valve\\\\Steam\\\\Apps\\\\1174180] 1791730000\n"Vulkan111080"=dword:00000001\n')
|
||||
self.run_seed()
|
||||
self.assertEqual(self.reg.read_text().count('"Vulkan111080"'), 2)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,95 @@
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import socket
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
SESSION = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-session"
|
||||
|
||||
STEAM = ["mangohud.Ab3dE6gH", ".com.valvesoftware.Steam.x1Y2z3/", "steam_chrome_shmem_uid10480_0", "steamADfAnd/"]
|
||||
CHROMIUM = ["scoped_dir3yu9Xt/SingletonSocket"]
|
||||
APPIMAGE = ["droiddeck-appimage.19PoOD"]
|
||||
BUS = ["dbus-1zWfOP1IaR="] # = a socket
|
||||
KDE = ["plasma-csd-generator.BVWIWA/"]
|
||||
STALE = STEAM + CHROMIUM + APPIMAGE + BUS + KDE
|
||||
KEPT = ["droiddeck-mangohud.conf", ".X11-unix/", "steamworks", "steamABCDEF/inside", "notes.txt",
|
||||
"mangohud.conf", ".wine-10480/", "dbus-1zWfOP1IaR.log", "dbus-notasocket",
|
||||
"plasma-csd-generator.CQGZSw/kept"]
|
||||
|
||||
|
||||
def sweep_function(tmp):
|
||||
match = re.search(r"^clear_stale_tmp\(\) \{\n.*?^\}\n", SESSION.read_text(), re.M | re.S)
|
||||
return match.group(0).replace("find /tmp ", "find %s " % tmp)
|
||||
|
||||
|
||||
class SessionTmpTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.root = Path(tempfile.mkdtemp())
|
||||
self.addCleanup(shutil.rmtree, self.root, True)
|
||||
self.tmp = self.root / "tmp"
|
||||
self.tmp.mkdir()
|
||||
for name in STALE + KEPT:
|
||||
path = self.tmp / name
|
||||
if name.endswith("/"):
|
||||
path.mkdir(parents=True)
|
||||
elif name.endswith("="):
|
||||
listener = socket.socket(socket.AF_UNIX)
|
||||
listener.bind(str(self.tmp / name[:-1]))
|
||||
listener.close()
|
||||
else:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text("x")
|
||||
self.bin = self.root / "bin"
|
||||
self.bin.mkdir()
|
||||
|
||||
def sweep(self, running=""):
|
||||
pgrep = self.bin / "pgrep"
|
||||
pgrep.write_text("#!/bin/sh\nprintf '%s' '" + running + "'\n")
|
||||
pgrep.chmod(0o755)
|
||||
env = dict(os.environ, PATH="%s:%s" % (self.bin, os.environ["PATH"]))
|
||||
return subprocess.run(["bash", "-c", sweep_function(self.tmp) + "clear_stale_tmp"], env=env,
|
||||
capture_output=True, text=True, timeout=30, check=True).stdout
|
||||
|
||||
def exists(self, name):
|
||||
return os.path.lexists(self.tmp / name.rstrip("=").split("/")[0])
|
||||
|
||||
def test_what_killed_sessions_left_goes_and_nothing_else(self):
|
||||
self.assertEqual("== /tmp: cleared 8 entries earlier sessions left\n", self.sweep())
|
||||
for name in STALE:
|
||||
self.assertFalse(self.exists(name), name)
|
||||
for name in KEPT:
|
||||
self.assertTrue((self.tmp / name).exists(), name)
|
||||
|
||||
def kept_while(self, running, owned):
|
||||
self.sweep(running)
|
||||
for name in STALE:
|
||||
self.assertEqual(name in owned, self.exists(name), name)
|
||||
|
||||
def test_a_running_client_keeps_its_own(self):
|
||||
self.kept_while("1234 /root/.local/share/Steam/steamrtarm64/steam -gamepadui\n", STEAM)
|
||||
|
||||
def test_a_running_chromium_keeps_its_singleton(self):
|
||||
self.kept_while("88 /opt/Heroic/heroic --type=renderer --enable-features=x\n", CHROMIUM)
|
||||
|
||||
def test_a_running_appimage_keeps_its_stamp(self):
|
||||
self.kept_while("77 /bin/bash /usr/local/bin/droiddeck-appimage-run /root/Apps/X.AppImage\n", APPIMAGE)
|
||||
|
||||
def test_a_running_session_bus_keeps_its_socket(self):
|
||||
self.kept_while("66 dbus-daemon --config-file=/usr/share/dbus-1/session.conf --nofork --session\n", BUS)
|
||||
|
||||
def test_the_system_bus_is_not_a_session_bus(self):
|
||||
self.kept_while("55 dbus-daemon --config-file=/usr/local/share/droiddeck/system-bus.conf --nofork\n", [])
|
||||
|
||||
def test_a_running_desktop_keeps_its_decorations(self):
|
||||
self.kept_while("44 kwin_wayland --xwayland\n", KDE)
|
||||
|
||||
def test_a_clean_tmp_says_nothing(self):
|
||||
self.sweep()
|
||||
self.assertEqual("", self.sweep())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -208,6 +208,33 @@ class ReconcileTest(unittest.TestCase):
|
||||
self.assertEqual((state["pending"], state.get("applied", 0)), (TOOL_11, 0))
|
||||
self.assertTrue(self.helper.request_waiting())
|
||||
|
||||
def test_per_game_customize_and_inherit_apply_live(self):
|
||||
page = FakePage({"0": TOOL, "10": TOOL, "11": TOOL_11}, [TOOL, TOOL_11])
|
||||
(self.state / "games.json").write_text(json.dumps({
|
||||
"version": 1,
|
||||
"games": {
|
||||
"10": {"valve": True, "dir": "Proton 11.0 (ARM64)"},
|
||||
"11": None,
|
||||
},
|
||||
}))
|
||||
state = self.reconcile(page)
|
||||
self.assertEqual(page.sets, [("10", TOOL_11), ("11", TOOL)])
|
||||
self.assertEqual(state["auto"], {"11": TOOL})
|
||||
|
||||
def test_missing_per_game_proton_stays_deferred_live(self):
|
||||
page = FakePage({"0": TOOL, "10": "GE-Proton9-1", "11": TOOL_11}, [TOOL, TOOL_11])
|
||||
(self.state / "games.json").write_text(json.dumps({
|
||||
"version": 1,
|
||||
"games": {
|
||||
"10": {"valve": False, "dir": "GE-Proton9-1"},
|
||||
"11": None,
|
||||
},
|
||||
}))
|
||||
state = self.reconcile(page)
|
||||
self.assertEqual(page.sets, [("11", TOOL)])
|
||||
self.assertEqual(page.mapping["10"], "GE-Proton9-1")
|
||||
self.assertEqual(state["auto"], {"11": TOOL})
|
||||
|
||||
def test_file_mode_defers_to_the_live_helper(self):
|
||||
(self.state / "live.pid").write_text("%d\n" % os.getpid())
|
||||
self.assertTrue(COMPAT["live_helper_running"]())
|
||||
|
||||
@@ -14,6 +14,8 @@ DISPLAY = MODULE['DISPLAY']
|
||||
seed_native_resolution = MODULE['seed_native_resolution']
|
||||
initialize_native_resolution = MODULE['initialize_native_resolution']
|
||||
NATIVE_RESOLUTION = MODULE['NATIVE_RESOLUTION']
|
||||
seed_no_screensaver_in_game = MODULE['seed_no_screensaver_in_game']
|
||||
initialize_screensaver = MODULE['initialize_screensaver']
|
||||
|
||||
|
||||
class SteamUiScaleTest(unittest.TestCase):
|
||||
@@ -151,3 +153,60 @@ class SteamNativeResolutionTest(unittest.TestCase):
|
||||
initialize_native_resolution(self.root)
|
||||
self.assertEqual(text, self.config.read_text())
|
||||
self.assertFalse(self.marker.exists())
|
||||
|
||||
|
||||
class SteamScreensaverTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
self.root = Path(self.temp.name)
|
||||
self.config = self.root / 'config/config.vdf'
|
||||
self.config.parent.mkdir()
|
||||
self.marker = self.config.with_name('droiddeck-screensaver-initialized')
|
||||
|
||||
def in_game(self, text):
|
||||
return parse(text).get('InstallConfigStore').get('Customization').get('Screensaver').get('WhileInGame')
|
||||
|
||||
def test_fresh_client_shows_no_screensaver_over_a_game(self):
|
||||
self.assertTrue(initialize_screensaver(self.root))
|
||||
self.assertEqual('0', self.in_game(self.config.read_text()))
|
||||
self.assertTrue(self.marker.exists())
|
||||
|
||||
def test_it_goes_beside_the_screensaver_the_user_picked(self):
|
||||
text = ('"InstallConfigStore"\n{\n\t"Customization"\n\t{\n\t\t"Screensaver"\n\t\t{\n'
|
||||
'\t\t\t"CurrentScreensaver"\t\t"steam-bouncinglogo"\n\t\t}\n\t}\n}\n')
|
||||
updated, changed = seed_no_screensaver_in_game(text)
|
||||
self.assertTrue(changed)
|
||||
screensaver = parse(updated).get('InstallConfigStore').get('Customization').get('Screensaver')
|
||||
self.assertEqual('steam-bouncinglogo', screensaver.get('CurrentScreensaver'))
|
||||
self.assertEqual('0', screensaver.get('WhileInGame'))
|
||||
self.assertIn('\t\t\t"WhileInGame"\t\t"0"\n\t\t}\n', updated)
|
||||
|
||||
def test_users_choice_is_kept(self):
|
||||
text = '"InstallConfigStore" { "Customization" { "Screensaver" { "WhileInGame" "1" } } }'
|
||||
self.assertEqual((text, False), seed_no_screensaver_in_game(text))
|
||||
|
||||
def test_turning_it_back_on_survives_restart(self):
|
||||
initialize_screensaver(self.root)
|
||||
text = '"InstallConfigStore" { "Customization" { } }'
|
||||
self.config.write_text(text)
|
||||
self.assertFalse(initialize_screensaver(self.root))
|
||||
self.assertEqual(text, self.config.read_text())
|
||||
|
||||
def test_every_seeded_setting_lands_in_one_valid_config(self):
|
||||
initialize(self.root, 2340, 1080)
|
||||
initialize_native_resolution(self.root)
|
||||
initialize_screensaver(self.root)
|
||||
store = parse(self.config.read_text()).get('InstallConfigStore')
|
||||
self.assertIsNotNone(store.get('UI').get('display').get(DISPLAY))
|
||||
self.assertEqual('1', store.get('Gamescope').get(NATIVE_RESOLUTION))
|
||||
self.assertEqual('0', store.get('Customization').get('Screensaver').get('WhileInGame'))
|
||||
|
||||
def test_invalid_config_is_never_rewritten_or_marked_initialized(self):
|
||||
for text in ('"InstallConfigStore" {', '"InstallConfigStore" { "Customization" "bad" }',
|
||||
'"InstallConfigStore" { "Customization" { "Screensaver" "bad" } }'):
|
||||
self.config.write_text(text)
|
||||
with self.assertRaises(ValueError):
|
||||
initialize_screensaver(self.root)
|
||||
self.assertEqual(text, self.config.read_text())
|
||||
self.assertFalse(self.marker.exists())
|
||||
Reference in new issue
Block a user