mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-12-06 04:55:44 +00:00
Compare commits
30
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e6e3673709 | ||
|
|
268dcef559 | ||
|
|
66abf0c707 | ||
|
|
5be04466af | ||
|
|
63ad5a722f | ||
|
|
f896d7fa75 | ||
|
|
995cbc411c | ||
|
|
5045002de1 | ||
|
|
e75505c019 | ||
|
|
264c0fc0f6 | ||
|
|
0f93fd75c4 | ||
|
|
4deff589e5 | ||
|
|
97853d0fde | ||
|
|
2d5061c986 | ||
|
|
6dab2cef17 | ||
|
|
3a4866e2ea | ||
|
|
499b06ff2c | ||
|
|
abca04336a | ||
|
|
5eaa6a76cc | ||
|
|
42df3a78b3 | ||
|
|
30e009a651 | ||
|
|
9e28a11270 | ||
|
|
ed3cfaf9c6 | ||
|
|
082ea000dc | ||
|
|
a251e8cc23 | ||
|
|
60184418ba | ||
|
|
125e39ea9c | ||
|
|
ee8911a382 | ||
|
|
3be85906e9 | ||
|
|
e76592ba4e |
No files matched your search
@@ -300,16 +300,6 @@ def stageGogNotices = tasks.register('stageGogNotices', Copy) {
|
||||
android.sourceSets.main.assets.srcDir(layout.buildDirectory.dir('gogNotices'))
|
||||
tasks.named('preBuild').configure { dependsOn(stageGogNotices) }
|
||||
|
||||
// CI publishes its packs; a local build pins packs nobody hosts (see addonPacks), so the APK carries them.
|
||||
if (!ciBuild) {
|
||||
def stageLocalPacks = tasks.register('stageLocalPacks', Sync) {
|
||||
from(layout.buildDirectory.dir('packs')) { include '*.tar.zst' }
|
||||
into(layout.buildDirectory.dir('localPackAssets/packs'))
|
||||
}
|
||||
android.sourceSets.main.assets.srcDir(layout.buildDirectory.dir('localPackAssets'))
|
||||
tasks.named('preBuild').configure { dependsOn(stageLocalPacks) }
|
||||
}
|
||||
|
||||
def verifyRuntimeInputs = tasks.register('verifyRuntimeInputs', Exec) {
|
||||
mustRunAfter(stageSessionScripts, stageRuntimeAssets)
|
||||
workingDir rootProject.projectDir
|
||||
|
||||
@@ -581,9 +581,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
val mode = intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM
|
||||
SessionState.programArgs = intent.getStringArrayExtra(SessionService.EXTRA_PROGRAM_ARGS)?.toList().orEmpty()
|
||||
SessionEvents.begin(this, mode, SessionPaths.label(mode, intent.getStringExtra(SessionService.EXTRA_PROGRAM)))
|
||||
// begin() moves the phase on, so the block below never runs for a new session; reset per-session flags here.
|
||||
SessionState.secondScreenAutoOpened = false
|
||||
SessionState.secondScreenProvisional = false
|
||||
}
|
||||
if (!SessionState.running && SessionState.phase in setOf(SessionPhase.IDLE, SessionPhase.FAILED)) {
|
||||
SessionState.program = intent.getStringExtra(SessionService.EXTRA_PROGRAM)
|
||||
@@ -591,6 +588,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
SessionState.steamUi = intent.getStringExtra(SessionService.EXTRA_STEAM_UI)
|
||||
SessionState.steamUrl = intent.getStringExtra(SessionService.EXTRA_STEAM_URL)
|
||||
SessionState.steamVr = intent.getBooleanExtra(EXTRA_STEAMVR, false)
|
||||
SessionState.secondScreenAutoOpened = false
|
||||
SessionState.secondScreenProvisional = false
|
||||
} else if (intent.getBooleanExtra(EXTRA_STEAMVR, false) && SessionState.mode == SessionService.MODE_STEAM) {
|
||||
SessionState.steamVr = true
|
||||
}
|
||||
@@ -920,8 +919,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
window.setBackgroundDrawable(android.graphics.drawable.ColorDrawable(android.graphics.Color.BLACK))
|
||||
},
|
||||
)
|
||||
// Also runs when a second screen appears, so Automatic applies then with the running game known.
|
||||
LaunchedEffect(AgentGuest.focusRevision, secondScreenDisplays.isNotEmpty()) {
|
||||
LaunchedEffect(AgentGuest.focusRevision) {
|
||||
val nextGame = kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) {
|
||||
if (SessionState.mode == SessionService.MODE_RUN) SessionState.program?.let { "program:$it" }
|
||||
else {
|
||||
@@ -3134,9 +3132,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
dashboard = if (bottomPages().isEmpty()) null else ({
|
||||
DroidDeckTheme {
|
||||
BottomDashboard(
|
||||
bottomPages(), com.droiddeck.launcher.ui.SessionBottomTab.picked(SessionState.sessionId),
|
||||
bottomPages(), SessionPrefs.bottomPage(this),
|
||||
gameStarts = gameStarts,
|
||||
onPage = { com.droiddeck.launcher.ui.SessionBottomTab.pick(SessionState.sessionId, it) },
|
||||
onPage = { SessionPrefs.setBottomPage(this, it) },
|
||||
onClose = { selectSecondScreenMode(SecondScreenMode.NONE) },
|
||||
onMenu = if (dockDrawer()) ({ drawerOpen = true }) else null,
|
||||
)
|
||||
@@ -3153,8 +3151,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
))
|
||||
|
||||
// A settings page opened on the bottom screen sits under the dashboard window, so the dashboard hides
|
||||
// until the setting is on, or for at most SETTINGS_WATCH_CHECKS seconds when it is left off (another
|
||||
// app's page closing cannot be seen); choosing Dashboard in the menu again shows it sooner.
|
||||
// until the setting is on; choosing Dashboard in the menu again shows it sooner.
|
||||
private fun openSettingsBelow(intent: android.content.Intent, done: () -> Boolean) {
|
||||
val presentation = secondScreenPresentation ?: return
|
||||
val options = android.app.ActivityOptions.makeBasic().setLaunchDisplayId(presentation.display.displayId)
|
||||
@@ -3166,34 +3163,23 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
if (!opened) return
|
||||
presentation.hide()
|
||||
var checks = 0
|
||||
// Show throws if the display went away while the settings page was open, as in showSecondScreen.
|
||||
fun showAgain() {
|
||||
try {
|
||||
presentation.show()
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "could not show the dashboard again", e)
|
||||
if (secondScreenPresentation === presentation) closeSecondScreen(reset = true)
|
||||
}
|
||||
}
|
||||
uiHandler.postDelayed(object : Runnable {
|
||||
override fun run() {
|
||||
if (secondScreenPresentation !== presentation || presentation.isShowing) return
|
||||
if (done()) {
|
||||
showAgain()
|
||||
presentation.show()
|
||||
return
|
||||
}
|
||||
if (++checks < SETTINGS_WATCH_CHECKS) uiHandler.postDelayed(this, SETTINGS_WATCH_MS) else showAgain()
|
||||
if (++checks < SETTINGS_WATCH_CHECKS) uiHandler.postDelayed(this, SETTINGS_WATCH_MS)
|
||||
}
|
||||
}, SETTINGS_WATCH_MS)
|
||||
}
|
||||
|
||||
/** Copies the game frame (no overlay) at the size it is shown and saves it to Pictures/DroidDeck. */
|
||||
private fun captureScreenshot(onDone: (Boolean) -> Unit) {
|
||||
// With the glasses as the output the game is drawn on their surface; the phone's surface is hidden then.
|
||||
val source = if (glassesOutputActive) glassesScreen?.surfaceView else if (::surfaceView.isInitialized) surfaceView else null
|
||||
val width = source?.width ?: 0
|
||||
val height = source?.height ?: 0
|
||||
if (source == null || width <= 0 || height <= 0 || source.holder.surface?.isValid != true) {
|
||||
val width = if (::surfaceView.isInitialized) surfaceView.width else 0
|
||||
val height = if (::surfaceView.isInitialized) surfaceView.height else 0
|
||||
if (width <= 0 || height <= 0 || surfaceView.holder.surface?.isValid != true) {
|
||||
onDone(false)
|
||||
return
|
||||
}
|
||||
@@ -3204,7 +3190,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
return
|
||||
}
|
||||
try {
|
||||
android.view.PixelCopy.request(source, bitmap, { result ->
|
||||
android.view.PixelCopy.request(surfaceView, bitmap, { result ->
|
||||
if (result != android.view.PixelCopy.SUCCESS) {
|
||||
bitmap.recycle()
|
||||
onDone(false)
|
||||
|
||||
@@ -22,7 +22,6 @@ import java.io.FileInputStream
|
||||
internal class AddonPack(
|
||||
val name: String, private val sha256: String, val size: Long, private val required: List<String>,
|
||||
private val reuseDeviceCopy: Boolean = sha256.isEmpty() && !BuildConfig.CI_BUILD,
|
||||
private val bundle: (Context) -> java.io.InputStream = { it.assets.open("packs/$name.tar.zst") },
|
||||
) {
|
||||
sealed interface State {
|
||||
data object Missing : State
|
||||
@@ -105,7 +104,7 @@ internal class AddonPack(
|
||||
}
|
||||
val root = root(context).apply { mkdirs() }
|
||||
val archive = File(root, "$sha256.tar.zst")
|
||||
val downloaded = bundled(context, archive) || urls.any { url ->
|
||||
val downloaded = urls.any { url ->
|
||||
Downloader.downloadFile(url, archive, true, sha256) { p -> mutableState.value = State.Downloading(p.coerceIn(0f, 1f)) }
|
||||
.also { if (!it) archive.delete() }
|
||||
}
|
||||
@@ -127,17 +126,6 @@ internal class AddonPack(
|
||||
return true
|
||||
}
|
||||
|
||||
// A local build pins the packs it compiled, which no release hosts, so it ships them as assets.
|
||||
internal fun bundled(context: Context, archive: File): Boolean {
|
||||
val copied = runCatching {
|
||||
bundle(context).use { input -> archive.outputStream().use { input.copyTo(it) } }
|
||||
}.isSuccess
|
||||
if (copied && Hashes.sha256(archive).equals(sha256, ignoreCase = true)) return true
|
||||
if (copied) Log.w(TAG, "$name: the bundled pack does not match the pinned digest")
|
||||
archive.delete()
|
||||
return false
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val TAG = "AddonPack"
|
||||
private const val REPO = "Droid-Deck/DroidDeck-Components"
|
||||
|
||||
@@ -53,13 +53,10 @@ object BottomNotifications {
|
||||
|
||||
class BottomNotificationListener : NotificationListenerService() {
|
||||
override fun onListenerConnected() {
|
||||
BottomNotifications.clear()
|
||||
runCatching { activeNotifications }.getOrNull()?.sortedBy { it.postTime }?.forEach { BottomNotifications.post(this, it) }
|
||||
}
|
||||
|
||||
override fun onNotificationPosted(sbn: StatusBarNotification) = BottomNotifications.post(this, sbn)
|
||||
|
||||
override fun onNotificationRemoved(sbn: StatusBarNotification) = BottomNotifications.remove(sbn.key)
|
||||
|
||||
override fun onListenerDisconnected() = BottomNotifications.clear()
|
||||
}
|
||||
@@ -100,6 +100,12 @@ object SessionPrefs {
|
||||
prefs(context).edit().putString("secondScreenPanel", mode).apply()
|
||||
}
|
||||
|
||||
fun bottomPage(context: Context): String? = prefs(context).getString("bottomPage", null)
|
||||
|
||||
fun setBottomPage(context: Context, page: String) {
|
||||
prefs(context).edit().putString("bottomPage", page).apply()
|
||||
}
|
||||
|
||||
fun statsStrip(context: Context): String? = prefs(context).getString("statsStrip", null)
|
||||
|
||||
fun setStatsStrip(context: Context, id: String) {
|
||||
|
||||
@@ -23,7 +23,7 @@ object SteamDownloads {
|
||||
val name = SteamDownloadMonitor.value(text, "name") ?: id
|
||||
names[id] = name
|
||||
fromManifest(id, name, text)
|
||||
}.let(::onePerApp)
|
||||
}
|
||||
val homes = client?.let { listOf(if (it == "x86_64") SteamDownloadMonitor.STEAM_HOMES[1] else SteamDownloadMonitor.STEAM_HOMES[0]) }
|
||||
?: SteamDownloadMonitor.STEAM_HOMES
|
||||
val log = homes.map { File(runtimeRoot, "$it/logs/content_log.txt") }.filter { it.isFile }.maxByOrNull { it.lastModified() }
|
||||
@@ -32,10 +32,6 @@ object SteamDownloads {
|
||||
return apps + shaders
|
||||
}
|
||||
|
||||
/** The arm64 and x86-64 Steam homes can both hold an unfinished manifest of one app; the page keys rows by app. */
|
||||
internal fun onePerApp(downloads: List<SteamDownload>): List<SteamDownload> =
|
||||
downloads.groupBy { it.appId }.values.map { same -> same.maxBy { it.done } }
|
||||
|
||||
internal fun fromManifest(id: String, name: String, text: String): SteamDownload? {
|
||||
val flags = SteamDownloadMonitor.value(text, "StateFlags")?.toLongOrNull() ?: 0L
|
||||
if (flags == FULLY_INSTALLED) return null
|
||||
|
||||
@@ -56,25 +56,7 @@ class BottomPage(
|
||||
internal fun pickBottomPage(remembered: String?, ids: List<String>): String? =
|
||||
ids.firstOrNull { it == remembered } ?: ids.firstOrNull { it == DEFAULT_PAGE } ?: ids.firstOrNull()
|
||||
|
||||
/**
|
||||
* The tab picked during one session. Each Steam session starts with no pick, so the dashboard opens on Chat; reopened
|
||||
* later in the same session it shows the tab picked last.
|
||||
*/
|
||||
internal object SessionBottomTab {
|
||||
private var session: String? = null
|
||||
private var tab: String? = null
|
||||
|
||||
@Synchronized
|
||||
fun picked(sessionId: String?): String? = tab.takeIf { sessionId != null && sessionId == session }
|
||||
|
||||
@Synchronized
|
||||
fun pick(sessionId: String?, id: String) {
|
||||
session = sessionId
|
||||
tab = id
|
||||
}
|
||||
}
|
||||
|
||||
/** The page a game start switches to; not remembered as the user's pick. */
|
||||
/** The page a game start switches to; not saved, so the page the user picked still opens next time. */
|
||||
internal fun pageForGameStart(ids: List<String>): String? = GAME_PAGE.takeIf { it in ids }
|
||||
|
||||
private const val DEFAULT_PAGE = "chat"
|
||||
|
||||
@@ -47,9 +47,7 @@ import com.droiddeck.launcher.hud.MangoReadings
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import com.droiddeck.launcher.session.GameStatusFiles
|
||||
import com.droiddeck.launcher.session.GameTelemetry
|
||||
import com.droiddeck.launcher.input.SteamTouchConfig
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import com.droiddeck.launcher.session.SessionService
|
||||
import com.droiddeck.launcher.session.SessionState
|
||||
import com.droiddeck.launcher.session.SpeedUnit
|
||||
import com.droiddeck.launcher.session.StatsDash
|
||||
@@ -98,8 +96,6 @@ fun BottomTelemetryPage(fps: () -> Float?, runningGame: () -> String? = { null }
|
||||
var outputs by remember { mutableStateOf<List<TelemetryOutput.Game>>(emptyList()) }
|
||||
var menuGames by remember { mutableStateOf<List<TelemetryOutput.MenuGame>>(emptyList()) }
|
||||
var running by remember { mutableStateOf<String?>(null) }
|
||||
var gameName by remember { mutableStateOf<String?>(null) }
|
||||
val steamClient = remember { if (SessionState.mode == SessionService.MODE_STEAM) SessionPrefs.activeSteamClientArch(context) else null }
|
||||
var outputFailed by remember { mutableStateOf<String?>(null) }
|
||||
var rescan by remember { mutableIntStateOf(0) }
|
||||
var auto by remember { mutableStateOf(SessionPrefs.telemetryAuto(context)) }
|
||||
@@ -220,11 +216,6 @@ fun BottomTelemetryPage(fps: () -> Float?, runningGame: () -> String? = { null }
|
||||
runCatching { Library.steamGames(context).mapNotNull { TelemetryOutput.MENU_GAMES[it.appId] }.distinct() }.getOrDefault(emptyList())
|
||||
}
|
||||
}
|
||||
LaunchedEffect(running) {
|
||||
val id = running?.toLongOrNull()
|
||||
gameName = if (id == null) null
|
||||
else withContext(Dispatchers.IO) { runCatching { SteamTouchConfig.gameName(context, id.toInt()) }.getOrNull() }
|
||||
}
|
||||
LaunchedEffect(rescan) {
|
||||
while (isActive) {
|
||||
outputs = withContext(Dispatchers.IO) { runCatching { TelemetryOutput.scan(Library.compatdataDirs(context)) }.getOrDefault(emptyList()) }
|
||||
@@ -235,8 +226,7 @@ fun BottomTelemetryPage(fps: () -> Float?, runningGame: () -> String? = { null }
|
||||
|
||||
Column(Modifier.fillMaxSize().verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
perfTick.let {
|
||||
StatsStripView(strip, StripData(fpsNow, device, fpsHistory.snapshot(), cpuHistory.snapshot(), gpuHistory.snapshot(), wattsHistory.snapshot(), clock,
|
||||
if (running != null) gameName else steamClient?.let { stringResource(steamClientLabel(it)) })) {
|
||||
StatsStripView(strip, StripData(fpsNow, device, fpsHistory.snapshot(), cpuHistory.snapshot(), gpuHistory.snapshot(), wattsHistory.snapshot(), clock)) {
|
||||
strip = strip.next()
|
||||
SessionPrefs.setStatsStrip(context, strip.id)
|
||||
}
|
||||
@@ -335,9 +325,6 @@ private fun httpGet(url: String): String {
|
||||
}
|
||||
|
||||
|
||||
/** The Steam client the session runs, shown in the strip's top line while no game runs. */
|
||||
internal fun steamClientLabel(arch: String): Int = if (arch == "x86_64") R.string.stats_steam_client_x86 else R.string.stats_steam_client_arm
|
||||
|
||||
@Composable
|
||||
private fun ChoiceRow(title: String, value: String, onClick: () -> Unit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
|
||||
@@ -64,12 +64,10 @@ class DualPanelModel(
|
||||
object DualScreenPanel {
|
||||
var model by mutableStateOf<DualPanelModel?>(null)
|
||||
private var displayId = -1
|
||||
private var presentation: DualScreenPresentation? = null
|
||||
set(value) { field = value; available = value != null || activity != null || launching }
|
||||
private var activity: DualScreenActivity? = null
|
||||
set(value) { field = value; available = value != null || presentation != null || launching }
|
||||
set(value) { field = value; available = value != null || launching }
|
||||
private var launching = false
|
||||
set(value) { field = value; available = value || activity != null || presentation != null }
|
||||
set(value) { field = value; available = value || activity != null }
|
||||
private var ownerTask = -1
|
||||
private var ownerYielded = false
|
||||
private var ownerPaused = false
|
||||
@@ -79,8 +77,8 @@ object DualScreenPanel {
|
||||
var typingShown by mutableStateOf(false)
|
||||
private set
|
||||
|
||||
val shownOn: Int get() = if (presentation != null || activity != null || launching) displayId else -1
|
||||
val attached: Boolean get() = presentation != null || activity != null
|
||||
val shownOn: Int get() = if (activity != null || launching) displayId else -1
|
||||
val attached: Boolean get() = activity != null
|
||||
var available by mutableStateOf(false)
|
||||
private set
|
||||
|
||||
@@ -125,20 +123,6 @@ object DualScreenPanel {
|
||||
ownerYielded = false
|
||||
ownerPaused = false
|
||||
launching = true
|
||||
val host = context as? ComponentActivity
|
||||
val target = host?.getSystemService(Context.DISPLAY_SERVICE)
|
||||
?.let { (it as android.hardware.display.DisplayManager).getDisplay(display) }
|
||||
// A second-display activity makes the system launcher treat its bottom home as lost and bring itself forward;
|
||||
// a presentation belongs to this task and leaves that home alone.
|
||||
if (host != null && target != null) {
|
||||
val shown = runCatching { DualScreenPresentation(host, target).also { it.show() } }
|
||||
if (shown.isSuccess) {
|
||||
presentation = shown.getOrThrow()
|
||||
launching = false
|
||||
return
|
||||
}
|
||||
android.util.Log.w("DualScreenPanel", "bottom panel presentation failed; falling back to an activity", shown.exceptionOrNull())
|
||||
}
|
||||
val intent = Intent(context, DualScreenActivity::class.java)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_MULTIPLE_TASK or Intent.FLAG_ACTIVITY_NO_ANIMATION)
|
||||
runCatching {
|
||||
@@ -150,8 +134,6 @@ object DualScreenPanel {
|
||||
stopTyping()
|
||||
launching = false
|
||||
displayId = -1
|
||||
presentation?.dismiss()
|
||||
presentation = null
|
||||
activity?.finishAndRemoveTask()
|
||||
activity = null
|
||||
}
|
||||
@@ -162,8 +144,6 @@ object DualScreenPanel {
|
||||
|
||||
internal fun attach(host: DualScreenActivity): Boolean {
|
||||
if (!launching && activity == null) return false
|
||||
presentation?.dismiss()
|
||||
presentation = null
|
||||
if (activity !== host) activity?.finishAndRemoveTask()
|
||||
activity = host
|
||||
launching = false
|
||||
@@ -186,13 +166,18 @@ object DualScreenPanel {
|
||||
return ownerTask.takeIf { it >= 0 }
|
||||
}
|
||||
|
||||
internal fun tookFocus(fresh: Boolean, touchedAt: Long, now: Long): Boolean =
|
||||
fresh || now - touchedAt in 0..TOUCH_FOCUS_MS
|
||||
|
||||
private const val TOUCH_FOCUS_MS = 1000L
|
||||
|
||||
internal fun returnFocus(context: Context, fromPanel: Boolean = false) {
|
||||
val task = focusTask(fromPanel) ?: return
|
||||
runCatching { (context.getSystemService(Context.ACTIVITY_SERVICE) as android.app.ActivityManager).moveTaskToFront(task, 0) }
|
||||
}
|
||||
|
||||
internal fun reclaimFocus(context: Context) {
|
||||
val task = focusTask(true) ?: return
|
||||
val task = focusTask(false) ?: return
|
||||
val manager = context.getSystemService(Context.ACTIVITY_SERVICE) as android.app.ActivityManager
|
||||
runCatching {
|
||||
manager.appTasks.firstOrNull {
|
||||
@@ -208,13 +193,6 @@ object DualScreenPanel {
|
||||
displayId = -1
|
||||
}
|
||||
}
|
||||
|
||||
internal fun detach(host: DualScreenPresentation) {
|
||||
if (presentation === host) {
|
||||
presentation = null
|
||||
displayId = -1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class DualScreenActivity : ComponentActivity() {
|
||||
@@ -267,16 +245,21 @@ class DualScreenActivity : ComponentActivity() {
|
||||
}
|
||||
|
||||
private var topResumed = false
|
||||
private var fresh = true
|
||||
private var touchedAt = Long.MIN_VALUE
|
||||
|
||||
override fun onTopResumedActivityChanged(isTopResumedActivity: Boolean) {
|
||||
super.onTopResumedActivityChanged(isTopResumedActivity)
|
||||
topResumed = isTopResumedActivity
|
||||
if (isTopResumedActivity && !DualScreenPanel.typingShown) DualScreenPanel.returnFocus(this, fromPanel = true)
|
||||
val took = DualScreenPanel.tookFocus(fresh, touchedAt, android.os.SystemClock.uptimeMillis())
|
||||
fresh = false
|
||||
if (isTopResumedActivity && !DualScreenPanel.typingShown) DualScreenPanel.returnFocus(this, fromPanel = took)
|
||||
}
|
||||
|
||||
override fun dispatchTouchEvent(event: android.view.MotionEvent): Boolean {
|
||||
if (event.actionMasked == android.view.MotionEvent.ACTION_DOWN && topResumed && !DualScreenPanel.typingShown) {
|
||||
DualScreenPanel.returnFocus(this, fromPanel = true)
|
||||
if (event.actionMasked == android.view.MotionEvent.ACTION_DOWN) {
|
||||
touchedAt = event.downTime
|
||||
if (topResumed && !DualScreenPanel.typingShown) DualScreenPanel.returnFocus(this, fromPanel = true)
|
||||
}
|
||||
return super.dispatchTouchEvent(event)
|
||||
}
|
||||
|
||||
@@ -1,99 +0,0 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import android.app.Presentation
|
||||
import android.os.Bundle
|
||||
import android.view.Display
|
||||
import android.view.KeyEvent
|
||||
import android.view.View
|
||||
import android.view.WindowManager
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.setViewTreeOnBackPressedDispatcherOwner
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.ComposeView
|
||||
import androidx.lifecycle.setViewTreeLifecycleOwner
|
||||
import androidx.lifecycle.setViewTreeViewModelStoreOwner
|
||||
import androidx.savedstate.setViewTreeSavedStateRegistryOwner
|
||||
import com.droiddeck.launcher.core.AppUiPrefs
|
||||
|
||||
internal class DualScreenPresentation(
|
||||
private val host: ComponentActivity,
|
||||
display: Display,
|
||||
) : Presentation(host, display) {
|
||||
private var content: ComposeView? = null
|
||||
|
||||
init {
|
||||
setCancelable(false)
|
||||
setCanceledOnTouchOutside(false)
|
||||
setOnDismissListener { DualScreenPanel.detach(this) }
|
||||
}
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
window?.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON or WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE)
|
||||
window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE)
|
||||
applyImmersiveMode()
|
||||
val decor = window?.decorView ?: return
|
||||
decor.setViewTreeLifecycleOwner(host)
|
||||
decor.setViewTreeViewModelStoreOwner(host)
|
||||
decor.setViewTreeSavedStateRegistryOwner(host)
|
||||
decor.setViewTreeOnBackPressedDispatcherOwner(host)
|
||||
val view = ComposeView(context)
|
||||
content = view
|
||||
view.setContent {
|
||||
val model = DualScreenPanel.model
|
||||
val request = DualScreenPanel.typing
|
||||
val typingOn = request != null && DualScreenPanel.typingShown
|
||||
LaunchedEffect(typingOn) { acceptFocus(typingOn) }
|
||||
DroidDeckTheme(model?.theme, appScale = model?.appScale ?: AppUiPrefs.DEFAULT_SCALE) {
|
||||
Box(Modifier.fillMaxSize().background(MaterialTheme.colorScheme.background)) {
|
||||
if (request != null && typingOn) TypingPanel(request) {
|
||||
if (DualScreenPanel.typing === request) DualScreenPanel.finishTyping()
|
||||
} else if (model != null) DualPanelContent(model)
|
||||
}
|
||||
}
|
||||
}
|
||||
setContentView(view)
|
||||
}
|
||||
|
||||
private fun acceptFocus(on: Boolean) {
|
||||
val window = window ?: return
|
||||
if (on) {
|
||||
window.clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE)
|
||||
content?.requestFocus()
|
||||
} else {
|
||||
window.addFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE)
|
||||
host.window?.decorView?.requestFocus()
|
||||
}
|
||||
}
|
||||
|
||||
override fun onWindowFocusChanged(hasFocus: Boolean) {
|
||||
super.onWindowFocusChanged(hasFocus)
|
||||
if (hasFocus) applyImmersiveMode()
|
||||
}
|
||||
|
||||
@Suppress("OVERRIDE_DEPRECATION")
|
||||
override fun onBackPressed() {
|
||||
if (DualScreenPanel.typingShown) DualScreenPanel.finishTyping()
|
||||
}
|
||||
|
||||
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
|
||||
if (DualScreenPanel.typingShown && event.keyCode == KeyEvent.KEYCODE_BUTTON_B) {
|
||||
if (event.action == KeyEvent.ACTION_UP && !event.isCanceled) DualScreenPanel.finishTyping()
|
||||
return true
|
||||
}
|
||||
return super.dispatchKeyEvent(event)
|
||||
}
|
||||
|
||||
private fun applyImmersiveMode() {
|
||||
@Suppress("DEPRECATION")
|
||||
window?.decorView?.systemUiVisibility = (View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
|
||||
or View.SYSTEM_UI_FLAG_FULLSCREEN or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
|
||||
or View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
|
||||
or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION)
|
||||
}
|
||||
}
|
||||
@@ -39,7 +39,6 @@ import androidx.compose.ui.graphics.toArgb
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.unit.dp
|
||||
@@ -96,16 +95,13 @@ private fun LogoBadge(size: Dp) {
|
||||
}
|
||||
}
|
||||
|
||||
/** The mark and "DroidDeck" on the left, the running game's name in the middle, the clock on the right. */
|
||||
@Composable
|
||||
private fun LogoHeader(clock: String, game: String?) {
|
||||
private fun LogoHeader(clock: String) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
Row(Modifier.fillMaxWidth().padding(horizontal = 2.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp), modifier = Modifier.padding(horizontal = 2.dp)) {
|
||||
DroidDeckLogo(16.dp)
|
||||
Text("DroidDeck", fontSize = 13.sp, fontWeight = FontWeight.Bold, color = colors.onBackground)
|
||||
Text(game.orEmpty(), fontSize = 13.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, textAlign = TextAlign.Center,
|
||||
maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f))
|
||||
if (clock.isNotEmpty()) Text(clock, fontSize = 12.sp, fontFamily = FontFamily.Monospace, color = colors.onSurfaceVariant)
|
||||
if (clock.isNotEmpty()) Text("· $clock", fontSize = 12.sp, fontFamily = FontFamily.Monospace, color = colors.onSurfaceVariant)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -150,7 +146,6 @@ internal class StripData(
|
||||
val gpuHistory: List<Float>,
|
||||
val wattsHistory: List<Float>,
|
||||
val clock: String,
|
||||
val game: String? = null,
|
||||
)
|
||||
|
||||
private fun percentTemp(percent: Int?, temp: Int?): String =
|
||||
@@ -217,7 +212,7 @@ private fun TilesStrip(d: StripData) {
|
||||
val gpuPercent: Int? = s?.gpuPercent
|
||||
val gpuTemp: Int? = s?.gpuTempC
|
||||
Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
LogoHeader(d.clock, d.game)
|
||||
LogoHeader(d.clock)
|
||||
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
HistoryTile("FPS", accent, fpsText(d.fps), "fps", d.fpsHistory, 75f)
|
||||
HistoryTile("CPU", StatsColors.cpu, s?.cpuPercent?.let { "$it%" } ?: "–", s?.cpuTempC?.let { "$it°" } ?: "", d.cpuHistory, 100f)
|
||||
@@ -253,7 +248,7 @@ private fun RingsStrip(d: StripData) {
|
||||
val gpuPercent: Int? = s?.gpuPercent
|
||||
val gpuTemp: Int? = s?.gpuTempC
|
||||
Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
LogoHeader(d.clock, d.game)
|
||||
LogoHeader(d.clock)
|
||||
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
RingTile("CPU", StatsColors.cpu, s?.cpuPercent?.let { it / 100f }, s?.cpuPercent?.let { "$it%" } ?: "–", s?.cpuTempC?.let { "$it °C" } ?: "")
|
||||
RingTile("GPU", StatsColors.gpu, gpuPercent?.let { it / 100f }, gpuPercent?.let { "$it%" } ?: gpuTemp?.let { "$it°" } ?: "–",
|
||||
|
||||
@@ -1903,8 +1903,6 @@
|
||||
<string name="stats_gear">Gear</string>
|
||||
<string name="stats_speed_units">Speed units</string>
|
||||
<string name="stats_speed_units_auto">Automatic (%1$s)</string>
|
||||
<string name="stats_steam_client_arm">Steam Client ARM</string>
|
||||
<string name="stats_steam_client_x86">Steam Client x86</string>
|
||||
<string name="stats_throttle">Throttle</string>
|
||||
<string name="stats_brake">Brake</string>
|
||||
<string name="stats_lights">Dashboard</string>
|
||||
|
||||
@@ -2,9 +2,6 @@ package com.droiddeck.launcher.core
|
||||
|
||||
import android.content.Context
|
||||
import androidx.test.core.app.ApplicationProvider
|
||||
import com.github.luben.zstd.ZstdOutputStream
|
||||
import org.apache.commons.compress.archivers.tar.TarArchiveEntry
|
||||
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream
|
||||
import java.io.File
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
@@ -57,35 +54,4 @@ class AddonPackTest {
|
||||
installed("b".repeat(64))
|
||||
assertFalse(AddonPack("sample", "", 0L, listOf("tool"), reuseDeviceCopy = false).installed(context))
|
||||
}
|
||||
|
||||
@Test fun localBuildInstallsTheBundledPackWithoutDownloading() {
|
||||
val archive = tarZst("tool" to "x")
|
||||
val pack = AddonPack("sample", Hashes.sha256(archive), archive.length(), listOf("tool"), bundle = { archive.inputStream() })
|
||||
|
||||
assertTrue(pack.await(context))
|
||||
assertEquals("x", pack.file(context, "tool").readText())
|
||||
}
|
||||
|
||||
@Test fun bundledPackWithTheWrongDigestIsRejected() {
|
||||
val archive = tarZst("tool" to "x")
|
||||
val pack = AddonPack("sample", "a".repeat(64), archive.length(), listOf("tool"),
|
||||
bundle = { archive.inputStream() })
|
||||
|
||||
val copy = File(context.cacheDir, "copy.tar.zst")
|
||||
|
||||
assertFalse(pack.bundled(context, copy))
|
||||
assertFalse(copy.exists())
|
||||
}
|
||||
|
||||
private fun tarZst(vararg files: Pair<String, String>): File =
|
||||
File(context.cacheDir, "sample-${System.nanoTime()}.tar.zst").apply {
|
||||
TarArchiveOutputStream(ZstdOutputStream(outputStream())).use { tar ->
|
||||
for ((path, text) in files) {
|
||||
val bytes = text.toByteArray()
|
||||
tar.putArchiveEntry(TarArchiveEntry(path).apply { size = bytes.size.toLong() })
|
||||
tar.write(bytes)
|
||||
tar.closeArchiveEntry()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -17,13 +17,6 @@ class SteamDownloadsTest {
|
||||
}
|
||||
""".trimIndent()
|
||||
|
||||
@Test fun anAppUnfinishedInBothSteamHomesIsListedOnce() {
|
||||
val arm = SteamDownload("220", "Half-Life 2", 10L, 100L)
|
||||
val x86 = SteamDownload("220", "Half-Life 2", 60L, 100L)
|
||||
val other = SteamDownload("440", "Team Fortress 2", 5L, 50L)
|
||||
assertEquals(listOf(x86, other), SteamDownloads.onePerApp(listOf(arm, x86, other)))
|
||||
}
|
||||
|
||||
@Test fun anInstalledGameIsNotADownload() {
|
||||
assertNull(SteamDownloads.fromManifest("220", "Half-Life 2", manifest(4, 100, 100)))
|
||||
}
|
||||
|
||||
@@ -55,17 +55,4 @@ class BottomTelemetryLapTimeTest {
|
||||
assertEquals("1:23.456", lapTime(83.456f))
|
||||
assertEquals("0:05.000", lapTime(5f))
|
||||
}
|
||||
|
||||
@Test fun eachSessionStartsWithoutAPickedTab() {
|
||||
SessionBottomTab.pick("2026-11-01-01-steam", "screenshots")
|
||||
assertEquals("screenshots", SessionBottomTab.picked("2026-11-01-01-steam"))
|
||||
assertNull(SessionBottomTab.picked("2026-11-01-02-steam"))
|
||||
assertNull(SessionBottomTab.picked(null))
|
||||
assertEquals("chat", pickBottomPage(SessionBottomTab.picked("2026-11-01-02-steam"), listOf("telemetry", "chat", "screenshots")))
|
||||
}
|
||||
|
||||
@Test fun theStripNamesTheSteamClient() {
|
||||
assertEquals(com.droiddeck.launcher.R.string.stats_steam_client_x86, steamClientLabel("x86_64"))
|
||||
assertEquals(com.droiddeck.launcher.R.string.stats_steam_client_arm, steamClientLabel("arm64"))
|
||||
}
|
||||
}
|
||||
@@ -81,4 +81,13 @@ class DualScreenPanelOwnerTest {
|
||||
DualScreenPanel.show(app, 2, 10)
|
||||
assertEquals(10, DualScreenPanel.focusTask(fromPanel = false))
|
||||
}
|
||||
|
||||
@Test fun thePanelTookFocusWhenItJustOpenedOrWasJustTouched() {
|
||||
assertTrue(DualScreenPanel.tookFocus(fresh = true, touchedAt = Long.MIN_VALUE, now = 5_000L))
|
||||
assertTrue(DualScreenPanel.tookFocus(fresh = false, touchedAt = 4_700L, now = 5_000L))
|
||||
assertTrue(DualScreenPanel.tookFocus(fresh = false, touchedAt = 5_000L, now = 5_000L))
|
||||
assertFalse(DualScreenPanel.tookFocus(fresh = false, touchedAt = 3_500L, now = 5_000L))
|
||||
assertFalse(DualScreenPanel.tookFocus(fresh = false, touchedAt = Long.MIN_VALUE, now = 5_000L))
|
||||
assertFalse(DualScreenPanel.tookFocus(fresh = false, touchedAt = 6_000L, now = 5_000L))
|
||||
}
|
||||
}
|
||||
@@ -1,15 +1,7 @@
|
||||
#!/usr/bin/python3
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import signal
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import urllib.parse
|
||||
|
||||
os.environ.setdefault("FLATPAK_BWRAP", "/usr/local/bin/droiddeck-bwrap")
|
||||
|
||||
@@ -19,22 +11,6 @@ gi.require_version("Flatpak", "1.0")
|
||||
from gi.repository import Flatpak, Gio, GLib
|
||||
|
||||
REMOTE = "flathub"
|
||||
SYSTEM_BUS = "/run/dbus/system_bus_socket"
|
||||
BUS_COMMANDS = ("install", "install-bundle", "uninstall", "update", "prune")
|
||||
BUS_CONFIG = """<!DOCTYPE busconfig PUBLIC "-//freedesktop//DTD D-Bus Bus Configuration 1.0//EN"
|
||||
"http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd">
|
||||
<busconfig>
|
||||
<type>system</type>
|
||||
<listen>unix:path=%s</listen>
|
||||
<auth>EXTERNAL</auth>
|
||||
<policy context="default">
|
||||
<allow user="*"/>
|
||||
<allow own="*"/>
|
||||
<allow send_destination="*"/>
|
||||
<allow receive_sender="*"/>
|
||||
</policy>
|
||||
</busconfig>
|
||||
"""
|
||||
|
||||
|
||||
def prepare_rootfs():
|
||||
@@ -57,116 +33,6 @@ def prepare_rootfs():
|
||||
emit(e="warning", message="could not prepare %s: %s" % (target, err))
|
||||
|
||||
|
||||
def bus_reachable(path):
|
||||
if isinstance(path, tuple):
|
||||
try:
|
||||
socket.create_connection(path, timeout=1).close()
|
||||
return True
|
||||
except (OSError, ValueError):
|
||||
return False
|
||||
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
||||
try:
|
||||
sock.connect(path)
|
||||
return True
|
||||
except OSError:
|
||||
return False
|
||||
finally:
|
||||
sock.close()
|
||||
|
||||
|
||||
def system_bus_paths():
|
||||
address = os.environ.get("DBUS_SYSTEM_BUS_ADDRESS", "")
|
||||
if not address:
|
||||
return [SYSTEM_BUS]
|
||||
paths = []
|
||||
for entry in filter(None, address.split(";")):
|
||||
found = None
|
||||
kind, _, params = entry.partition(":")
|
||||
values = dict(part.partition("=")[::2] for part in params.split(","))
|
||||
if kind == "unix":
|
||||
if values.get("path"):
|
||||
found = urllib.parse.unquote_to_bytes(values["path"])
|
||||
elif values.get("abstract"):
|
||||
found = b"\0" + urllib.parse.unquote_to_bytes(values["abstract"])
|
||||
elif kind == "tcp":
|
||||
port = urllib.parse.unquote(values.get("port", ""))
|
||||
digits = port.lstrip("0")
|
||||
if not re.fullmatch(r"[0-9]+", port, re.ASCII) or not 0 < len(digits) <= 5 or int(digits) > 65535:
|
||||
continue
|
||||
found = (urllib.parse.unquote(values.get("host", "localhost")), int(digits))
|
||||
if found is None:
|
||||
return None
|
||||
paths.append(found)
|
||||
return paths
|
||||
|
||||
|
||||
def system_bus_reachable():
|
||||
paths = system_bus_paths()
|
||||
return paths is None or any(bus_reachable(path) for path in paths)
|
||||
|
||||
|
||||
def stop_system_bus(bus):
|
||||
if not bus:
|
||||
return
|
||||
proc, work, conf, path = bus
|
||||
if proc.poll() is None:
|
||||
proc.terminate()
|
||||
try:
|
||||
proc.wait(timeout=5)
|
||||
except subprocess.TimeoutExpired:
|
||||
proc.kill()
|
||||
proc.wait()
|
||||
remove_bus_files(work, conf, path)
|
||||
|
||||
|
||||
def remove_bus_files(work, conf, path):
|
||||
for name in (path, conf):
|
||||
try:
|
||||
os.unlink(name)
|
||||
except OSError:
|
||||
pass
|
||||
try:
|
||||
os.rmdir(work)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def private_system_bus():
|
||||
if system_bus_reachable():
|
||||
return None
|
||||
daemon = shutil.which("dbus-daemon")
|
||||
if not daemon:
|
||||
emit(e="warning", message="no system bus and no dbus-daemon to start one")
|
||||
return None
|
||||
try:
|
||||
work = tempfile.mkdtemp(prefix="droiddeck-flatpak-bus-")
|
||||
except OSError as err:
|
||||
emit(e="warning", message="could not start a private system bus: %s" % err)
|
||||
return None
|
||||
conf = os.path.join(work, "bus.conf")
|
||||
path = os.path.join(work, "bus")
|
||||
try:
|
||||
with open(conf, "w") as f:
|
||||
f.write(BUS_CONFIG % path)
|
||||
proc = subprocess.Popen([daemon, "--config-file=" + conf, "--nofork", "--nopidfile"],
|
||||
stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
except OSError as err:
|
||||
remove_bus_files(work, conf, path)
|
||||
emit(e="warning", message="could not start a private system bus: %s" % err)
|
||||
return None
|
||||
bus = (proc, work, conf, path)
|
||||
for _ in range(50):
|
||||
if bus_reachable(path) or proc.poll() is not None:
|
||||
break
|
||||
time.sleep(0.1)
|
||||
if not bus_reachable(path):
|
||||
stop_system_bus(bus)
|
||||
emit(e="warning", message="the private system bus did not start")
|
||||
return None
|
||||
os.environ["DBUS_SYSTEM_BUS_ADDRESS"] = "unix:path=" + path
|
||||
return bus
|
||||
|
||||
|
||||
def emit(**kw):
|
||||
sys.stdout.write(json.dumps(kw) + "\n")
|
||||
sys.stdout.flush()
|
||||
@@ -391,16 +257,6 @@ def main():
|
||||
cmd, args = sys.argv[1], sys.argv[2:]
|
||||
if cmd in ("install", "install-bundle", "update"):
|
||||
prepare_rootfs()
|
||||
bus = private_system_bus() if cmd in BUS_COMMANDS else None
|
||||
if bus:
|
||||
signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit(128 + signum))
|
||||
try:
|
||||
return command(cmd, args)
|
||||
finally:
|
||||
stop_system_bus(bus)
|
||||
|
||||
|
||||
def command(cmd, args):
|
||||
if cmd == "install" and args:
|
||||
return install(args[0])
|
||||
if cmd == "install-bundle" and args:
|
||||
|
||||
@@ -143,12 +143,6 @@ def protonfixes_off(game):
|
||||
return {"PROTONFIXES_DISABLE": "1"}, [], "umu-protonfixes off (its ALSA audio and VC++ installer steps fail here)"
|
||||
|
||||
|
||||
@fix
|
||||
def little_nightmares_threads(game):
|
||||
if game.stem == "littlenightmares":
|
||||
return {"PROTONFIXES_DISABLE": "1"}, [], "Little Nightmares: umu-protonfixes off (its -onethread puts the game and renderer on one thread)"
|
||||
|
||||
|
||||
@fix
|
||||
def caravan_sandwitch_feature_level(game):
|
||||
if "caravansandwitch.exe" in game.files or game.stem == "caravansandwitch-win64-shipping":
|
||||
@@ -780,18 +774,6 @@ def proton_has_dirt_fix(proton):
|
||||
return False
|
||||
|
||||
|
||||
WINE_DLL_DIRS = ("/lib/wine/i386-windows", "/lib/wine/x86_64-windows", "/lib/wine/aarch64-windows", "/lib/wine",
|
||||
"/lib/wine/fakedlls", "/lib64/wine", "/lib64/wine/fakedlls", "/lib64/wine/x86_64-windows")
|
||||
|
||||
|
||||
def is_wine_dll_link(path):
|
||||
"""A link into a Wine DLL folder: the rule Proton uses to tell its own DLLs in a prefix (file_is_wine_builtin_dll)."""
|
||||
try:
|
||||
return os.path.islink(path) and os.path.dirname(os.readlink(path)).endswith(WINE_DLL_DIRS)
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
|
||||
def prefix_ws2(prefix):
|
||||
return Path(prefix) / "pfx/drive_c/windows/syswow64/ws2_32.dll"
|
||||
|
||||
@@ -829,24 +811,17 @@ def swap_dirt_ws2(prefix):
|
||||
|
||||
|
||||
def restore_dirt_ws2(prefix, proton):
|
||||
"""Puts a Wine syswow64/ws2_32.dll back if the stand-in is still there; true when it changed something.
|
||||
|
||||
That is the prefix's own one, unless it was a link to a Wine DLL folder and the game ran on another Proton since
|
||||
the swap: Proton then relinked the prefix's other DLLs to itself but left the stand-in, so a link to the running
|
||||
Proton's ws2_32.dll goes back instead. Anything else (a native file, a link to a mod's DLL) goes back as it was."""
|
||||
"""Puts the prefix's own syswow64/ws2_32.dll back if the stand-in is still there; true when it changed something."""
|
||||
target = prefix_ws2(prefix)
|
||||
saved = target.with_name(target.name + DIRT_SAVED)
|
||||
own = proton_ws2(proton)
|
||||
had_saved = os.path.lexists(saved)
|
||||
if had_saved:
|
||||
if os.path.lexists(target) and not is_dirt_stand_in(target):
|
||||
os.unlink(saved)
|
||||
return False
|
||||
if not own.is_file() or not is_wine_dll_link(saved) or os.path.realpath(saved) == os.path.realpath(own):
|
||||
if os.path.lexists(saved):
|
||||
if is_dirt_stand_in(target) or not os.path.lexists(target):
|
||||
os.replace(saved, target)
|
||||
return True
|
||||
os.unlink(saved)
|
||||
if own.is_file() and (is_dirt_stand_in(target) or (had_saved and not os.path.lexists(target))):
|
||||
return False
|
||||
own = proton_ws2(proton)
|
||||
if is_dirt_stand_in(target) and own.is_file():
|
||||
link = target.with_name(target.name + ".droiddeck-tmp")
|
||||
if os.path.lexists(link):
|
||||
os.unlink(link)
|
||||
@@ -856,55 +831,6 @@ def restore_dirt_ws2(prefix, proton):
|
||||
return False
|
||||
|
||||
|
||||
EGO_RESTRICTIONS = "system/hardware_settings_restrictions.xml"
|
||||
EGO_CORE_RULE = re.compile(r'[ \t]*<restrict_if name="cores" op="(int_[a-z]+)" value="(\d+)">.*?</restrict_if>[ \t]*\r?\n', re.S)
|
||||
EGO_OPS = {"int_eq": int.__eq__, "int_ne": int.__ne__, "int_ge": int.__ge__, "int_gt": int.__gt__,
|
||||
"int_le": int.__le__, "int_lt": int.__lt__}
|
||||
|
||||
|
||||
def windows_core_count(env):
|
||||
count = (env.get("WINE_CPU_TOPOLOGY") or "").split(":", 1)[0]
|
||||
return int(count) if count.isdigit() and int(count) > 0 else None
|
||||
|
||||
|
||||
def ego_core_plan(command, env):
|
||||
"""Codemasters EGO games (DiRT 3, DiRT Showdown, GRID, F1 ...) pick their thread plan by core count from
|
||||
system/hardware_settings_restrictions.xml. A count with no plan (5 when a phone's slow cores are left out) puts
|
||||
every worker on one core, and DiRT 3 then stops on a loading screen. Adds a plan for the count Windows sees,
|
||||
copied from the nearest smaller one; the file as it was is kept beside it. Returns a note, or None."""
|
||||
count = windows_core_count(env)
|
||||
if not count or len(command) < 3:
|
||||
return None
|
||||
folder = Path(command[2]).parent
|
||||
path = folder / EGO_RESTRICTIONS
|
||||
try:
|
||||
raw = path.read_bytes()
|
||||
except OSError:
|
||||
return None
|
||||
text = raw.decode("latin-1")
|
||||
start, end = text.find("<cpu>"), text.find("</cpu>")
|
||||
if start < 0 or end < start:
|
||||
return None
|
||||
rules = list(EGO_CORE_RULE.finditer(text, start, end))
|
||||
if not rules or any(EGO_OPS.get(rule.group(1), lambda a, b: True)(count, int(rule.group(2))) for rule in rules):
|
||||
return None
|
||||
smaller = [rule for rule in rules if rule.group(1) == "int_eq" and int(rule.group(2)) < count]
|
||||
if not smaller:
|
||||
return None
|
||||
source = max(smaller, key=lambda rule: int(rule.group(2)))
|
||||
worker_map = re.search(r'workerMapFile="([^"]+)"', source.group(0))
|
||||
if worker_map and not (folder / worker_map.group(1)).is_file():
|
||||
return None
|
||||
plan = source.group(0).replace('value="%s"' % source.group(2), 'value="%d"' % count, 1)
|
||||
saved = path.with_name(path.name + DIRT_SAVED)
|
||||
if not os.path.lexists(saved):
|
||||
saved.write_bytes(raw)
|
||||
staged = path.with_name(path.name + ".droiddeck-tmp")
|
||||
staged.write_bytes((text[:source.end()] + plan + text[source.end():]).encode("latin-1"))
|
||||
os.replace(staged, path)
|
||||
return "%s had no thread plan for %d cores; added a copy of its %s-core plan" % (EGO_RESTRICTIONS, count, source.group(2))
|
||||
|
||||
|
||||
def wait_forwarding_signals(process):
|
||||
def forward(signum, frame):
|
||||
try:
|
||||
@@ -912,12 +838,9 @@ def wait_forwarding_signals(process):
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
previous = {signum: signal.signal(signum, forward) for signum in (signal.SIGTERM, signal.SIGINT, signal.SIGHUP)}
|
||||
try:
|
||||
code = process.wait()
|
||||
finally:
|
||||
for signum, handler in previous.items():
|
||||
signal.signal(signum, handler)
|
||||
for signum in (signal.SIGTERM, signal.SIGINT, signal.SIGHUP):
|
||||
signal.signal(signum, forward)
|
||||
code = process.wait()
|
||||
return 128 - code if code < 0 else code
|
||||
|
||||
|
||||
@@ -927,11 +850,7 @@ def start(launch, launch_env, digest, after=None):
|
||||
try:
|
||||
return wait_forwarding_signals(process)
|
||||
finally:
|
||||
try:
|
||||
after()
|
||||
except OSError as error:
|
||||
print("droiddeck-game-env: DiRT telemetry fix: prefix ws2_32 not put back (%s); the next launch does it" % error,
|
||||
file=sys.stderr)
|
||||
after()
|
||||
if digest:
|
||||
code = subprocess.run(launch, env=launch_env, check=False).returncode
|
||||
if code == 0:
|
||||
@@ -1012,13 +931,6 @@ def main():
|
||||
env = force_ssbs(command, env)
|
||||
game_cores(env)
|
||||
cpu_topology(env, command)
|
||||
if app_id and len(command) > 2 and command[1] == "waitforexitandrun":
|
||||
try:
|
||||
note = ego_core_plan(command, env)
|
||||
except OSError as error:
|
||||
note = "no thread plan added for this core count (%s)" % error
|
||||
if note:
|
||||
print("droiddeck-game-env: " + note, file=sys.stderr)
|
||||
try:
|
||||
xbox = runpy.run_path(str(Path(__file__).with_name("droiddeck-xbox")))
|
||||
except Exception as error:
|
||||
@@ -1036,21 +948,14 @@ def main():
|
||||
if app_id and prefix and len(command) > 1 and command[1] == "waitforexitandrun":
|
||||
try:
|
||||
if dirt_prefix:
|
||||
after = lambda: restore_dirt_ws2(dirt_prefix, command[0])
|
||||
swap_dirt_ws2(dirt_prefix)
|
||||
after = lambda: restore_dirt_ws2(dirt_prefix, command[0])
|
||||
print("droiddeck-game-env: DiRT telemetry fix: ws2_32 stand-in in the prefix until the game exits",
|
||||
file=sys.stderr)
|
||||
elif restore_dirt_ws2(prefix, command[0]):
|
||||
print("droiddeck-game-env: DiRT telemetry fix: put the prefix's own ws2_32 back", file=sys.stderr)
|
||||
except OSError as error:
|
||||
print("droiddeck-game-env: DiRT telemetry fix not applied (%s)" % error, file=sys.stderr)
|
||||
if after:
|
||||
after = None
|
||||
try:
|
||||
restore_dirt_ws2(dirt_prefix, command[0])
|
||||
except OSError as undo:
|
||||
print("droiddeck-game-env: DiRT telemetry fix: prefix ws2_32 not put back (%s); Wine uses its own copy "
|
||||
"and the next launch puts the file back" % undo, file=sys.stderr)
|
||||
sync = load_sync()
|
||||
launch, launch_env = select_sync(command, env, sync)
|
||||
if launch[0] != command[0]:
|
||||
@@ -1060,16 +965,7 @@ def main():
|
||||
print("droiddeck-game-env: %s could not start (%s); stock launch" % (launch[0], error), file=sys.stderr)
|
||||
launch, launch_env = command, without_pack(launch_env, env)
|
||||
record_stock(sync, launch, launch_env)
|
||||
try:
|
||||
return start(launch, launch_env, digest, after)
|
||||
except OSError:
|
||||
if after:
|
||||
try:
|
||||
after()
|
||||
except OSError as error:
|
||||
print("droiddeck-game-env: DiRT telemetry fix: prefix ws2_32 not put back (%s); the next launch does it" % error,
|
||||
file=sys.stderr)
|
||||
raise
|
||||
return start(launch, launch_env, digest, after)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -1,199 +0,0 @@
|
||||
import importlib.machinery
|
||||
import importlib.util
|
||||
import os
|
||||
from pathlib import Path
|
||||
import socket
|
||||
import sys
|
||||
import tempfile
|
||||
import types
|
||||
import unittest
|
||||
from unittest import mock
|
||||
|
||||
SCRIPT = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-flatpak"
|
||||
|
||||
|
||||
def load():
|
||||
repository = types.ModuleType("gi.repository")
|
||||
repository.Flatpak = types.SimpleNamespace()
|
||||
repository.Gio = types.SimpleNamespace()
|
||||
repository.GLib = types.SimpleNamespace(Error=RuntimeError)
|
||||
gi = types.ModuleType("gi")
|
||||
gi.require_version = lambda *args: None
|
||||
gi.repository = repository
|
||||
saved = {name: sys.modules.get(name) for name in ("gi", "gi.repository")}
|
||||
sys.modules["gi"] = gi
|
||||
sys.modules["gi.repository"] = repository
|
||||
try:
|
||||
loader = importlib.machinery.SourceFileLoader("droiddeck_flatpak_bus", str(SCRIPT))
|
||||
module = importlib.util.module_from_spec(importlib.util.spec_from_loader(loader.name, loader))
|
||||
loader.exec_module(module)
|
||||
finally:
|
||||
for name, value in saved.items():
|
||||
if value is None:
|
||||
sys.modules.pop(name, None)
|
||||
else:
|
||||
sys.modules[name] = value
|
||||
return module
|
||||
|
||||
|
||||
class FakeDaemon:
|
||||
started = []
|
||||
|
||||
def __init__(self, argv, **kwargs):
|
||||
conf = next(a for a in argv if a.startswith("--config-file=")).split("=", 1)[1]
|
||||
text = open(conf).read()
|
||||
self.path = text.split("<listen>unix:path=", 1)[1].split("</listen>", 1)[0]
|
||||
self.server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
||||
self.server.bind(self.path)
|
||||
self.server.listen(4)
|
||||
self.running = True
|
||||
FakeDaemon.started.append(self)
|
||||
|
||||
def poll(self):
|
||||
return None if self.running else 0
|
||||
|
||||
def terminate(self):
|
||||
self.running = False
|
||||
self.server.close()
|
||||
|
||||
def wait(self, timeout=None):
|
||||
return 0
|
||||
|
||||
def kill(self):
|
||||
self.terminate()
|
||||
|
||||
|
||||
class FlatpakSystemBusTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.module = load()
|
||||
self.tmp = tempfile.mkdtemp()
|
||||
self.env = mock.patch.dict(os.environ, {"DBUS_SYSTEM_BUS_ADDRESS": "unix:path=" + os.path.join(self.tmp, "missing")})
|
||||
self.env.start()
|
||||
FakeDaemon.started = []
|
||||
|
||||
def tearDown(self):
|
||||
self.env.stop()
|
||||
os.rmdir(self.tmp)
|
||||
|
||||
def test_a_reachable_system_bus_is_used_as_it_is(self):
|
||||
path = os.path.join(self.tmp, "system")
|
||||
server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
||||
server.bind(path)
|
||||
server.listen(1)
|
||||
try:
|
||||
os.environ["DBUS_SYSTEM_BUS_ADDRESS"] = "unix:path=" + path
|
||||
with mock.patch.object(self.module.subprocess, "Popen", FakeDaemon):
|
||||
self.assertIsNone(self.module.private_system_bus())
|
||||
self.assertEqual([], FakeDaemon.started)
|
||||
finally:
|
||||
server.close()
|
||||
os.unlink(path)
|
||||
|
||||
def test_without_a_system_bus_a_private_one_runs_for_the_command_and_is_removed_after(self):
|
||||
with mock.patch.object(self.module.shutil, "which", return_value="/usr/bin/dbus-daemon"), \
|
||||
mock.patch.object(self.module.subprocess, "Popen", FakeDaemon):
|
||||
bus = self.module.private_system_bus()
|
||||
self.assertIsNotNone(bus)
|
||||
_, work, conf, path = bus
|
||||
self.assertEqual("unix:path=" + path, os.environ["DBUS_SYSTEM_BUS_ADDRESS"])
|
||||
self.assertTrue(self.module.bus_reachable(path))
|
||||
self.module.stop_system_bus(bus)
|
||||
self.assertFalse(os.path.exists(work))
|
||||
|
||||
def test_any_reachable_address_in_a_list_counts_as_the_system_bus(self):
|
||||
path = os.path.join(self.tmp, "system")
|
||||
server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
||||
server.bind(path)
|
||||
server.listen(1)
|
||||
try:
|
||||
os.environ["DBUS_SYSTEM_BUS_ADDRESS"] = "unix:path=%s;unix:guid=1,path=%s" % (os.path.join(self.tmp, "missing"), path)
|
||||
with mock.patch.object(self.module.subprocess, "Popen", FakeDaemon):
|
||||
self.assertIsNone(self.module.private_system_bus())
|
||||
self.assertEqual([], FakeDaemon.started)
|
||||
finally:
|
||||
server.close()
|
||||
os.unlink(path)
|
||||
|
||||
def test_escaped_and_abstract_addresses_are_probed_as_dbus_reads_them(self):
|
||||
path = os.path.join(self.tmp, "sys-bus")
|
||||
server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
||||
server.bind(path)
|
||||
server.listen(1)
|
||||
abstract = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
||||
abstract.bind(b"\0droiddeck-flatpak-test-%d\xff" % os.getpid())
|
||||
abstract.listen(1)
|
||||
try:
|
||||
os.environ["DBUS_SYSTEM_BUS_ADDRESS"] = "unix:path=" + path.replace("-", "%2D")
|
||||
self.assertTrue(self.module.system_bus_reachable())
|
||||
os.environ["DBUS_SYSTEM_BUS_ADDRESS"] = "unix:path=%s;unix:abstract=droiddeck-flatpak-test-%d%%FF" % (os.path.join(self.tmp, "missing"), os.getpid())
|
||||
self.assertTrue(self.module.system_bus_reachable())
|
||||
os.environ["DBUS_SYSTEM_BUS_ADDRESS"] = "unix:abstract=droiddeck-flatpak-missing-%d" % os.getpid()
|
||||
self.assertFalse(self.module.system_bus_reachable())
|
||||
listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
listener.bind(("127.0.0.1", 0))
|
||||
listener.listen(8)
|
||||
port = listener.getsockname()[1]
|
||||
os.environ["DBUS_SYSTEM_BUS_ADDRESS"] = "unix:abstract=droiddeck-flatpak-missing-%d;tcp:host=127.0.0.1,port=%d" % (os.getpid(), port)
|
||||
self.assertTrue(self.module.system_bus_reachable())
|
||||
os.environ["DBUS_SYSTEM_BUS_ADDRESS"] = "tcp:host=127.0.0.1,port=" + "".join("%%%02X" % ord(c) for c in str(port))
|
||||
self.assertTrue(self.module.system_bus_reachable())
|
||||
os.environ["DBUS_SYSTEM_BUS_ADDRESS"] = "tcp:host=127.0.0.1,port=000%d" % port
|
||||
self.assertTrue(self.module.system_bus_reachable())
|
||||
listener.close()
|
||||
self.assertFalse(self.module.system_bus_reachable())
|
||||
for bad in ("%C2%B2", "65536", "0", "000", "x", "9" * 5000):
|
||||
os.environ["DBUS_SYSTEM_BUS_ADDRESS"] = "tcp:host=127.0.0.1,port=" + bad
|
||||
self.assertEqual([], self.module.system_bus_paths())
|
||||
self.assertFalse(self.module.system_bus_reachable())
|
||||
os.environ["DBUS_SYSTEM_BUS_ADDRESS"] = "launchd:env=DBUS_LAUNCHD_SESSION_BUS_SOCKET"
|
||||
self.assertTrue(self.module.system_bus_reachable())
|
||||
finally:
|
||||
abstract.close()
|
||||
server.close()
|
||||
os.unlink(path)
|
||||
|
||||
def test_a_daemon_that_cannot_launch_leaves_no_files_and_warns(self):
|
||||
made = []
|
||||
real = tempfile.mkdtemp
|
||||
|
||||
def mkdtemp(**kwargs):
|
||||
made.append(real(**kwargs))
|
||||
return made[-1]
|
||||
|
||||
with mock.patch.object(self.module.shutil, "which", return_value="/usr/bin/dbus-daemon"), \
|
||||
mock.patch.object(self.module.tempfile, "mkdtemp", mkdtemp), \
|
||||
mock.patch.object(self.module.subprocess, "Popen", side_effect=OSError("exec failed")), \
|
||||
mock.patch.object(self.module, "emit") as emit:
|
||||
self.assertIsNone(self.module.private_system_bus())
|
||||
emit.assert_called_once()
|
||||
self.assertFalse(os.path.exists(made[0]))
|
||||
|
||||
def test_without_dbus_daemon_the_command_still_runs_and_warns(self):
|
||||
with mock.patch.object(self.module.shutil, "which", return_value=None), \
|
||||
mock.patch.object(self.module, "emit") as emit:
|
||||
self.assertIsNone(self.module.private_system_bus())
|
||||
emit.assert_called_once()
|
||||
|
||||
def test_every_command_that_changes_apps_gets_a_system_bus(self):
|
||||
calls = []
|
||||
self.module.private_system_bus = lambda: calls.append("start") or "bus"
|
||||
self.module.stop_system_bus = lambda bus: calls.append("stop:%s" % bus)
|
||||
self.module.prepare_rootfs = lambda: None
|
||||
self.module.install = lambda app_id: calls.append("install") or 0
|
||||
self.module.updates = lambda: calls.append("updates") or 0
|
||||
with mock.patch.object(sys, "argv", ["droiddeck-flatpak", "install", "org.example.App"]), \
|
||||
mock.patch.object(self.module.signal, "signal") as handler:
|
||||
self.assertEqual(0, self.module.main())
|
||||
self.assertEqual(["start", "install", "stop:bus"], calls)
|
||||
self.assertEqual(self.module.signal.SIGTERM, handler.call_args[0][0])
|
||||
with self.assertRaises(SystemExit):
|
||||
handler.call_args[0][1](self.module.signal.SIGTERM, None)
|
||||
calls.clear()
|
||||
with mock.patch.object(sys, "argv", ["droiddeck-flatpak", "updates"]):
|
||||
self.assertEqual(0, self.module.main())
|
||||
self.assertNotIn("start", calls)
|
||||
self.assertIn("updates", calls)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -111,26 +111,6 @@ class DirtTelemetryFixTest(unittest.TestCase):
|
||||
self.assertEqual(os.readlink(self.target), str(newer))
|
||||
self.assertFalse(os.path.lexists(self.target.with_name("ws2_32.dll.droiddeck-original")))
|
||||
|
||||
def test_after_a_proton_switch_the_running_protons_file_goes_back(self):
|
||||
MODULE["swap_dirt_ws2"](self.prefix)
|
||||
other = Path(self.tmp.name) / "GE-Proton/proton"
|
||||
other_own = other.parent / "files/lib/wine/i386-windows/ws2_32.dll"
|
||||
other_own.parent.mkdir(parents=True)
|
||||
other_own.write_bytes(b"MZ GE wine ws2_32")
|
||||
other.write_text("")
|
||||
self.assertTrue(MODULE["restore_dirt_ws2"](self.prefix, other))
|
||||
self.assertEqual(os.readlink(self.target), str(other_own))
|
||||
self.assertFalse(os.path.lexists(self.target.with_name("ws2_32.dll.droiddeck-original")))
|
||||
|
||||
def test_restore_follows_a_proton_reached_through_a_linked_folder(self):
|
||||
MODULE["swap_dirt_ws2"](self.prefix)
|
||||
pack = Path(self.tmp.name) / "pack"
|
||||
(pack / "files/lib/wine").mkdir(parents=True)
|
||||
(pack / "files/lib/wine/i386-windows").symlink_to(self.own.parent)
|
||||
(pack / "proton").write_text("")
|
||||
self.assertTrue(MODULE["restore_dirt_ws2"](self.prefix, pack / "proton"))
|
||||
self.assertEqual(os.readlink(self.target), str(self.own))
|
||||
|
||||
def test_a_stand_in_left_without_the_saved_link_is_replaced_by_protons_own_file(self):
|
||||
self.target.unlink()
|
||||
self.target.write_bytes(self.stand_in.read_bytes())
|
||||
@@ -159,22 +139,6 @@ class DirtTelemetryFixTest(unittest.TestCase):
|
||||
self.assertEqual(os.readlink(self.target), str(self.own))
|
||||
self.assertFalse(os.path.lexists(self.target.with_name("ws2_32.dll.droiddeck-original")))
|
||||
|
||||
def test_a_proton_that_cannot_start_leaves_the_prefix_as_it_was(self):
|
||||
self.config("DiRT Showdown", self.SHOWDOWN_ON)
|
||||
self.proton.write_text("not a program")
|
||||
self.proton.chmod(0o644)
|
||||
runner = Path(self.tmp.name) / "run.py"
|
||||
runner.write_text("import runpy, sys\nmain = runpy.run_path(sys.argv[1])['main']\nmain.__globals__['DIRT_WS2'] = sys.argv[2]\n"
|
||||
"sys.argv = [sys.argv[1]] + sys.argv[3:]\nsys.exit(main())\n")
|
||||
home = Path(self.tmp.name) / "home"
|
||||
home.mkdir()
|
||||
result = subprocess.run([sys.executable, str(runner), str(BIN / "droiddeck-game-env"), str(self.stand_in), *self.command()],
|
||||
env={**os.environ, "HOME": str(home), "STEAM_COMPAT_DATA_PATH": str(self.prefix)}, text=True, capture_output=True)
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("DiRT telemetry fix: ws2_32 stand-in", result.stderr)
|
||||
self.assertEqual(os.readlink(self.target), str(self.own))
|
||||
self.assertFalse(os.path.lexists(self.target.with_name("ws2_32.dll.droiddeck-original")))
|
||||
|
||||
def test_launch_with_telemetry_off_leaves_the_prefix_alone(self):
|
||||
self.config("DiRT Showdown", self.SHOWDOWN_DEFAULT)
|
||||
self.proton.write_text("#!" + sys.executable + "\nimport os\nprint(os.environ.get('WINEDLLOVERRIDES', ''))\n")
|
||||
@@ -187,54 +151,6 @@ class DirtTelemetryFixTest(unittest.TestCase):
|
||||
self.assertNotIn("ws2_32=n,b", result.stdout)
|
||||
self.assertEqual(os.readlink(self.target), str(self.own))
|
||||
|
||||
def test_a_failed_put_back_does_not_end_the_launch_with_an_error(self):
|
||||
def fail():
|
||||
raise OSError(28, "No space left on device")
|
||||
stderr = io.StringIO()
|
||||
with mock.patch("sys.stderr", stderr):
|
||||
code = MODULE["start"]([sys.executable, "-c", "raise SystemExit(0)"], dict(os.environ), None, fail)
|
||||
self.assertEqual(code, 0)
|
||||
self.assertIn("not put back", stderr.getvalue())
|
||||
|
||||
def test_a_half_done_swap_is_put_back(self):
|
||||
saved = self.target.with_name("ws2_32.dll.droiddeck-original")
|
||||
os.replace(self.target, saved)
|
||||
self.assertTrue(MODULE["restore_dirt_ws2"](self.prefix, self.proton))
|
||||
self.assertEqual(os.readlink(self.target), str(self.own))
|
||||
self.assertFalse(os.path.lexists(saved))
|
||||
|
||||
def test_a_native_ws2_32_goes_back_as_it_was_after_a_proton_switch(self):
|
||||
self.target.unlink()
|
||||
self.target.write_bytes(b"MZ a mod's own ws2_32")
|
||||
MODULE["swap_dirt_ws2"](self.prefix)
|
||||
other = Path(self.tmp.name) / "GE-Proton/proton"
|
||||
(other.parent / "files/lib/wine/i386-windows").mkdir(parents=True)
|
||||
(other.parent / "files/lib/wine/i386-windows/ws2_32.dll").write_bytes(b"MZ GE wine ws2_32")
|
||||
other.write_text("")
|
||||
self.assertTrue(MODULE["restore_dirt_ws2"](self.prefix, other))
|
||||
self.assertFalse(self.target.is_symlink())
|
||||
self.assertEqual(self.target.read_bytes(), b"MZ a mod's own ws2_32")
|
||||
|
||||
def test_a_link_to_a_mods_ws2_32_goes_back_as_it_was(self):
|
||||
mod = Path(self.tmp.name) / "mods/ws2_32.dll"
|
||||
mod.parent.mkdir()
|
||||
mod.write_bytes(b"MZ a mod's ws2_32")
|
||||
self.target.unlink()
|
||||
self.target.symlink_to(mod)
|
||||
MODULE["swap_dirt_ws2"](self.prefix)
|
||||
other = Path(self.tmp.name) / "GE-Proton/proton"
|
||||
(other.parent / "files/lib/wine/i386-windows").mkdir(parents=True)
|
||||
(other.parent / "files/lib/wine/i386-windows/ws2_32.dll").write_bytes(b"MZ GE wine ws2_32")
|
||||
other.write_text("")
|
||||
self.assertTrue(MODULE["restore_dirt_ws2"](self.prefix, other))
|
||||
self.assertEqual(os.readlink(self.target), str(mod))
|
||||
|
||||
def test_start_gives_the_signal_handlers_back(self):
|
||||
import signal
|
||||
before = {s: signal.getsignal(s) for s in (signal.SIGTERM, signal.SIGINT, signal.SIGHUP)}
|
||||
MODULE["start"]([sys.executable, "-c", "pass"], dict(os.environ), None, lambda: None)
|
||||
self.assertEqual(before, {s: signal.getsignal(s) for s in before})
|
||||
|
||||
def test_start_puts_the_file_back_after_the_game_exits(self):
|
||||
calls = []
|
||||
code = MODULE["start"]([sys.executable, "-c", "raise SystemExit(3)"], dict(os.environ), None, lambda: calls.append("restored"))
|
||||
@@ -245,93 +161,6 @@ class DirtTelemetryFixTest(unittest.TestCase):
|
||||
self.assertEqual(calls, ["restored"])
|
||||
|
||||
|
||||
class EgoCorePlanTest(unittest.TestCase):
|
||||
"""DiRT 3's restrictions as shipped: plans for 2, 3, 4, 6 and 8+ cores, one core for anything else."""
|
||||
|
||||
@staticmethod
|
||||
def rule(op, value, worker_map):
|
||||
return (' <restrict_if name="cores" op="%s" value="%d">\r\n <restrict_add>\r\n'
|
||||
' <threadStrategy parallelUpdateRender="true" workerMapFile="system/%s" updateProcessor="2" />\r\n'
|
||||
' </restrict_add>\r\n </restrict_if>\r\n' % (op, value, worker_map))
|
||||
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.tmp.cleanup)
|
||||
self.system = Path(self.tmp.name) / "DiRT 3/system"
|
||||
self.system.mkdir(parents=True)
|
||||
cpu = "".join(self.rule("int_eq", n, "workerMap%dCore.xml" % n) for n in (2, 3, 4, 6)) + self.rule("int_ge", 8, "workerMap8Core.xml")
|
||||
self.shipped = ('<?xml version="1.0" encoding="UTF-8" ?>\r\n<hardware_settings_restrictions>\r\n <cpu>\r\n'
|
||||
' <restrict_info>\r\n' + cpu +
|
||||
' <restrict_else>\r\n <restrict_add>\r\n'
|
||||
' <threadStrategy parallelUpdateRender="false" workerMapFile="system/workerMap.xml" />\r\n'
|
||||
' </restrict_add>\r\n </restrict_else>\r\n </restrict_info>\r\n </cpu>\r\n'
|
||||
' <audio_card>\r\n' + self.rule("int_eq", 5, "audio.xml") + ' </audio_card>\r\n'
|
||||
'</hardware_settings_restrictions>').encode("latin-1")
|
||||
self.path = self.system / "hardware_settings_restrictions.xml"
|
||||
self.path.write_bytes(self.shipped)
|
||||
for name in ("workerMap.xml", "workerMap2Core.xml", "workerMap3Core.xml", "workerMap4Core.xml", "workerMap6Core.xml", "workerMap8Core.xml"):
|
||||
(self.system / name).write_text("<workerMap />")
|
||||
self.command = ["/proton", "waitforexitandrun", str(self.system.parent / "dirt3_game.exe")]
|
||||
self.saved = self.path.with_name(self.path.name + ".droiddeck-original")
|
||||
|
||||
def plan(self, topology, command=None):
|
||||
env = {} if topology is None else {"WINE_CPU_TOPOLOGY": topology}
|
||||
return MODULE["ego_core_plan"](command or self.command, env)
|
||||
|
||||
def test_five_cores_get_a_copy_of_the_four_core_plan(self):
|
||||
note = self.plan("5:7,3,4,5,6")
|
||||
self.assertIn("5 cores", note)
|
||||
self.assertIn("4-core plan", note)
|
||||
text = self.path.read_bytes()
|
||||
four = self.rule("int_eq", 4, "workerMap4Core.xml").encode("latin-1")
|
||||
five = self.rule("int_eq", 5, "workerMap4Core.xml").encode("latin-1")
|
||||
self.assertEqual(text, self.shipped.replace(four, four + five))
|
||||
self.assertNotIn(b"\n", text.replace(b"\r\n", b""))
|
||||
self.assertEqual(self.saved.read_bytes(), self.shipped)
|
||||
self.assertIsNone(self.plan("5:7,3,4,5,6"))
|
||||
self.assertEqual(self.path.read_bytes(), text)
|
||||
self.assertEqual(self.saved.read_bytes(), self.shipped)
|
||||
|
||||
def test_seven_cores_get_the_six_core_plan(self):
|
||||
self.assertIn("6-core plan", self.plan("7:7,1,2,3,4,5,6"))
|
||||
self.assertIn(b'value="7">\r\n <restrict_add>\r\n <threadStrategy parallelUpdateRender="true" '
|
||||
b'workerMapFile="system/workerMap6Core.xml"', self.path.read_bytes())
|
||||
|
||||
def test_counts_with_a_plan_are_left_alone(self):
|
||||
for topology in ("2:7,6", "4:7,3,4,5", "6:7,3,4,5,6,2", "8:7,2,3,4,5,6,0,1", "12:0,1,2,3,4,5,6,7,8,9,10,11"):
|
||||
self.assertIsNone(self.plan(topology), topology)
|
||||
self.assertEqual(self.path.read_bytes(), self.shipped)
|
||||
self.assertFalse(os.path.lexists(self.saved))
|
||||
|
||||
def test_nothing_changes_without_a_core_count_a_restrictions_file_a_smaller_plan_or_its_worker_map(self):
|
||||
self.assertIsNone(self.plan(None))
|
||||
self.assertIsNone(self.plan(""))
|
||||
self.assertIsNone(self.plan("x:1"))
|
||||
self.assertIsNone(self.plan("1:7"))
|
||||
self.assertIsNone(self.plan("5:7,3,4,5,6", ["/proton", "waitforexitandrun"]))
|
||||
self.assertIsNone(self.plan("5:7,3,4,5,6", ["/proton", "waitforexitandrun", "/elsewhere/game.exe"]))
|
||||
(self.system / "workerMap4Core.xml").unlink()
|
||||
self.assertIsNone(self.plan("5:7,3,4,5,6"))
|
||||
self.assertEqual(self.path.read_bytes(), self.shipped)
|
||||
self.assertFalse(os.path.lexists(self.saved))
|
||||
|
||||
def test_an_unknown_comparison_counts_as_a_plan(self):
|
||||
self.path.write_bytes(self.shipped.replace(b'op="int_ge" value="8"', b'op="int_between" value="8"'))
|
||||
self.assertIsNone(self.plan("5:7,3,4,5,6"))
|
||||
|
||||
def test_main_adds_the_plan_before_the_game_starts(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
probe = Path(tmp) / "probe"
|
||||
probe.write_text('#!/bin/sh\ngrep -c \'value="5"\' "%s"\n' % self.path)
|
||||
probe.chmod(0o755)
|
||||
env = {k: v for k, v in os.environ.items() if not k.startswith(("WINE", "PROTON", "DROIDDECK", "BL_", "STEAM"))}
|
||||
env.update(HOME=tmp, STEAM_COMPAT_DATA_PATH="/compatdata/3791535942", WINE_CPU_TOPOLOGY="5:7,3,4,5,6")
|
||||
result = subprocess.run([sys.executable, str(BIN / "droiddeck-game-env"), str(probe), "waitforexitandrun", self.command[2]],
|
||||
env=env, text=True, capture_output=True, check=True)
|
||||
self.assertEqual(result.stdout.strip(), "2", result.stderr)
|
||||
self.assertIn("added a copy of its 4-core plan", result.stderr)
|
||||
|
||||
|
||||
class GameDebugLoggingTest(unittest.TestCase):
|
||||
def test_maintenance_precision_survives_run_with_performance_game_settings(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
@@ -887,12 +716,6 @@ class GameEnvironmentTest(unittest.TestCase):
|
||||
self.assertTrue(notes)
|
||||
self.assertEqual(MODULE["engine_fixes"]("/game/Game/DarkSoulsII.exe", []), ({}, [], []))
|
||||
|
||||
def test_little_nightmares_keeps_its_render_thread(self):
|
||||
env, extra, notes = MODULE["engine_fixes"]("/game/Little Nightmares/Atlas/Binaries/Win64/LittleNightmares.exe", [])
|
||||
self.assertEqual((env, extra), ({"PROTONFIXES_DISABLE": "1"}, []))
|
||||
self.assertTrue(notes)
|
||||
self.assertEqual(MODULE["engine_fixes"]("/game/Little Nightmares II/Moonlight/Binaries/Win64/LittleNightmaresII.exe", []), ({}, [], []))
|
||||
|
||||
def test_game_cores_are_parsed_from_lists_and_ranges(self):
|
||||
parse = MODULE["parse_cores"]
|
||||
self.assertEqual(parse("0-3,6"), {0, 1, 2, 3, 6})
|
||||
|
||||
Reference in new issue
Block a user