Compare commits

...
Author SHA1 Message Date
Kurt Himebauch c4d4610548 Merge branch 'main' into fix/epic-gta5-error-window-hidden 2026-11-24 17:51:06 -05:00
TapuukandTapuuk c08952dff9 perf(input): throttle on-screen stick knob redraws to about 30 fps (#2842)
The unified input surface redrew the overlay on every stick move. Knob-only
moves now redraw through ThrottledRedraw at 33 ms and skip sub-pixel moves
away from the rim. Pad updates still go out on every event; touch down, touch
up and reaching the rim still redraw immediately.

Co-authored-by: Tapuuk <177422350+Tapuuk@users.noreply.github.com>
2026-11-24 17:50:20 -05:00
MaxsTechReview 58430cd393 fix(library): persist explicitly selected executables in discovered folders (#2818)
fix(library): keep re-selected executables and store launchers across scans
2026-11-24 17:50:14 -05:00
Kurt Himebauch 46d42f9ca9 fix(library): keep another program of a Steam install out of the Steam app's route (#2742)
* fix(library): keep another program of a Steam install out of the Steam app's route

* fix(library): cover a Steam-edited target in the unrouted-program test and docs

* fix(library): keep Steam-edited targets routed and release stale Spacewar imports for other programs

* fix(library): keep Steam-edited targets adopted before the marker existed routed

A saved executable and seen revision without the adoption marker are recognised
from the Steam shortcut record (its target is the current executable and differs
from the one the app asked for), and the marker is stored.
2026-11-24 17:50:09 -05:00
The412Banner 43ff1db06b fix(appimage): DwarFS AppImages unpack without proot (#3161) 2026-11-24 17:50:04 -05:00
The412Banner f934feb457 fix(input): Remote Play connects again after the controls revert (#2968)
#2958 reverted the controller redesign and its follow-ups, and #2946 was
in that list, so streaming_client lost the real libudev again. #2963
brought back #2942 but not #2946. With the session's udev answers,
SDL3 in streaming_client hands a virtual pad's handle to the real
udev_device_get_driver and crashes about a second after it starts.

streaming_client in steamrtarm64/steamrt64 keeps the real libudev again,
like the Steam client. The no-driver answer for pads that #2946 also
added is left to #2915, which covers every device call.
2026-11-24 17:49:59 -05:00
xlulx 79d41b29ad fix(gamescope): the nested mouse moves the pointer while touch is Disabled (#2961)
The nested Wayland pointer reaches wlserver as touch 0, and in the Disabled
touch click mode wlserver_touchmotion returned before moving anything.
Buttons go through wlserver_mousebutton, so they still arrived, at an X
pointer that stayed at (0,0). Steam picks Disabled for Don't Starve
Together: DroidDeck's cursor followed the mouse while every click landed
in the top-left corner. The nested pointer now warps the X pointer in
Disabled as in the other modes; real fingers are still ignored.
2026-11-24 17:49:54 -05:00
Kurt Himebauch bb6523cd9c fix(display): keep the 16:9 stretch size on the game screen after Steam resizes it (#2738) 2026-11-24 17:49:49 -05:00
Albert Carreras 925e9743a8 fix(game-env): draw Dragon Quest Monsters 4 slime bodies (#2847)
At the game's default monster mesh detail, slimes show only their tips.
Set the two skeletal mesh detail values in Engine.ini before each launch,
in the prefix the game profile selects, and keep the file's permissions.
The game ignores -ini: overrides and deletes a writable Engine.ini after
reading it, so a launch argument or a one-time write does not work.
2026-11-24 17:49:44 -05:00
JM LamboandJacob Lambert 049c4be6e5 fix(desktop): Plasma draws on the system PowerVR driver (#2836)
* fix(desktop): Plasma draws on the system PowerVR driver

KWin lacks the Android-buffer Wayland protocol the system PowerVR driver's
swapchain needs, so every Plasma client failed with "zink: could not create
swapchain" and the desktop stayed black under the cursor. Plasma's clients now
present through DRI on that path, as the Steam session already does.

* test(desktop): the kopper override reaches Plasma's child processes

* test(desktop): check the kopper override where Plasma launches

---------

Co-authored-by: Jacob Lambert <183008808+JMLambo@users.noreply.github.com>
2026-11-24 17:49:39 -05:00
e36cf24ba9 fix(guest): use /usr/bin/python3 in the payload shebangs, not /usr/bin/env (#2930)
PRoot's link2symlink resolves /usr/bin/env to a `.l2s.env….` stub and the
guest's uutils coreutils multicall refuses that name:

  Security violation: Requested utility 'env' does not match executable
  name: /usr/lib/cargo/bin/coreutils/.l2s.env0001.0116

Every exec of these five scripts therefore dies with GUEST_EXIT 1 before
Python starts, 20-60 ms into the session. They are droiddeck-diagnostic-
inventory (the session's first child), droiddeck-desktop-bookmarks (the
desktop's bookmarks refresh), droiddeck-ime, droiddeck-steam-games and
droiddeck-steam-shortcuts.

The absolute interpreter is what the other payload scripts already use,
and the guest runtime installs the python3 package (tools/ubuntu/
packages-runtime.txt), so /usr/bin/python3 exists in the rootfs.

Only the tracked overlay copies change: app/src/main/assets/linuxfs is
generated by the stageSessionScripts Gradle task, so the asset copies
follow from the overlay.

Co-authored-by: Pablo González <pgm1207@users.noreply.github.com>
Co-authored-by: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com>
2026-11-24 17:49:33 -05:00
The412BannerandKurt Himebauch 1772291da7 fix(native): programs started through the rootfs loader show their own command line (#3055)
* fix(native): programs started through the rootfs loader show their own command line

Without proot every dynamic guest program runs as "ld.so --preload <hook>
--library-path <dirs> --argv0 <name> <program> <args>", and the kernel's
/proc/<pid>/cmdline kept all of it. Launchers and the session match programs
by their command line, and Wine only moves its Windows command line over its
loader's name when its arguments follow each other, so the Battle.net launcher
never saw Battle.net.exe, gave up after five minutes and ended the session
with the game still running.

The hook now moves the program's own arguments to the front of that area at
start, as an exec of the program would have laid them out.

* fix(native): programs the app starts natively keep their path for /proc/<pid>/exe

* fix(native): the rewritten command line keeps AT_EXECFN naming the program

---------

Co-authored-by: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com>
2026-11-24 17:48:17 -05:00
The412Banner 1c3c9040ac fix(epic): draw the Epic Games Launcher inside gamescope, not over it 2026-11-20 09:27:15 +00:00
48 changed files with 1163 additions and 60 deletions

No files matched your search

+1
View File
@@ -72,6 +72,7 @@ DroidDeck is [GPL-3.0](LICENSE). Steam and Proton belong to Valve Corporation. V
- mmap ring buffer controller input by ribbit384 ([WinNative #345](https://github.com/WinNative-Emu/WinNative/pull/345)).
- [FEX](https://github.com/FEX-Emu/FEX) (MIT) runs x86 code. DroidDeck's build puts the platform name under `AT_PLATFORM` so [sharun](https://github.com/VHSgunzo/sharun) AppImages by VHSgunzo (MIT) start through its [userland-execve](https://crates.io/crates/userland-execve) loader (MIT), and its GL thunk hands X errors to the program's own error handler. FEX's code disk cache was checked in its source. The fix for host stack left behind when a program leaves a signal handler without returning follows the approach suggested in [FEX-Emu/FEX#2487](https://github.com/FEX-Emu/FEX/issues/2487). The host stack fix for system calls that end a block is a backport of Ryan Houdek's [FEX-Emu/FEX#6122](https://github.com/FEX-Emu/FEX/pull/6122).
- x86 AppImages, and arm64 ones whose runtime can't unpack on Android, are unpacked with [uruntime](https://github.com/VHSgunzo/uruntime) by VHSgunzo (MIT), shipped unmodified with its licence.
- DwarFS AppImages are unpacked without proot by `dwarfsextract` from [DwarFS](https://github.com/mhx/dwarfs) by Marcus Holland-Moritz (MIT), the release binary uruntime embeds, taken out of its self-extracting wrapper and shipped with its licence.
- x86 programs linking OpenSSL 3 use the copy in the [Steam Linux Runtime 4.0](https://gitlab.steamos.cloud/steamrt/steamrt). x86 Linux games get the `/etc/asound.conf` that [pressure-vessel](https://gitlab.steamos.cloud/steamrt/steam-runtime-tools) writes.
- `WriteProcessMemory` hooks fall back to `/proc/<pid>/mem` the way [Wine](https://gitlab.winehq.org/wine/wine)'s `server/ptrace.c` did before Wine 11.
- Windows programs on noexec storage get executable copies of their image pages, following [@yujikaido](https://github.com/yujikaido)'s finding in [droiddeck-rp4pro](https://github.com/yujikaido/droiddeck-rp4pro) that Wine's own processes need the noexec shim.
@@ -31,6 +31,7 @@ object AddedGames {
val exeUncertain: Boolean = false,
val launchOptions: String = "",
val single: Boolean = false,
val steamProgram: Boolean = true,
) {
fun folderName(): String = folder.name
}
@@ -336,7 +337,10 @@ object AddedGames {
val owner = ownerFolder(app, exe)
if (owner != null && owner.path !in SessionPrefs.removedAddedGames(app)) {
single(app, owner.path)?.takeIf { canonical(it.exe) == path }?.let {
if (guestPath(app, exe) != null) AddedExes.put(app, AddedExes.Entry(owner.path, exe.path))
if (guestPath(app, it.exe) != null) {
SessionPrefs.setAddedGameExe(app, owner.path, it.exe.path)
AddedExes.put(app, AddedExes.Entry(owner.path, it.exe.path))
}
return AddResult.Existing(it)
}
}
@@ -442,9 +446,9 @@ object AddedGames {
val chosen = picked.takeIf { it.isNotEmpty() }?.let { File(it) }?.takeIf { it.isFile }
?: single?.takeIf { it.picked }?.let { File(it.exe) }?.takeIf { it.isFile }
val found = chosen ?: sidecar?.exeFile(folder)?.takeIf { it.isFile } ?: candidates.firstOrNull() ?: return
val epicLauncher = sidecar?.takeIf { it.store == Store.EPIC && (chosen == null || canonical(chosen) == canonical(it.exeFile(folder))) }
val storeLauncher = sidecar?.takeIf { chosen == null || canonical(chosen) == canonical(it.exeFile(folder)) }
?.launcherFile(folder)?.takeIf { it.isFile }
val launch = epicLauncher ?: if (chosen == null) sidecar?.launcherFile(folder)?.takeIf { it.isFile } ?: found else found
val launch = storeLauncher ?: found
val foundGuest = guestPath(context, launch)
if (foundGuest == null) { Log.w(TAG, "${folder.name}: the session cannot see ${launch.path}"); return }
val autoName = sidecar?.title ?: identifiedName(folder, found) ?: folder.name
@@ -470,7 +474,13 @@ object AddedGames {
val guestDir = SessionPrefs.addedGameStartIn(context, folder.path).takeIf { sidecar == null && it.isNotEmpty() }
?: sidecarDir
?: guestPath(context, (if (adopted != null) adopted else launch).parentFile ?: folder) ?: return
val steamId = config?.let { steamRoute(it, appId) }
if (adopted == null && SessionPrefs.addedGameAdopted(context, folder.path, "Exe") == null &&
guestPath(context, folder)?.let { steamEditedTo(it, record, guestExe) } == true) {
SessionPrefs.setAddedGameAdopted(context, folder.path, "Exe", exe.path)
}
val steamProgram = candidates.firstOrNull()?.let { canonical(it) == canonical(exe) } ?: true ||
SessionPrefs.addedGameAdopted(context, folder.path, "Exe")?.let { canonical(File(it)) == canonical(exe) } == true
val steamId = config?.takeIf { steamProgram }?.let { steamRoute(it, appId) }
out.add(Game(folder, name, exe, guestExe, guestDir, appId,
steamId?.toLong() ?: ((appId shl 32) or 0x02000000L), candidates, steamId,
source = sidecar?.store?.id ?: Library.ADDED, storeId = sidecar?.id,
@@ -480,7 +490,7 @@ object AddedGames {
sidecar.store == Store.UBISOFT -> com.droiddeck.launcher.stores.ubisoft.UbisoftConnect.launchOptions(context)
else -> ""
},
single = single != null))
single = single != null, steamProgram = steamProgram))
}
}
@@ -520,6 +530,11 @@ object AddedGames {
return file.takeIf { inside && it.isFile }
}
internal fun steamEditedTo(folderGuest: String, record: JSONObject?, guestExe: String): Boolean {
val steam = unquote(record?.optJSONObject("steam")?.optString("Exe"))
return steam == guestExe && steam != unquote(record?.optJSONObject("app")?.optString("Exe")) && steam.startsWith("$folderGuest/")
}
private fun unquote(value: String?): String = value.orEmpty().trim().trim('"')
internal fun adoptSteamEdits(context: Context, folder: File, record: JSONObject) {
@@ -568,6 +583,7 @@ object AddedGames {
.append(",\"seen\":").append(SessionPrefs.addedGameExeSeen(context, g.folder.path))
if (g.launchOptions.isNotEmpty()) json.append(",\"launch\":").append(quote(g.launchOptions))
if (g.source != Library.ADDED) json.append(",\"store\":").append(quote(g.source))
if (!g.steamProgram) json.append(",\"route\":false")
val art = AddedGameArt.resolve(context, g)
val pieces = listOf("p" to art.portrait, "header" to art.header, "hero" to art.hero, "logo" to art.logo, "icon" to art.icon)
.mapNotNull { (k, f) -> f?.let { file -> artGuestPath(context, file)?.let { k to it } } }
@@ -436,6 +436,7 @@ object BwrapSpawner {
"DDNATV_ROOT" to sandbox,
"DDNATV_EXEC" to NativeGuest.execLoader.orEmpty(),
"DDNATV_LINK_ROOT" to rootfs.path,
"DDNATV_REAL_EXE" to program.path,
"DDNATV_BINDS" to plan.binds.joinToString("|") { "${it.host}:${it.guest}" },
"DDNATV_HOSTNAME" to SessionPrefs.guestHostname(context),
"LD_LIBRARY_PATH" to SANDBOX_LIB_DIRS.map(::host).filter { it.isDirectory }.joinToString(":") { it.path },
@@ -73,9 +73,10 @@ object NativeGuest {
fun libraryPath(root: File): String = LIB_DIRS.joinToString(":") { File(root, it).path }
/** Environment every native process starts with; a guest `env -i` is re-seeded by the hook. */
fun environment(root: File, preload: List<String> = emptyList()): Map<String, String> = linkedMapOf(
fun environment(root: File, program: String, preload: List<String> = emptyList()): Map<String, String> = linkedMapOf(
"DDNATV_ROOT" to root.path,
"DDNATV_EXEC" to execLoader.orEmpty(),
"DDNATV_REAL_EXE" to hostProgram(root, program).path,
"LD_PRELOAD" to (preload.map { File(root, it.removePrefix("/")).path } + hook(root).path).joinToString(":"),
).filterValues { it.isNotEmpty() }
@@ -85,17 +86,20 @@ object NativeGuest {
*/
fun command(root: File, program: String, args: List<String>, libraryPath: String = libraryPath(root)): List<String> {
val loader = checkNotNull(loader(root)) { "no glibc loader in ${root.path}" }
val host = File(root, program.removePrefix("/"))
val host = hostProgram(root, program)
val launch = listOf(loader.path, "--library-path", libraryPath, "--argv0", host.name, host.path) + args
return simulator(root)?.let { it + launch } ?: (execPrefix(loader.path) + launch)
}
private fun hostProgram(root: File, program: String): File = File(root, program.removePrefix("/"))
/** The environment of the session process: the hook's root, the mounts proot used to make, the preload list. */
fun sessionEnvironment(root: File, binds: List<String>, hostname: String? = null): Map<String, String> {
fun sessionEnvironment(root: File, binds: List<String>, program: String, hostname: String? = null): Map<String, String> {
val preload = preloadList(root)
return linkedMapOf(
"DDNATV_ROOT" to root.path,
"DDNATV_EXEC" to execLoader.orEmpty(),
"DDNATV_REAL_EXE" to hostProgram(root, program).path,
"DDNATV_HOSTNAME" to hostname.orEmpty(),
"DDNATV_BINDS" to binds.joinToString("|") { if (it.contains(':')) it else "$it:$it" },
"DDNATV_PRELOAD" to preload.joinToString(":"),
@@ -114,7 +118,7 @@ object NativeGuest {
.also { builder ->
builder.environment().apply {
remove("LD_AUDIT")
putAll(sessionEnvironment(root, binds, SessionPrefs.guestHostname(context)))
putAll(sessionEnvironment(root, binds, guest.first(), SessionPrefs.guestHostname(context)))
}
}
@@ -278,7 +282,7 @@ object NativeGuest {
builder.directory(File(root, cwd.removePrefix("/")).takeIf { it.isDirectory } ?: root)
builder.environment().apply {
clear()
putAll(environment(root, preload))
putAll(environment(root, program, preload))
putAll(env)
}
return builder
@@ -328,7 +328,7 @@ object BottomDesktop {
LinuxRuntime.commandWithBinds(context, current.root, binds, guest)
}
val environment = if (current.nativeUserland) {
com.droiddeck.launcher.runtime.NativeGuest.sessionEnvironment(current.root, binds, SessionPrefs.guestHostname(context))
com.droiddeck.launcher.runtime.NativeGuest.sessionEnvironment(current.root, binds, guest.first(), SessionPrefs.guestHostname(context))
.map { (k, v) -> "$k=$v" }.toTypedArray()
} else current.hostEnvironment
val line = command.joinToString(" ") { it.replace("\\", "\\\\").replace(" ", "\\ ") }
@@ -263,7 +263,9 @@ object SessionFiles {
"usr/local/share/vkbridge/droidbridge_icd.json" to "usr/local/share/vkbridge/droidbridge_icd.json",
"usr/local/bin/droiddeck-vkbridge-smoke" to "usr/local/bin/droiddeck-vkbridge-smoke",
"usr/local/lib/droiddeck/uruntime" to "usr/local/lib/droiddeck/uruntime",
"usr/local/lib/droiddeck/dwarfsextract" to "usr/local/lib/droiddeck/dwarfsextract",
"usr/local/lib/droiddeck-pipewire.tzst" to "usr/local/lib/droiddeck-pipewire.tzst",
"usr/local/share/licenses/dwarfs/LICENSE" to "usr/local/share/licenses/dwarfs/LICENSE",
"usr/local/share/licenses/uruntime/LICENSE" to "usr/local/share/licenses/uruntime/LICENSE",
) + mangoapp + xclipse.map { it to it } + maliCompat + msitools.map { it to it } + vr + gpuLoad + fexPreloads).filter { (asset, _) ->
val dir = asset.substringBeforeLast('/')
@@ -1562,7 +1562,7 @@ object SessionPrefs {
fun adoptAddedGameExe(context: Context, folderPath: String, expected: String, path: String, seen: Int): Boolean =
synchronized(addedGameLock) {
val unchanged = addedGameExe(context, folderPath) == expected
if (unchanged) prefs(context).edit().putString("addedExe:$folderPath", path).putInt("addedExeSeen:$folderPath", seen).apply()
if (unchanged) prefs(context).edit().putString("addedExe:$folderPath", path).putString("addedAdopted:Exe:$folderPath", path).putInt("addedExeSeen:$folderPath", seen).apply()
unchanged
}
@@ -784,7 +784,7 @@ class SessionService : Service() {
if (drives > 0) Log.i(TAG, "$drives Wine drive links given their guest paths back")
val hostEnv = if (nativeUserland) HostEnvironment().also { env ->
Log.i(TAG, "native userland: no proot (${sessionBindSpecs.size} mounts)")
com.droiddeck.launcher.runtime.NativeGuest.sessionEnvironment(root, sessionBindSpecs, SessionPrefs.guestHostname(this))
com.droiddeck.launcher.runtime.NativeGuest.sessionEnvironment(root, sessionBindSpecs, guest.first(), SessionPrefs.guestHostname(this))
.forEach { (k, v) -> env[k] = v }
} else prootEnv
@@ -38,8 +38,10 @@ import com.droiddeck.launcher.input.InputButtonShape
import com.droiddeck.launcher.input.InputButtonImages
import com.droiddeck.launcher.input.PadBridge
import com.droiddeck.launcher.input.PadKit
import com.droiddeck.launcher.input.ThrottledRedraw
import com.droiddeck.launcher.input.pcKeyLabel
import com.droiddeck.launcher.session.SessionPrefs
import kotlin.math.abs
import kotlin.math.atan2
import kotlin.math.hypot
import kotlin.math.min
@@ -581,6 +583,10 @@ class InputSurfaceView(
private var originY = 0f
private var knobX = 0f
private var knobY = 0f
private var drawnX = 0f
private var drawnY = 0f
private var atRim = false
private val redraw = ThrottledRedraw(this, STICK_REDRAW_MS)
private val ring = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE }
private val knob = Paint(Paint.ANTI_ALIAS_FLAG)
@@ -663,6 +669,7 @@ class InputSurfaceView(
MotionEvent.ACTION_MOVE -> follow(event.getX(0), event.getY(0), r)
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
touching = false
atRim = false
val cancelled = event.actionMasked == MotionEvent.ACTION_CANCEL || event.flags and MotionEvent.FLAG_CANCELED != 0
travel = maxOf(travel, hypot(event.x - downX, event.y - downY))
lastUp = if (!clicking && !cancelled && event.eventTime - downAt <= STICK_TAP_MS && travel <= tapSlop) event.eventTime else 0L
@@ -678,15 +685,27 @@ class InputSurfaceView(
var dx = x - originX
var dy = y - originY
val length = hypot(dx, dy)
if (length > r) { dx *= r / length; dy *= r / length }
if (force || dx != knobX || dy != knobY) move(dx, dy, r)
val rim = length > r
if (rim) { dx *= r / length; dy *= r / length }
val reachedRim = rim && !atRim
atRim = rim
if (force || dx != knobX || dy != knobY) move(dx, dy, r, throttled = !force && !reachedRim, rim = rim)
}
private fun move(dx: Float, dy: Float, r: Float) {
private fun move(dx: Float, dy: Float, r: Float, throttled: Boolean = false, rim: Boolean = false) {
knobX = dx
knobY = dy
source?.update(dx / r, dy / r)
invalidate()
if (!throttled) {
redraw.cancel()
drawnX = dx
drawnY = dy
invalidate()
} else if (rim || abs(dx - drawnX) >= MIN_STICK_MOVE_PX || abs(dy - drawnY) >= MIN_STICK_MOVE_PX) {
drawnX = dx
drawnY = dy
redraw.request()
}
}
private fun setClick(down: Boolean) {
@@ -699,6 +718,7 @@ class InputSurfaceView(
override fun onDetachedFromWindow() {
setClick(false)
if (knobX != 0f || knobY != 0f) move(0f, 0f, 1f)
redraw.cancel()
super.onDetachedFromWindow()
}
}
@@ -766,6 +786,8 @@ class InputSurfaceView(
companion object {
private const val CLICK_MS = 300L
private const val STICK_TAP_MS = 200L
private const val STICK_REDRAW_MS = 33L
private const val MIN_STICK_MOVE_PX = 1f
private const val CLASSIC_REACH = 0.5f
private const val PANEL_REACH = 0.30f
private const val HIT_SLACK = 0.25f
@@ -92,6 +92,38 @@ class AddedExesTest {
}
}
@Test fun reselectingTheCurrentExeKeepsItWhenTheRankingChanges() {
val storage = tmp.newFolder("Ranked")
exe(File(storage, "Example/Example.exe"))
exe(File(storage, "Example/Other.exe"))
SessionPrefs.setAddedGamesDirs(app, emptyList())
SessionPrefs.setGameStorage(app, storage.path, "Card")
val folder = File(storage, "Example")
val current = AddedGames.scan(app).single { it.folder == folder }.exe
val other = listOf("Example.exe", "Other.exe").map { File(folder, it) }.single { it.path != current.path }
val existing = AddedGames.addExe(app, current)
assertTrue(existing is AddedGames.AddResult.Existing)
assertEquals(current.path, SessionPrefs.addedGameExe(app, folder.path))
File(folder, "MicrosoftGame.config").writeText("<Executable Name=\"${other.name}\" />")
assertEquals(other.path, AddedGames.rank(folder).exes.first().path)
assertEquals(current.path, AddedGames.scan(app).single { it.folder == folder }.exe.path)
}
@Test fun reselectingASteamInstallsExeThroughAnAliasStoresTheReachablePath() {
val storage = tmp.newFolder("Aliased")
val pick = exe(File(storage, "steamapps/common/Example/Example.exe"))
File(storage, "steamapps/appmanifest_123.acf").writeText("\"installdir\" \"Example\"")
SessionPrefs.setAddedGamesDirs(app, emptyList())
SessionPrefs.setGameStorage(app, storage.path, "Card")
val alias = File(tmp.newFolder("Links"), "Example.exe")
java.nio.file.Files.createSymbolicLink(alias.toPath(), pick.toPath())
assertTrue(AddedGames.addExe(app, alias) is AddedGames.AddResult.Existing)
assertEquals(pick.path, AddedExes.list(app).single { it.folder == pick.parentFile!!.path }.exe)
assertEquals(pick.path, SessionPrefs.addedGameExe(app, pick.parentFile!!.path))
assertEquals(pick.path, AddedGames.scan(app).single { it.folder == pick.parentFile }.exe.path)
AddedExes.drop(app, pick.parentFile!!.path)
}
@Test fun anotherExeInTheSameGameSwitchesItsExe() {
noGamesFolders()
val first = onStorage("Games2/Hades/Hades.exe")
@@ -297,6 +329,39 @@ class AddedExesTest {
assertEquals(listOf(other.path), AddedGames.scan(app).map { it.exe.path })
}
private fun routeEveryGameTo(steamApp: Int) {
val config = File(SessionPrefs.activeSteamRoot(app), "userdata/123/config").apply { mkdirs() }
val routes = org.json.JSONObject()
AddedGames.scan(app).forEach { routes.put(it.appId.toString(), steamApp) }
File(config, ".droiddeck-routes.json").writeText(routes.toString())
}
@Test fun anotherProgramOfASteamInstallIsNotRoutedToTheSteamApp() {
noGamesFolders()
val main = onStorage("Games2/The Binding of Isaac Rebirth/isaac-ng.exe")
val launcher = onStorage("Games2/The Binding of Isaac Rebirth/REPENTOGONLauncher.exe")
AddedExes.put(app, AddedExes.Entry(main.parent!!, launcher.path))
routeEveryGameTo(250900)
val game = AddedGames.scan(app).single()
assertEquals(launcher.path, game.exe.path)
assertEquals(main.path, game.candidates.first().path)
assertNull(game.steamAppId)
assertTrue(!game.steamProgram)
assertTrue(File(AddedGames.writeListing(app, listOf(game), emptyList()).path).readText().contains("\"route\":false"))
}
@Test fun theSteamAppsOwnProgramStillRoutesToTheSteamApp() {
noGamesFolders()
val main = onStorage("Games2/The Binding of Isaac Rebirth/isaac-ng.exe")
onStorage("Games2/The Binding of Isaac Rebirth/REPENTOGONLauncher.exe")
AddedExes.put(app, AddedExes.Entry(main.parent!!, main.path))
routeEveryGameTo(250900)
val game = AddedGames.scan(app).single()
assertEquals(250900, game.steamAppId)
assertTrue(game.steamProgram)
assertTrue(!File(AddedGames.writeListing(app, listOf(game), emptyList()).path).readText().contains("route"))
}
@Test fun aDifferentGameWithANumberedNameIsNotTakenAsAnotherBuild() {
noGamesFolders()
val held = onStorage("Games2/id/Doom/Doom.exe")
@@ -47,6 +47,11 @@ class AddedGamesSteamEditsTest {
.writeText(JSONObject().put("games", JSONObject().put(appId.toString(), game)).toString())
}
private fun legacyAdoption(exe: File, seen: Int) {
context.getSharedPreferences("session", Context.MODE_PRIVATE).edit()
.putString("addedExe:${folder.path}", exe.path).putInt("addedExeSeen:${folder.path}", seen).commit()
}
private fun scanned() = AddedGames.scan(context).single { it.folder == folder }
@Test fun aTargetChangedInSteamBecomesTheAppsChoiceOnce() {
@@ -68,6 +73,65 @@ class AddedGamesSteamEditsTest {
assertEquals(main.path, SessionPrefs.addedGameExe(context, folder.path))
}
@Test fun aTargetChosenInSteamKeepsTheSteamAppsRouteBeforeAndAfterItIsAdopted() {
val first = scanned()
val routes = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/userdata/123/config/.droiddeck-routes.json")
routes.writeText(JSONObject().put(first.appId.toString(), 250900).toString())
assertEquals(250900, scanned().steamAppId)
record(first.appId, "/root/Games/PC/Example/Example.exe", "/root/Games/PC/Example/bin/Other.exe", 1)
val adopted = scanned()
assertEquals(other, adopted.exe)
assertEquals(250900, adopted.steamAppId)
assertTrue(adopted.steamProgram)
val later = scanned()
assertEquals(other, later.exe)
assertEquals(250900, later.steamAppId)
assertTrue(later.steamProgram)
}
@Test fun aTargetAdoptedBeforeTheMarkerExistedKeepsTheSteamAppsRoute() {
val first = scanned()
val routes = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/userdata/123/config/.droiddeck-routes.json")
routes.writeText(JSONObject().put(first.appId.toString(), 250900).toString())
record(first.appId, "/root/Games/PC/Example/Example.exe", "/root/Games/PC/Example/bin/Other.exe", 1)
legacyAdoption(other, 1)
assertNull(SessionPrefs.addedGameAdopted(context, folder.path, "Exe"))
val legacy = scanned()
assertEquals(other, legacy.exe)
assertEquals(250900, legacy.steamAppId)
assertTrue(legacy.steamProgram)
assertEquals(other.path, SessionPrefs.addedGameAdopted(context, folder.path, "Exe"))
}
@Test fun aProgramPickedInDroidDeckThatSteamNeverEditedStaysOutOfTheRoute() {
val first = scanned()
val routes = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/userdata/123/config/.droiddeck-routes.json")
routes.writeText(JSONObject().put(first.appId.toString(), 250900).toString())
record(first.appId, "/root/Games/PC/Example/Example.exe", "/root/Games/PC/Example/Example.exe", 1)
legacyAdoption(other, 1)
val picked = scanned()
assertEquals(other, picked.exe)
assertNull(picked.steamAppId)
assertTrue(!picked.steamProgram)
}
@Test fun aProgramChosenInDroidDeckAfterASteamEditLeavesTheSteamAppsRoute() {
val first = scanned()
val routes = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/userdata/123/config/.droiddeck-routes.json")
routes.writeText(JSONObject().put(first.appId.toString(), 250900).toString())
record(first.appId, "/root/Games/PC/Example/Example.exe", "/root/Games/PC/Example/bin/Other.exe", 1)
assertEquals(other, scanned().exe)
val third = File(folder, "Third.exe").apply { writeBytes(ByteArray(4)) }
SessionPrefs.setAddedGameExe(context, folder.path, third.path)
val chosen = scanned()
assertEquals(third, chosen.exe)
assertNull(chosen.steamAppId)
assertTrue(!chosen.steamProgram)
}
@Test fun theListingTellsTheSessionWhichSteamEditTheAppHasTaken() {
val first = scanned()
record(first.appId, "/root/Games/PC/Example/Example.exe", "/root/Games/PC/Example/bin/Other.exe", 3)
@@ -66,6 +66,27 @@ class AddedGamesStoreScanTest {
assertTrue(game.guestExe.endsWith("/Tools/Editor.exe"))
}
@Test fun everyStoreKeepsItsLauncherWhenItsOwnExeIsReselected() {
for (store in listOf(Store.GOG, Store.AMAZON, Store.EPIC)) {
val folder = install(store, "own-${store.id}", "Own ${store.label}", "Binaries/Game.exe", launcher = true)
val own = File(folder, "Binaries/Game.exe")
val before = AddedGames.scan(app).single { it.folder.absolutePath == folder.absolutePath }
assertTrue(AddedGames.addExe(app, own) is AddedGames.AddResult.Existing)
val game = AddedGames.scan(app).single { it.folder.absolutePath == folder.absolutePath }
assertEquals(own.path, game.exe.path)
assertTrue(game.guestExe.endsWith("/" + StoreLaunch.LAUNCHER))
assertEquals(before.appId, game.appId)
}
}
@Test fun aDifferentPickedExeOnAnyStoreGameIsRunDirectly() {
val folder = install(Store.GOG, "tool", "Tool GOG", "Binaries/Game.exe", launcher = true)
val tool = File(folder, "Tools/Editor.exe").apply { parentFile!!.mkdirs(); writeText("tool") }
AddedExes.put(app, AddedExes.Entry(folder.path, tool.path, picked = true))
val game = AddedGames.scan(app).single { it.folder.absolutePath == folder.absolutePath }
assertTrue(game.guestExe.endsWith("/Tools/Editor.exe"))
}
@Test fun anOlderSidecarsSteamSwitchIsIgnoredEveryInstallIsListed() {
val folder = install(Store.AMAZON, "amzn1.adg.product.x", "Yakuza 0", "Yakuza0.exe")
val file = StoreGameSidecar.file(folder)
@@ -45,7 +45,7 @@ class NativeGuestTest {
val command = NativeGuest.command(root, "/usr/bin/env", listOf("-i", "A=1"))
assertEquals(File(root, "usr/lib/ld-linux-aarch64.so.1").path, command[0])
assertEquals(listOf("--library-path", NativeGuest.libraryPath(root), "--argv0", "env", File(root, "usr/bin/env").path, "-i", "A=1"), command.drop(1))
assertTrue("LD_LIBRARY_PATH" !in NativeGuest.environment(root))
assertTrue("LD_LIBRARY_PATH" !in NativeGuest.environment(root, "/usr/bin/env"))
}
@Test
@@ -79,13 +79,22 @@ class NativeGuestTest {
@Test
fun mountsWithoutADestinationMapToThemselves() {
val root = rootWithLoader()
val env = NativeGuest.sessionEnvironment(root, listOf("/dev", "/a:/b"))
val env = NativeGuest.sessionEnvironment(root, listOf("/dev", "/a:/b"), "/usr/bin/env")
assertEquals("/dev:/dev|/a:/b", env["DDNATV_BINDS"])
assertEquals(root.path, env["DDNATV_ROOT"])
assertTrue("LD_LIBRARY_PATH" !in env)
assertTrue(env.getValue("LD_PRELOAD").replace(File.separatorChar, '/').endsWith("usr/lib/libddnatv-hook.so"))
}
@Test
fun theProgramTheLoaderRunsIsNamedInItsEnvironment() {
val root = rootWithLoader()
val program = NativeGuest.command(root, "/usr/bin/env", listOf("-i"))[5]
assertEquals(program, NativeGuest.sessionEnvironment(root, listOf("/dev"), "/usr/bin/env")["DDNATV_REAL_EXE"])
assertEquals(program, NativeGuest.environment(root, "/usr/bin/env")["DDNATV_REAL_EXE"])
assertEquals(program, NativeGuest.builder(root, "/", listOf("/usr/bin/env", "-i"), emptyMap()).environment()["DDNATV_REAL_EXE"])
}
private val linkRoot = "/data/user/0/app/files/linuxfs"
private val sdBinds = listOf(
"/mnt/media_rw/CARD/files/steam:/mnt/droiddeck-sd",
+6
View File
@@ -212,6 +212,12 @@ more, so its fix removes both variables, also from its launch options, and sets
`vk_x11_strict_image_count=true`, the option Mesa's driconf gives the game. A
per-game value in the environment editor still wins.
Dragon Quest Monsters 4 does not draw slime bodies at its default monster mesh
detail, leaving only their tips. Before each launch, DroidDeck sets
`r.SkeletalMeshLODBias=-4` and `r.SkeletalMeshLODRadiusScale=0.25` under
`[SystemSettings]` in the game's `Engine.ini`. It does this every time because the
game ignores `-ini:` overrides and deletes a writable `Engine.ini` after reading it.
## Defaults and available suggestions
The initial configuration enables Mesa shader caching with
@@ -215,6 +215,15 @@ Still to check by hand: pasting Android text into a game.
Force fullscreen is still unsafe without a matching Game Resolution: with the default (native),
a game drawing at another size fights it as in run 4. It stays off by default.
## Stretch 16:9 with two Xwayland servers
With "Stretch 16:9 to panel" the games' server starts at the 16:9 nested size, but the client sets it
to the output size at every launch (run 7), so games saw a near-square screen and letterboxed
themselves. While stretching, the session script rewrites a `GAMESCOPE_XWAYLAND_MODE_CONTROL` that
sizes the game server (`1`) to exactly the output into the nested size with `allow_super_res` set,
since gamescope otherwise clamps it to the output. A Game Resolution chosen in Steam is a different
size and is kept.
## Force fullscreen removed (`feat/remove-force-fullscreen`)
With games on their own Xwayland server, FlatOut 2 no longer shrinks under the QAM, which was the
+3 -1
View File
@@ -60,7 +60,9 @@ missing prefix is removed first, and nothing is copied.
The account's `.droiddeck-routes.json` maps shortcut IDs to real Steam app IDs so the
Android launcher uses the same title and Proton prefix as Steam. Other accounts do not
inherit those routes. Managed shortcuts are replaced; user-created shortcuts and
inherit those routes. A program chosen in DroidDeck other than the folder's default executable (for example a mod
launcher beside the game's own executable) is never routed: it stays its own shortcut and tile.
A target set in the Steam shortcut's properties keeps the route. Managed shortcuts are replaced; user-created shortcuts and
unreadable shortcut files are preserved. Both routes use the existing ARM64 Proton
registration.
+6
View File
@@ -312,6 +312,12 @@ else
mkdir -p "${linuxfs_dir}/usr/local/lib/droiddeck" "${linuxfs_dir}/usr/local/share/licenses/uruntime"
install -m644 "${uruntime_binary}" "${linuxfs_dir}/usr/local/lib/droiddeck/uruntime"
install -m644 "${repo_root}/tools/linuxfs/licenses/uruntime-LICENSE" "${linuxfs_dir}/usr/local/share/licenses/uruntime/LICENSE"
dwarfs_wrapper=$(cached "${DWARFS_SHA256}" "${DWARFS_ASSET}" \
bash -c 'curl -fsSL --retry 5 --retry-all-errors --connect-timeout 20 -o "$out" "$0"' "https://github.com/mhx/dwarfs/releases/download/${DWARFS_VERSION}/${DWARFS_ASSET}")
mkdir -p "${linuxfs_dir}/usr/local/share/licenses/dwarfs"
bash "${repo_root}/tools/linuxfs/unwrap-dwarfs.sh" "${dwarfs_wrapper}" "${linuxfs_dir}/usr/local/lib/droiddeck/dwarfsextract"
printf '%s %s\n' "${DWARFS_PAYLOAD_SHA256}" "${linuxfs_dir}/usr/local/lib/droiddeck/dwarfsextract" | shasum -a 256 -c - >&2
install -m644 "${repo_root}/tools/linuxfs/licenses/dwarfs-LICENSE" "${linuxfs_dir}/usr/local/share/licenses/dwarfs/LICENSE"
sync_assets="${repo_root}/app/src/main/assets/droiddeck-esync"
if [[ -f "${repo_root}/tools/droiddeck-esync/release.env" ]]; then
+1
View File
@@ -8,6 +8,7 @@
"tools/linuxfs/desktop",
"tools/linuxfs/licenses",
"tools/linuxfs/uruntime.env",
"tools/linuxfs/unwrap-dwarfs.sh",
"tools/gamescope/release.env",
"tools/wlroots/release.env",
"tools/mangoapp",
+7
View File
@@ -26,6 +26,13 @@ echo "${URUNTIME_SHA256} uruntime" | sha256sum -c -
install -Dm644 uruntime "$D/usr/local/lib/droiddeck/uruntime"
install -Dm644 tools/linuxfs/licenses/uruntime-LICENSE "$D/usr/local/share/licenses/uruntime/LICENSE"
rm uruntime
curl -fsSL --retry 5 --retry-all-errors --connect-timeout 20 -o dwarfs-wrapper "https://github.com/mhx/dwarfs/releases/download/${DWARFS_VERSION}/${DWARFS_ASSET}"
echo "${DWARFS_SHA256} dwarfs-wrapper" | sha256sum -c -
bash tools/linuxfs/unwrap-dwarfs.sh dwarfs-wrapper dwarfsextract
echo "${DWARFS_PAYLOAD_SHA256} dwarfsextract" | sha256sum -c -
install -Dm644 dwarfsextract "$D/usr/local/lib/droiddeck/dwarfsextract"
install -Dm644 tools/linuxfs/licenses/dwarfs-LICENSE "$D/usr/local/share/licenses/dwarfs/LICENSE"
rm dwarfs-wrapper dwarfsextract
M="$D/usr/local/lib/mangoapp"
mkdir -p "$M" mango-pkgs
grep -v '^#' tools/mangoapp/packages.txt | while read -r sum url; do
+9
View File
@@ -416,3 +416,12 @@ changed focus. In a nested session with no other window the SDL window stayed hi
on screen. Focus is now chosen again whenever a window's opacity crosses zero in either direction; a change between
two visible opacities leaves focus alone. `tools/tests/test_gamescope_focus_opacity.py` compiles the rule from this
patch and checks the property handler applies it.
## 0141 wlserver: the nested mouse moves the pointer while touch is Disabled
The nested Wayland pointer reaches wlserver as touch 0 (`bAlwaysWarpCursor`, see 0111), and in the Disabled touch click
mode `wlserver_touchmotion` returned before anything moved. Buttons take `wlserver_mousebutton`, so they still arrived,
at a pointer that never left the top-left corner. Steam picks Disabled for some games (Don't Starve Together): the drawn
cursor followed the mouse while every click landed at (0,0). In Disabled the nested pointer now warps the X pointer as
in the other modes; real fingers are still ignored. `tools/tests/test_gamescope_disabled_touch_mouse.py` compiles the
branch from this patch.
@@ -0,0 +1,16 @@
diff --git a/src/wlserver.cpp b/src/wlserver.cpp
index df352b0..9740875 100644
--- a/src/wlserver.cpp
+++ b/src/wlserver.cpp
@@ -3326,7 +3326,10 @@ void wlserver_touchmotion( double x, double y, int touch_id, uint32_t time, bool
}
else if ( eMode == gamescope::TouchClickModes::Disabled )
{
- return;
+ if ( !bAlwaysWarpCursor )
+ return;
+
+ wlserver_mousewarp( tx, ty, time, false );
}
else if ( eMode == gamescope::TouchClickModes::Trackpad )
{
+3
View File
@@ -118,6 +118,9 @@ if [ "$(cat /usr/share/droiddeck/kwin-compositor 2>/dev/null)" = opengl ]; then
# On the system PowerVR driver, Firefox's hardware WebRender on zink leaves stale, half-drawn
# frames; its software renderer draws correctly.
[ "${DD_STEAM_GL_PRESENT:-}" = 1 ] && export MOZ_ACCELERATED=0
# The system driver's (PowerVR, Xclipse) libhybris Wayland swapchain needs the app compositor's Android-buffer
# protocol, which KWin lacks: Plasma's clients present through DRI instead.
[ "${DD_STEAM_GL_PRESENT:-}" = 1 ] && export LIBGL_KOPPER_DISABLE=true
if [ -z "${KWIN_RENDER_NODES:-}" ]; then
for node in /dev/dri/renderD0 /dev/dri/renderD307 /dev/dri/renderD*; do
if [ -c "$node" ]; then export KWIN_RENDER_NODES="$node"; break; fi
+49
View File
@@ -0,0 +1,49 @@
Parts of the DwarFS project are licensed under the MIT license, while others are
licensed under the GPL-3.0 license. In general, the code used to *read* DwarFS
images is licensed under the MIT license, while the code used to *write* DwarFS
images is licensed under the GPL-3.0 license. Also, all testing/benchmarking
code is currently licensed under the GPL-3.0 license.
That means you can use `mkdwarfs` to create images and then use these images
with only the MIT-licensed code.
The following libraries and associated header files are licensed under the
MIT license:
- `dwarfs_common`
- `dwarfs_compressor`
- `dwarfs_decompressor`
- `dwarfs_extractor`
- `dwarfs_reader`
The following libraries and associated header files are licensed under the
GPL-3.0 license:
- `dwarfs_rewrite`
- `dwarfs_writer`
Each header and source file should contain an SPDX identifier near the top
of the file.
Please also check the licenses of the projects that DwarFS depends on.
----
MIT License
Copyright (c) Marcus Holland-Moritz
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the "Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the
following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial
portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO
EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -1,4 +1,4 @@
#!/usr/bin/env python3
#!/usr/bin/python3
import hashlib
import json
import os
@@ -1,4 +1,4 @@
#!/usr/bin/env python3
#!/usr/bin/python3
import argparse
import hashlib
import json
@@ -102,6 +102,7 @@ CLIENT_ENV = {
"WEBKIT_DISABLE_COMPOSITING_MODE": "1",
"WEBKIT_DISABLE_DMABUF_RENDERER": "1",
"WEBKIT_SKIA_ENABLE_CPU_RENDERING": "1",
"GDK_BACKEND": "x11",
"NO_AT_BRIDGE": "1",
"GTK_A11Y": "none",
"LIBGL_ALWAYS_SOFTWARE": "1",
@@ -27,6 +27,7 @@ GAME_ENVIRONMENT = os.path.join(HOME, ".config", "droiddeck", "game-environment.
BIN_DIR = os.path.dirname(os.path.abspath(__file__))
PRELOADS = "/usr/local/lib/droiddeck-fex"
URUNTIME = "/usr/local/lib/droiddeck/uruntime"
DWARFSEXTRACT = "/usr/local/lib/droiddeck/dwarfsextract"
HOST_PRELOAD = "/etc/ld.so.preload"
FEX_APPID = "3127680"
OWN_FEX = "/usr/local"
@@ -824,6 +825,30 @@ def extracted():
return os.path.isdir("squashfs-root")
def dwarfs_image(image):
try:
offset = appimage_offset(image)
with open(image, "rb") as f:
f.seek(offset)
return f.read(6) == b"DWARFS"
except (OSError, ValueError, struct.error):
return False
def dwarfs_extract(image):
clear_extracted()
os.mkdir("squashfs-root")
with open(image, "rb") as source:
status = subprocess.call([DWARFSEXTRACT, "--input", "/proc/self/fd/%d" % source.fileno(),
"--image-offset=%d" % appimage_offset(image), "--output", "squashfs-root",
"--log-level=error"], stdout=subprocess.DEVNULL, pass_fds=(source.fileno(),))
if status == 0 and extracted():
return True
say("dwarfsextract could not extract it (status %d)" % status)
clear_extracted()
return False
def want_fex():
with locked():
update_own_fex()
@@ -869,6 +894,10 @@ def extract(image):
return 0
say("uruntime could not extract it (status %d)" % status)
clear_extracted()
if os.access(DWARFSEXTRACT, os.X_OK) and dwarfs_image(image) and dwarfs_extract(image):
if x86:
want_fex()
return 0
fex = prepare() if x86 else None
if fex is not None:
status = subprocess.call([fex["bin"], image, "--appimage-extract"], stdout=subprocess.DEVNULL,
@@ -242,6 +242,57 @@ def skip_red_launcher(command):
return command
DQM4_MESH_DETAIL = {"r.SkeletalMeshLODBias": "-4", "r.SkeletalMeshLODRadiusScale": "0.25"}
def with_system_settings(text, settings):
lines = text.splitlines()
try:
section = lines.index("[SystemSettings]")
except ValueError:
if lines and lines[-1].strip():
lines.append("")
lines.append("[SystemSettings]")
section = len(lines) - 1
end = next((i for i in range(section + 1, len(lines)) if lines[i].startswith("[")), len(lines))
block = [line for line in lines[section + 1:end] if line.split("=", 1)[0].strip() not in settings]
while block and not block[-1].strip():
block.pop()
block += ["%s=%s" % item for item in settings.items()]
tail = lines[end:]
return "\n".join(lines[:section + 1] + block + ([""] if tail else []) + tail) + "\n"
# The game ignores -ini: overrides and deletes a writable Engine.ini after reading it, so this runs at every launch.
def dragon_quest_monsters_4_mesh_detail(exe, env):
project = Path(exe).stem.split("-", 1)[0]
if not project.lower().startswith("dragonquestmonsters4"):
return
prefix = Path(env.get("STEAM_COMPAT_DATA_PATH", "/nonexistent")) / "pfx"
config = prefix / "drive_c/users/steamuser/AppData/Local" / project / "Saved/Config/Windows/Engine.ini"
try:
if not prefix.is_dir():
return
text = config.read_text(encoding="utf-8") if config.exists() else ""
updated = with_system_settings(text, DQM4_MESH_DETAIL)
if updated == text:
return
config.parent.mkdir(parents=True, exist_ok=True)
handle, staged = tempfile.mkstemp(prefix=".engine-", dir=config.parent)
try:
with os.fdopen(handle, "w", encoding="utf-8") as target:
target.write(updated)
if config.exists():
os.chmod(staged, config.stat().st_mode & 0o7777)
os.replace(staged, config)
except BaseException:
os.unlink(staged)
raise
print("droiddeck-game-env: Dragon Quest Monsters 4: full-detail monster meshes", file=sys.stderr)
except (OSError, UnicodeDecodeError) as error:
print("droiddeck-game-env: Dragon Quest Monsters 4 mesh detail left as is (%s)" % error, file=sys.stderr)
UBISOFT_LAUNCHER = "drive_c/Program Files (x86)/Ubisoft/Ubisoft Game Launcher"
UBISOFT_SETTINGS = "drive_c/users/steamuser/AppData/Local/Ubisoft Game Launcher/settings.yaml"
@@ -1412,6 +1463,7 @@ def main():
command = skip_red_launcher(command)
if len(command) > 2:
death_stranding_allocator(app_id, command[2])
dragon_quest_monsters_4_mesh_detail(command[2], effective_env)
ubisoft_overlay_off(env)
project_zomboid_jvm(command)
fixes, extra, notes = engine_fixes(command[2], command[3:], app_id) if len(command) > 2 else ({}, [], [])
@@ -1,4 +1,4 @@
#!/usr/bin/env python3
#!/usr/bin/python3
import json
import os
import select
@@ -540,7 +540,7 @@ if [ -z "${DD_INSIDE:-}" ]; then
args=(--backend "$backend" --expose-wayland -f -W "$width" -H "$height" -w "$nested" -h "$nested_h")
if [ "${game_size:-0}" != 1 ] && { [ "$nested" != "$width" ] || [ "$nested_h" != "$height" ]; }; then
args+=(-S stretch)
export DD_STRETCHED=1
export DD_STRETCHED=1 DD_STRETCH_OUTPUT="${width}x${height}" DD_STRETCH_GAME="${nested}x${nested_h}"
fi
if [ "${DD_REFRESH:-0}" -gt 0 ]; then
args+=(-r "$DD_REFRESH")
@@ -593,6 +593,12 @@ dd_xprop_set_all() {
done
[ "$ok" = 1 ]
}
dd_stretch_game_screen() {
local idx w h super
IFS=', ' read -r idx w h super <<<"$1"
[ "$idx" = 1 ] && [ "${w}x${h}" = "$2" ] && [ "${super:-0}" = 0 ] || return 1
xprop -root -f GAMESCOPE_XWAYLAND_MODE_CONTROL 32c -set GAMESCOPE_XWAYLAND_MODE_CONTROL "$idx, ${3%x*}, ${3#*x}, 1" 2>/dev/null
}
export GDK_BACKEND=x11 QT_QPA_PLATFORM=xcb SDL_VIDEODRIVER=x11
reap_orphans() {
local round p stat pid left
@@ -1205,7 +1211,7 @@ case $mode in
[ "${DD_STRETCHED:-0}" = 1 ] && stretch=1
[ "${DD_RESTORE_ON_RESUME:-1}" = 1 ] && restore=1
atoms=(STEAM_TOUCH_CLICK_MODE GAMESCOPE_FOCUSED_APP)
[ "$stretch" = 1 ] && atoms+=(GAMESCOPE_NEW_SCALING_SCALER)
[ "$stretch" = 1 ] && atoms+=(GAMESCOPE_NEW_SCALING_SCALER GAMESCOPE_XWAYLAND_MODE_CONTROL)
prop_value() {
case $1 in *'not found'*|*=) pv=$2; return ;; esac
pv=${1#*=}
@@ -1273,6 +1279,11 @@ case $mode in
xprop -root -f GAMESCOPE_NEW_SCALING_SCALER 32c -set GAMESCOPE_NEW_SCALING_SCALER 4 2>/dev/null \
&& echo "== stretch 16:9 to panel: the client's scaler was Auto, set to Stretch"
;;
GAMESCOPE_XWAYLAND_MODE_CONTROL*)
prop_value "$line" ""
dd_stretch_game_screen "$pv" "$DD_STRETCH_OUTPUT" "$DD_STRETCH_GAME" \
&& echo "== stretch 16:9 to panel: the client sized the game screen to the output ($DD_STRETCH_OUTPUT), set to $DD_STRETCH_GAME"
;;
esac
done < <(xprop -spy -root "${atoms[@]}" 2>/dev/null)
) &
@@ -1,4 +1,4 @@
#!/usr/bin/env python3
#!/usr/bin/python3
import ctypes as C
import functools
import json
@@ -71,6 +71,10 @@ def store_game(game):
return bool(game.get("store"))
def steam_program(game):
return game.get("route") is not False
def manifest_ids(steamapps, name):
matches = []
try:
@@ -230,7 +234,7 @@ def remember_tried(steam_root, account, appids):
def watch(steam_root, listing):
games = [game for game in read_json(listing, []) if not store_game(game) and not game.get("native")]
games = [game for game in read_json(listing, []) if not store_game(game) and not game.get("native") and steam_program(game)]
if os.environ.get("DD_STEAM_OFFLINE") == "1" or not games:
return
candidates, sources = {}, {}
@@ -526,6 +530,13 @@ def release(steam_root, game, stale, reason):
print(f"droiddeck-steam-games: {game.get('name', appid)} {reason}; it is no longer Steam app {appid}")
def release_stale(steam_root, game, stale):
try:
release(steam_root, game, stale, "names another Steam app now")
except OSError as error:
print(f"droiddeck-steam-games: earlier import not undone ({error})")
PREFIX_LINKS = ".droiddeck-prefix-links.json"
@@ -603,17 +614,18 @@ def route(steam_root, acct, games):
if game.get("native"):
shortcuts.append(game)
continue
if not steam_program(game):
release_stale(steam_root, game, lambda old: old == SPACEWAR)
share_prefix(steam_root, game)
shortcuts.append(game)
continue
folder = game.get("folder", "")
appid = candidates.get(folder, candidates.get(legacy_path(folder)))
stamp = source_stamp(game)
recorded = sources.get(folder, sources.get(legacy_path(folder)))
current = stamp is not None and recorded in (stamp, [stamp[0], legacy_path(stamp[1])] + stamp[2:])
named = isinstance(appid, int) and 0 < appid < 0x80000000 and appid != SPACEWAR
try:
release(steam_root, game, lambda old: old == SPACEWAR or (current and named and old != appid),
"names another Steam app now")
except OSError as error:
print(f"droiddeck-steam-games: earlier import not undone ({error})")
release_stale(steam_root, game, lambda old: old == SPACEWAR or (current and named and old != appid))
confirmed = named and current and owned.get(str(appid)) is True
if confirmed:
try:
@@ -1,4 +1,4 @@
#!/usr/bin/env python3
#!/usr/bin/python3
"""Import added games while Steam is closed, preserving user-created shortcuts.
Usage: droiddeck-steam-shortcuts <steam_root> <added-games.json>
+1 -1
View File
@@ -1146,7 +1146,7 @@ static int steam_runtime_path(const char *path) {
const char *name = strrchr(path, '/');
size_t i;
if (name == NULL || strcmp(name + 1, "steam") != 0) return 0;
if (name == NULL || (strcmp(name + 1, "steam") != 0 && strcmp(name + 1, "streaming_client") != 0)) return 0;
for (i = 0; i < sizeof(runtimes) / sizeof(runtimes[0]); i++) {
size_t length = strlen(runtimes[i]);
+8
View File
@@ -0,0 +1,8 @@
#!/usr/bin/env bash
set -euo pipefail
wrapper=${1:?usage: unwrap-dwarfs.sh WRAPPER OUTPUT}
output=${2:?usage: unwrap-dwarfs.sh WRAPPER OUTPUT}
[ "$(tail -c 32 "$wrapper" | head -c 8)" = "SQUEEZE!" ] || { echo "unwrap-dwarfs.sh: $wrapper has no SQUEEZE! trailer" >&2; exit 1; }
packed=$(tail -c 16 "$wrapper" | od -An -tu8 -N8 | tr -d ' ')
[ "$packed" -gt 0 ] && [ "$packed" -le $(( $(wc -c < "$wrapper") - 32 )) ] || { echo "unwrap-dwarfs.sh: bad payload size in $wrapper" >&2; exit 1; }
tail -c $((packed + 32)) "$wrapper" | head -c "$packed" | zstd -dcq > "$output"
+4
View File
@@ -1,3 +1,7 @@
URUNTIME_VERSION=v0.8.1
URUNTIME_ASSET=uruntime-appimage-lite-aarch64
URUNTIME_SHA256=8485ae20eb0bfd4eaeac38d7fd7f78e153b391c718cf33ff07879605683be1ea
DWARFS_VERSION=v0.15.7
DWARFS_ASSET=dwarfs-fuse-extract-0.15.7-Linux-aarch64
DWARFS_SHA256=edb698186db6b162c755770ffabfcc05482bb7105a716fd943548e64244b0fd2
DWARFS_PAYLOAD_SHA256=cc3b3e342ca6537139d8c90d3c0a00236cf786bb61bdccf019e5ed0ca5917a7a
+118 -17
View File
@@ -134,8 +134,11 @@ static void init_ddnatv_hook(void) {
// environment is kept in. A program that had changed its environment (putenv, setenv) and passed it
// to execv() before its first call into the hook handed the exec code a block that was freed by the
// time it was read.
__attribute__((constructor(103))) static void init_ddnatv_hook_early(void) {
static void compact_loader_args(int argc, char **argv);
__attribute__((constructor(103))) static void init_ddnatv_hook_early(int argc, char **argv) {
init_ddnatv_hook();
compact_loader_args(argc, argv);
// The kernel names the process after what it executed, the rootfs ld.so: process monitors, and
// the app's own checks of /proc/<pid>/comm (steam, wineserver), saw only "ld-linux-aarch64.so.1"
const char *name = program_invocation_short_name;
@@ -232,27 +235,39 @@ static ssize_t (*real_readlinkat_fn(void))(int, const char *, char *, size_t) {
return fn;
}
static int proc_env_value(pid_t pid, const char *key, char *out, size_t outsz) {
char path[64];
snprintf(path, sizeof(path), "/proc/%d/environ", (int)pid);
int fd = open(path, O_RDONLY | O_CLOEXEC);
if (fd < 0) return 0;
size_t cap = 65536, used = 0, keylen = strlen(key);
char *env = malloc(cap + 1);
ssize_t got;
while (env && (got = read(fd, env + used, cap - used)) > 0) {
static char *read_proc_file(const char *path, size_t *len, int *whole) {
*len = 0;
*whole = 0;
int fd = (int)syscall(SYS_openat, AT_FDCWD, path, O_RDONLY | O_CLOEXEC);
if (fd < 0) return NULL;
size_t cap = 65536, used = 0;
char *text = malloc(cap + 1);
ssize_t got = 0;
while (text && (got = (ssize_t)syscall(SYS_read, fd, text + used, cap - used)) > 0) {
used += (size_t)got;
if (used == cap) {
char *bigger = cap < (8u << 20) ? realloc(env, cap * 2 + 1) : NULL;
char *bigger = cap < (8u << 20) ? realloc(text, cap * 2 + 1) : NULL;
if (!bigger) break;
env = bigger;
text = bigger;
cap *= 2;
}
}
close(fd);
syscall(SYS_close, fd);
if (!text) return NULL;
text[used] = '\0';
*len = used;
*whole = got == 0;
return text;
}
static int proc_env_value(pid_t pid, const char *key, char *out, size_t outsz) {
char path[64];
snprintf(path, sizeof(path), "/proc/%d/environ", (int)pid);
size_t used, keylen = strlen(key);
int whole;
char *env = read_proc_file(path, &used, &whole);
int found = 0;
if (env) {
env[used] = '\0';
for (char *e = env; e < env + used; e += strlen(e) + 1) {
if (strncmp(e, key, keylen) == 0 && e[keylen] == '=' && e[keylen + 1] != '\0') {
ddnatv_copy_cstr(out, outsz, e + keylen + 1);
@@ -265,6 +280,94 @@ static int proc_env_value(pid_t pid, const char *key, char *out, size_t outsz) {
return found;
}
static int is_loader_option(const char *arg) {
return strcmp(arg, "--preload") == 0 || strcmp(arg, "--library-path") == 0 || strcmp(arg, "--argv0") == 0;
}
static int is_exec_loader(const char *path) {
const char *base = strrchr(path, '/');
return strcmp(base ? base + 1 : path, "libddexec.so") == 0;
}
static size_t next_arg(const char *text, size_t pos) {
return pos + strlen(text + pos) + 1;
}
static uintptr_t *execfn_entry(int argc, char **argv) {
if (argv[argc]) return NULL;
char **env = argv + argc + 1;
while (*env) env++;
for (uintptr_t *aux = (uintptr_t *)(env + 1); aux[0] != AT_NULL; aux += 2) {
if (aux[0] == AT_EXECFN) return aux + 1;
}
return NULL;
}
static void compact_loader_args(int argc, char **argv) {
if (g_ddnatv_root[0] == '\0' || argc < 1 || !argv || !argv[0]) return;
size_t len;
int whole;
char *text = read_proc_file("/proc/self/cmdline", &len, &whole);
size_t *at = text && whole && len > 0 && text[len - 1] == '\0' ? malloc(sizeof(size_t) * (size_t)argc) : NULL;
size_t pos = 0, program = 0;
if (at && is_exec_loader(text)) {
pos = next_arg(text, pos);
if (pos < len) pos = next_arg(text, pos);
}
int ok = at && pos < len && is_ld_linux(text + pos), named = 0;
if (ok) pos = next_arg(text, pos);
while (ok && pos < len && is_loader_option(text + pos)) {
size_t value = next_arg(text, pos);
ok = value < len;
if (ok && strcmp(text + pos, "--argv0") == 0) {
at[0] = value;
named = 1;
}
if (ok) pos = next_arg(text, value);
}
int count = 0;
if (ok && named && pos < len) {
program = pos;
pos = next_arg(text, pos);
for (count = 1; pos < len && count < argc; count++) {
at[count] = pos;
pos = next_arg(text, pos);
}
}
char *base = count == argc && pos == len ? argv[0] - at[0] : NULL;
for (int i = 1; base && i < argc; i++) {
if (argv[i] != base + at[i]) base = NULL;
}
if (base && memcmp(base, text, len) != 0) base = NULL;
uintptr_t *execfn = base ? execfn_entry(argc, argv) : NULL;
char *execfn_text = NULL;
if (execfn && *execfn >= (uintptr_t)base && *execfn < (uintptr_t)base + len) {
execfn_text = strdup(text + (*execfn - (uintptr_t)base));
if (!execfn_text) base = NULL;
}
if (base) {
char *old_name = argv[0];
size_t name_len = strlen(old_name);
char *name = program_invocation_name, *short_name = program_invocation_short_name;
size_t used = 0;
for (int i = 0; i < argc; i++) {
size_t n = strlen(text + at[i]) + 1;
memcpy(base + used, text + at[i], n);
argv[i] = base + used;
used += n;
}
memset(base + used, 0, len - used);
if (name >= old_name && name <= old_name + name_len) program_invocation_name = argv[0] + (name - old_name);
if (short_name >= old_name && short_name <= old_name + name_len) {
program_invocation_short_name = argv[0] + (short_name - old_name);
}
if (g_real_exe[0] == '\0') ddnatv_copy_cstr(g_real_exe, sizeof(g_real_exe), text + program);
if (execfn_text) *execfn = (uintptr_t)execfn_text;
}
free(at);
free(text);
}
// Overlay filesystems report a different device to stat() than in /proc/<pid>/maps; the path, as the
// kernel resolved it, then stands in for the device.
static int proc_maps_file(pid_t pid, dev_t dev, ino_t ino, const char *resolved) {
@@ -320,9 +423,7 @@ static ssize_t handle_proc_other_exe(const char *path, char *buf, size_t bufsiz)
ssize_t n = real_readlinkat(AT_FDCWD, path, loader, sizeof(loader) - 1);
if (n <= 0) return -1;
loader[n] = '\0';
const char *base = strrchr(loader, '/');
base = base ? base + 1 : loader;
if (strcmp(base, "libddexec.so") != 0 && !is_ld_linux(loader)) return -1;
if (!is_exec_loader(loader) && !is_ld_linux(loader)) return -1;
char real_exe[PATH_MAX] = "";
if (!proc_env_value(pid, "DDNATV_REAL_EXE", real_exe, sizeof(real_exe))) {
+1 -1
View File
@@ -99,7 +99,7 @@ def required():
for name in ['turnip26.3.0-a6xx', 'turnip26.3.0-quest2']]
paths += ['assets/linuxfs/' + name for name in ['libfakeinput.so', 'libddsession.so',
'libddfastpath.so', 'libddnatv-hook.so', 'libssbs.so', 'usr/local/bin/droiddeck-clipboard',
'usr/local/bin/gamescope', 'usr/local/lib/droiddeck/uruntime',
'usr/local/bin/gamescope', 'usr/local/lib/droiddeck/uruntime', 'usr/local/lib/droiddeck/dwarfsextract',
'usr/local/lib/droiddeck-pipewire.tzst']]
for arch in ['x86_64', 'i386']:
paths += ['assets/linuxfs/' + arch + '/' + lib for lib in ['libfakeinput.so', 'libddsession.so']]
+42
View File
@@ -0,0 +1,42 @@
import os
from pathlib import Path
import subprocess
import tempfile
import unittest
DESKTOP = (Path(__file__).resolve().parents[1] / 'linuxfs/desktop/droiddeck-desktop').read_text()
START = 'if [ "$(cat /usr/share/droiddeck/kwin-compositor 2>/dev/null)" = opengl ]; then'
LAUNCH = 'dbus-run-session -- startplasma-wayland'
STUBS = '''
pipewire() { return 0; }
dbus-run-session() { sh -c 'echo "kopper:${LIBGL_KOPPER_DISABLE:-on}"'; }
'''
class DesktopPowerVrTest(unittest.TestCase):
def kopper_at_plasma_launch(self, gl_present):
segment = DESKTOP[DESKTOP.index(START):DESKTOP.index(LAUNCH) + len(LAUNCH)]
with tempfile.TemporaryDirectory() as run:
segment = (segment.replace(START, 'if true; then')
.replace('/usr/local/bin/droiddeck-pipewire', 'pipewire')
.replace('/run/droiddeck', run))
environment = {key: value for key, value in os.environ.items()
if key not in ('DD_STEAM_GL_PRESENT', 'LIBGL_KOPPER_DISABLE')}
if gl_present is not None:
environment['DD_STEAM_GL_PRESENT'] = gl_present
result = subprocess.run(['bash', '-c', STUBS + segment], env=environment,
capture_output=True, text=True, timeout=5)
self.assertEqual(0, result.returncode, result.stderr)
return result.stdout.strip().splitlines()[-1]
def test_system_powervr_plasma_starts_with_kopper_off(self):
self.assertEqual('kopper:true', self.kopper_at_plasma_launch('1'))
def test_other_drivers_start_plasma_with_kopper(self):
self.assertEqual('kopper:on', self.kopper_at_plasma_launch(None))
self.assertEqual('kopper:on', self.kopper_at_plasma_launch('0'))
if __name__ == '__main__':
unittest.main()
+11
View File
@@ -659,6 +659,17 @@ class DisplayTest(EpicTestCase):
self.assertNotIn("WAYLAND_DISPLAY", env)
self.assertEqual("unix:path=/b", env["DBUS_SESSION_BUS_ADDRESS"])
def test_the_launcher_draws_on_its_x_display_not_the_session_compositor(self):
base = {"XDG_RUNTIME_DIR": "/run/droiddeck", "WAYLAND_DISPLAY": "wayland-0",
"GAMESCOPE_WAYLAND_DISPLAY": "gamescope-0", "XDG_SESSION_TYPE": "wayland", "GDK_BACKEND": "wayland"}
with mock.patch.dict(G, {"fex_environment": lambda fex, files, base: {}}):
visible = G["client_environment"](base, None, None, ":1", "bus", "broker")
hidden = G["client_environment"](base, None, None, ":2", "bus", "broker", hidden=True)
for env, display in ((visible, ":1"), (hidden, ":2")):
self.assertEqual(("x11", display, "/run/droiddeck"), (env.get("GDK_BACKEND"), env.get("DISPLAY"), env.get("XDG_RUNTIME_DIR")))
for name in ("WAYLAND_DISPLAY", "GAMESCOPE_WAYLAND_DISPLAY", "XDG_SESSION_TYPE"):
self.assertNotIn(name, env)
class InstallationsTest(EpicTestCase):
def add_game(self, guid="G1", app="Fig", store="epic", extra=None):
+55
View File
@@ -1090,6 +1090,61 @@ class ExtractTest(FexTestCase):
self.assertNotIn("no unsquashfs", said)
self.assertFalse(os.path.lexists("squashfs-root"))
def runtime_elf(self):
head = bytearray(elf(183))
struct.pack_into("<Q", head, 0x28, len(head))
return bytes(head)
def dwarfs(self, body):
self.write(self.image, self.runtime_elf() + b"DWARFS\x02\x05payload", 0o755)
self.ran = self.tmp / "dwarfsextract-ran"
return str(self.write(self.tmp / "dwarfsextract", "#!/bin/sh\ntouch %s\n%s" % (self.ran, body), 0o755))
def test_a_dwarfs_image_the_runtime_cannot_unpack_is_read_through_its_open_descriptor(self):
reader = self.dwarfs(
'[ "$1 $3 $4 $5" = "--input --image-offset=64 --output squashfs-root" ] || exit 9\n'
'case $2 in /proc/self/fd/*) ;; *) exit 8 ;; esac\n'
'cmp -s "$2" "%s" || exit 7\ntouch squashfs-root/AppRun\n' % self.image)
tool = self.uruntime("echo 'Failed to execute dwarfsextract: EACCES: Permission denied' >&2\nexit 1\n")
with mock.patch.dict(os.environ, {"DDNATV_ROOT": str(self.tmp / "rootfs")}), \
mock.patch.dict(G, {"URUNTIME": tool, "DWARFSEXTRACT": reader}), \
mock.patch("shutil.which", return_value=None):
status, said = self.quiet(FEX["extract"], "image.AppImage")
self.assertEqual(status, 0)
self.assertIn("uruntime could not extract it (status 1)", said)
self.assertNotIn("dwarfsextract could not", said)
self.assertTrue(Path("squashfs-root/AppRun").is_file())
self.assertFalse((self.home / ".config/droiddeck/fex-wanted").exists())
def test_a_dwarfs_image_the_runtime_unpacks_never_runs_dwarfsextract(self):
reader = self.dwarfs("touch squashfs-root/AppRun\n")
tool = self.uruntime("mkdir -p AppDir && touch AppDir/AppRun\n")
with mock.patch.dict(G, {"URUNTIME": tool, "DWARFSEXTRACT": reader}):
status, said = self.quiet(FEX["extract"], "image.AppImage")
self.assertEqual((status, said), (0, ""))
self.assertFalse(self.ran.exists())
def test_a_dwarfsextract_failure_leaves_nothing_unpacked(self):
reader = self.dwarfs("mkdir -p squashfs-root/usr\nexit 3\n")
tool = self.uruntime("exit 1\n")
with mock.patch.dict(G, {"URUNTIME": tool, "DWARFSEXTRACT": reader}), \
mock.patch("shutil.which", return_value=None):
status, said = self.quiet(FEX["extract"], "image.AppImage")
self.assertEqual(status, 1)
self.assertTrue(self.ran.exists())
self.assertIn("dwarfsextract could not extract it (status 3)", said)
self.assertFalse(os.path.lexists("squashfs-root"))
def test_a_squashfs_image_still_goes_to_unsquashfs(self):
reader = self.dwarfs("exit 0\n")
self.write(self.image, self.runtime_elf() + b"hsqs" + b"payload", 0o755)
tool = self.uruntime("exit 1\n")
with mock.patch.dict(G, {"DWARFSEXTRACT": reader}):
status, said, commands = self.seven_zip(tool, {"unsquashfs": "/usr/bin/unsquashfs", "7z": "/usr/bin/7z"})
self.assertEqual(status, 0)
self.assertNotIn("dwarfsextract", said)
self.assertEqual(["/usr/bin/unsquashfs", "/usr/bin/7z"], [c[0] for c in commands])
class LaunchTest(FexTestCase):
def test_the_guest_environment(self):
+60
View File
@@ -1,3 +1,4 @@
import contextlib
import hashlib
import io
import json
@@ -1548,6 +1549,65 @@ class GameEnvironmentTest(unittest.TestCase):
self.assertEqual(MODULE["engine_fixes"](game, [], "42"), ({}, [], []))
self.assertEqual(MODULE["engine_fixes"](game, []), ({}, [], []))
def test_dragon_quest_monsters_4_writes_full_detail_mesh_settings(self):
apply = MODULE["dragon_quest_monsters_4_mesh_detail"]
wanted = "r.SkeletalMeshLODBias=-4\nr.SkeletalMeshLODRadiusScale=0.25\n"
for exe, project in (("DragonQuestMonsters4Demo.exe", "DragonQuestMonsters4Demo"),
("DragonQuestMonsters4-Win64-Shipping.exe", "DragonQuestMonsters4")):
with self.subTest(exe=exe), tempfile.TemporaryDirectory() as tmp:
(Path(tmp) / "pfx").mkdir()
config = Path(tmp) / "pfx/drive_c/users/steamuser/AppData/Local" / project / "Saved/Config/Windows/Engine.ini"
with contextlib.redirect_stderr(io.StringIO()):
apply("/game/" + exe, {"STEAM_COMPAT_DATA_PATH": tmp})
self.assertEqual(config.read_text(), "[SystemSettings]\n" + wanted)
def test_dragon_quest_monsters_4_keeps_other_engine_settings(self):
with tempfile.TemporaryDirectory() as tmp:
(Path(tmp) / "pfx").mkdir()
config = Path(tmp) / "pfx/drive_c/users/steamuser/AppData/Local/DragonQuestMonsters4Demo/Saved/Config/Windows/Engine.ini"
config.parent.mkdir(parents=True)
config.write_text("[Core.Log]\nLogTemp=Log\n\n[SystemSettings]\nr.Fog=0\nr.SkeletalMeshLODBias=0\n\n[Other]\nKey=1\n")
config.chmod(0o444)
with contextlib.redirect_stderr(io.StringIO()):
MODULE["dragon_quest_monsters_4_mesh_detail"]("/game/DragonQuestMonsters4Demo.exe", {"STEAM_COMPAT_DATA_PATH": tmp})
self.assertEqual(config.read_text(), "[Core.Log]\nLogTemp=Log\n\n[SystemSettings]\nr.Fog=0\n"
"r.SkeletalMeshLODBias=-4\nr.SkeletalMeshLODRadiusScale=0.25\n\n[Other]\nKey=1\n")
self.assertEqual(config.stat().st_mode & 0o777, 0o444)
def test_dragon_quest_monsters_4_settings_use_the_game_profile_prefix(self):
with tempfile.TemporaryDirectory() as tmp:
home = Path(tmp)
exe = home / "game/DragonQuestMonsters4Demo.exe"
exe.parent.mkdir()
exe.touch()
proton = home / "fake-proton"
proton.write_text("#!" + sys.executable + "\nimport json, sys\nprint(json.dumps(sys.argv[1:]))\n")
proton.chmod(0o755)
inherited, chosen = home / "compatdata/42", home / "profile/42"
for data in (inherited, chosen):
(data / "pfx").mkdir(parents=True)
config = home / ".config/droiddeck/game-environment.json"
config.parent.mkdir(parents=True)
config.write_text(json.dumps({"version": 1, "games": {"42": {"STEAM_COMPAT_DATA_PATH": str(chosen)}}}))
subprocess.run([sys.executable, str(BIN / "droiddeck-game-env"), str(proton), "waitforexitandrun", str(exe)],
env=dict(os.environ, HOME=tmp, STEAM_COMPAT_DATA_PATH=str(inherited)),
text=True, capture_output=True, check=True)
engine = "pfx/drive_c/users/steamuser/AppData/Local/DragonQuestMonsters4Demo/Saved/Config/Windows/Engine.ini"
self.assertIn("r.SkeletalMeshLODBias=-4", (chosen / engine).read_text())
self.assertFalse((inherited / engine).exists())
def test_dragon_quest_monsters_4_prefix_errors_do_not_stop_the_launch(self):
errors = io.StringIO()
with mock.patch.object(Path, "is_dir", side_effect=PermissionError("denied")), contextlib.redirect_stderr(errors):
MODULE["dragon_quest_monsters_4_mesh_detail"]("/game/DragonQuestMonsters4Demo.exe", {"STEAM_COMPAT_DATA_PATH": "/compatdata/42"})
self.assertIn("left as is", errors.getvalue())
def test_other_games_do_not_get_the_dragon_quest_monsters_4_settings(self):
with tempfile.TemporaryDirectory() as tmp:
(Path(tmp) / "pfx").mkdir()
MODULE["dragon_quest_monsters_4_mesh_detail"]("/game/DragonQuestMonsters3.exe", {"STEAM_COMPAT_DATA_PATH": tmp})
self.assertEqual(list((Path(tmp) / "pfx").iterdir()), [])
def test_arkham_city_gets_full_x87_precision_over_the_preset(self):
with tempfile.TemporaryDirectory() as tmp:
city = Path(tmp) / "Batman Arkham City GOTY/Binaries/Win32"
@@ -0,0 +1,76 @@
from pathlib import Path
import shutil
import subprocess
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[2]
PATCH = ROOT / "tools/gamescope/patches/0141-nested-mouse-moves-when-touch-is-disabled.patch"
def patched_source():
return "\n".join(line[1:] for line in PATCH.read_text().splitlines()
if line[:1] in (" ", "+") and not line.startswith("+++"))
def branch(text, start):
begin = text.index(start)
depth = 0
for i in range(text.index("{", begin), len(text)):
depth += {"{": 1, "}": -1}.get(text[i], 0)
if depth == 0:
return text[begin:i + 1]
raise ValueError(start)
PREAMBLE = r'''
#include <cassert>
#include <cstdint>
namespace gamescope { enum class TouchClickModes { Hover, Left, Right, Middle, Passthrough, Disabled, Trackpad }; }
static int warps, bumps, warp_from_touch = -1;
static double warp_x, warp_y;
static void wlserver_mousewarp( double x, double y, uint32_t, bool, bool bFromTouch = false ) { warps++; warp_x = x; warp_y = y; warp_from_touch = bFromTouch; }
static void bump_input_counter() { bumps++; }
static void touchmotion( double tx, double ty, uint32_t time, bool bAlwaysWarpCursor )
{
gamescope::TouchClickModes eMode = gamescope::TouchClickModes::Disabled;
if ( eMode == gamescope::TouchClickModes::Passthrough )
{
}
'''
MAIN = r'''
bump_input_counter();
}
int main() {
touchmotion( 0.0, 0.0, 1, false );
assert( warps == 0 && bumps == 0 );
touchmotion( 640.5, 360.25, 2, true );
assert( warps == 1 && warp_x == 640.5 && warp_y == 360.25 );
assert( warp_from_touch == 0 );
assert( bumps == 1 );
return 0;
}
'''
class GamescopeDisabledTouchMouseTest(unittest.TestCase):
def test_the_nested_mouse_moves_the_pointer_while_fingers_stay_ignored(self):
compiler = shutil.which("c++") or shutil.which("g++") or shutil.which("clang++")
if not compiler:
self.skipTest("no C++ compiler")
disabled = branch(patched_source(), "else if ( eMode == gamescope::TouchClickModes::Disabled )")
with tempfile.TemporaryDirectory() as tmp:
src = Path(tmp) / "disabled_touch_mouse.cpp"
exe = Path(tmp) / "disabled_touch_mouse"
src.write_text(PREAMBLE + "\t" + disabled + "\n" + MAIN)
subprocess.run([compiler, "-std=c++17", "-Wall", "-Werror", "-UNDEBUG", str(src), "-o", str(exe)], check=True)
subprocess.run([str(exe)], check=True)
if __name__ == "__main__":
unittest.main()
+5 -3
View File
@@ -650,9 +650,11 @@ class InputUdevPreloadTest(unittest.TestCase):
"nothing added scan -1",
])
def test_only_the_steam_client_runtime_path_gets_the_real_libudev(self):
for path, pad in (("steamrt64/steam", 0), ("steamrtarm64/steam", 0), ("steamrt64/steam-probe", 1),
("xsteamrt64/steam", 1), ("steamrt64/xsteam", 1), ("steamrt/steam", 1)):
def test_only_the_steam_client_and_its_remote_play_client_get_the_real_libudev(self):
for path, pad in (("steamrt64/steam", 0), ("steamrtarm64/steam", 0), ("steamrt64/streaming_client", 0),
("steamrtarm64/streaming_client", 0), ("steamrt64/steam-probe", 1),
("steamrt64/streaming_client2", 1), ("xsteamrt64/steam", 1), ("steamrt64/xsteam", 1),
("steamrt/steam", 1), ("steamrt/streaming_client", 1)):
with self.subTest(path=path):
client = self.dir / "clients" / path
client.parent.mkdir(parents=True, exist_ok=True)
+179
View File
@@ -0,0 +1,179 @@
import os
from pathlib import Path
import subprocess
import tempfile
import unittest
from tools.tests.test_usr2_preload import runner
REPO = Path(__file__).resolve().parents[2]
HOOK_BUILD = REPO / "tools/nativeguest/build.sh"
DDEXEC = REPO / "app/src/main/cpp/ddexec/ddexec.c"
DDEXEC_FLAGS = ["-shared", "-fPIC", "-O2", "-ffreestanding", "-fno-builtin", "-fno-stack-protector",
"-fno-asynchronous-unwind-tables", "-nostdlib", "-Wl,-e,_start", "-Wl,-z,noexecstack",
"-Wl,--no-undefined", "-Wl,-Bsymbolic"]
WINDOWS_PROGRAM = "C:\\Program Files (x86)\\Battle.net\\Battle.net.exe"
PROBE = r"""
#define _GNU_SOURCE
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <sys/auxv.h>
#include <sys/syscall.h>
#include <unistd.h>
static void show_cmdline(const char *label) {
static char buf[1 << 20];
int fd = (int)syscall(SYS_openat, AT_FDCWD, "/proc/self/cmdline", O_RDONLY);
ssize_t len = 0, n;
while (fd >= 0 && (n = read(fd, buf + len, sizeof(buf) - len)) > 0) len += n;
if (fd >= 0) close(fd);
while (len > 0 && buf[len - 1] == '\0') len--;
printf("%s", label);
for (ssize_t at = 0; at < len; at += (ssize_t)strlen(buf + at) + 1) printf("\t%s", buf + at);
printf("\n");
}
int main(int argc, char **argv) {
int contiguous = 1;
for (int i = 1; i < argc; i++) {
if (argv[i] != argv[i - 1] + strlen(argv[i - 1]) + 1) contiguous = 0;
}
printf("execfn\t%s\n", (const char *)getauxval(AT_EXECFN));
printf("contiguous\t%d\n", contiguous);
printf("argv");
for (int i = 0; i < argc; i++) printf("\t%s", argv[i]);
printf("\n");
printf("name\t%s\t%s\n", program_invocation_name, program_invocation_short_name);
show_cmdline("cmdline");
if (argc > 1 && contiguous) {
size_t offset = (size_t)(argv[1] - argv[0]);
char *end = argv[argc - 1] + strlen(argv[argc - 1]) + 1;
memmove(argv[0], argv[1], (size_t)(end - argv[1]));
memset(end - offset, 0, offset);
show_cmdline("shifted");
}
return 0;
}
"""
class NativeHookCmdlineTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.cc, cls.prefix = runner()
if cls.cc is None:
raise unittest.SkipTest("no aarch64 compiler and runner")
cls.tmp = tempfile.TemporaryDirectory()
tmp = Path(cls.tmp.name)
cls.hook = tmp / "hook.so"
subprocess.run(["bash", str(HOOK_BUILD), str(cls.hook), cls.cc], check=True, capture_output=True)
(tmp / "probe.c").write_text(PROBE)
cls.probe = tmp / "probe"
subprocess.run([cls.cc, "-O1", "-o", str(cls.probe), str(tmp / "probe.c")], check=True)
cls.ddexec = tmp / "lib/libddexec.so"
cls.ddexec.parent.mkdir()
subprocess.run([cls.cc, *DDEXEC_FLAGS, "-o", str(cls.ddexec), str(DDEXEC)], check=True)
cls.ddexec_runs = subprocess.run(list(cls.prefix) + [str(cls.ddexec), str(cls.probe), str(cls.probe)],
capture_output=True, timeout=120).returncode == 0
cls.root = tmp / "root"
cls.root.mkdir()
if cls.prefix:
libs = Path(cls.prefix[cls.prefix.index("-L") + 1]) / "lib"
else:
libs = next(Path(p) for p in ("/lib/aarch64-linux-gnu", "/usr/lib/aarch64-linux-gnu", "/lib64")
if (Path(p) / "libc.so.6").exists())
cls.ld_so = next(str(p) for p in (libs / "ld-linux-aarch64.so.1", Path("/lib/ld-linux-aarch64.so.1"))
if p.exists())
cls.libs = str(libs)
@classmethod
def tearDownClass(cls):
cls.tmp.cleanup()
def run_probe(self, argv, root=True, preload=False):
env = {k: v for k, v in os.environ.items() if k not in ("LD_PRELOAD", "DDNATV_ROOT", "DDNATV_REAL_EXE")}
if root:
env["DDNATV_ROOT"] = str(self.root)
runner_args = list(self.prefix)
if preload and self.prefix:
runner_args += ["-E", f"LD_PRELOAD={self.hook}"]
elif preload:
env["LD_PRELOAD"] = str(self.hook)
out = subprocess.run(runner_args + argv, env=env, capture_output=True, text=True, timeout=120)
self.assertEqual(out.returncode, 0, out.stderr)
return {line.split("\t")[0]: line.split("\t")[1:] for line in out.stdout.splitlines()}
def loader_argv(self, *args, name="/usr/bin/wine"):
named = ["--argv0", name] if name else []
return [self.ld_so, "--preload", str(self.hook), "--library-path", self.libs, *named, str(self.probe), *args]
def test_a_program_its_loader_starts_has_its_arguments_together(self):
seen = self.run_probe(self.loader_argv(WINDOWS_PROGRAM, "--in-tray"))
self.assertEqual(["/usr/bin/wine", WINDOWS_PROGRAM, "--in-tray"], seen["argv"])
self.assertEqual(["1"], seen["contiguous"])
self.assertEqual(["/usr/bin/wine", "wine"], seen["name"])
@unittest.skipIf(runner()[1], "qemu answers /proc/self/cmdline from its own copy of the arguments")
def test_the_command_line_shows_the_arguments_the_program_was_started_with(self):
seen = self.run_probe(self.loader_argv(WINDOWS_PROGRAM, "--in-tray"))
self.assertEqual(["/usr/bin/wine", WINDOWS_PROGRAM, "--in-tray"], seen["cmdline"])
self.assertEqual([WINDOWS_PROGRAM, "--in-tray"], seen["shifted"])
@unittest.skipIf(runner()[1], "qemu answers /proc/self/cmdline from its own copy of the arguments")
def test_the_app_loader_in_front_of_the_loader_is_left_out(self):
if not self.ddexec_runs:
self.skipTest("libddexec.so does not start a program on this host")
seen = self.run_probe([str(self.ddexec), self.ld_so] + self.loader_argv(WINDOWS_PROGRAM))
self.assertEqual(["/usr/bin/wine", WINDOWS_PROGRAM], seen["argv"])
self.assertEqual(["/usr/bin/wine", WINDOWS_PROGRAM], seen["cmdline"])
self.assertEqual([WINDOWS_PROGRAM], seen["shifted"])
@unittest.skipIf(runner()[1], "qemu answers AT_EXECFN from its own copy of the arguments")
def test_a_program_its_loader_starts_still_finds_its_own_path(self):
unchanged = self.run_probe(self.loader_argv(WINDOWS_PROGRAM), root=False)
self.assertEqual([str(self.probe)], unchanged["execfn"])
seen = self.run_probe(self.loader_argv(WINDOWS_PROGRAM, "--in-tray"))
self.assertEqual([WINDOWS_PROGRAM, "--in-tray"], seen["shifted"])
self.assertEqual(unchanged["execfn"], seen["execfn"])
@unittest.skipIf(runner()[1], "qemu answers AT_EXECFN from its own copy of the arguments")
def test_a_program_the_app_loader_starts_still_finds_its_own_path(self):
if not self.ddexec_runs:
self.skipTest("libddexec.so does not start a program on this host")
argv = [str(self.ddexec), self.ld_so] + self.loader_argv(WINDOWS_PROGRAM)
unchanged = self.run_probe(argv, root=False)
seen = self.run_probe(argv)
self.assertEqual([WINDOWS_PROGRAM], seen["shifted"])
self.assertEqual(unchanged["execfn"], seen["execfn"])
self.assertNotEqual([""], seen["execfn"])
def test_a_loader_run_without_a_program_name_keeps_its_command_line(self):
argv = self.loader_argv(WINDOWS_PROGRAM, name=None)
seen = self.run_probe(argv)
self.assertEqual([str(self.probe), WINDOWS_PROGRAM], seen["argv"])
self.assertEqual(["1"], seen["contiguous"])
if not self.prefix:
self.assertEqual(argv, seen["cmdline"])
def test_outside_the_native_userland_the_command_line_is_unchanged(self):
argv = self.loader_argv(WINDOWS_PROGRAM)
seen = self.run_probe(argv, root=False)
self.assertEqual(["/usr/bin/wine", WINDOWS_PROGRAM], seen["argv"])
self.assertEqual(["0"], seen["contiguous"])
if not self.prefix:
self.assertEqual(argv, seen["cmdline"])
def test_a_program_started_directly_is_unchanged(self):
seen = self.run_probe([str(self.probe), WINDOWS_PROGRAM, "--in-tray"], preload=True)
self.assertEqual([str(self.probe), WINDOWS_PROGRAM, "--in-tray"], seen["argv"])
self.assertEqual(["1"], seen["contiguous"])
if not self.prefix:
self.assertEqual([str(self.probe), WINDOWS_PROGRAM, "--in-tray"], seen["cmdline"])
if __name__ == "__main__":
unittest.main()
+15 -5
View File
@@ -74,8 +74,8 @@ class NativeHookProcExeTest(unittest.TestCase):
shutil.copy(shutil.which(cls.prefix[0]), cls.loader)
cls.loader_args = list(cls.prefix[1:])
else:
ld = next(p for p in ("/lib/ld-linux-aarch64.so.1", "/lib64/ld-linux-aarch64.so.1") if os.path.exists(p))
shutil.copy(ld, cls.loader)
cls.ld_so = next(p for p in ("/lib/ld-linux-aarch64.so.1", "/lib64/ld-linux-aarch64.so.1") if os.path.exists(p))
shutil.copy(cls.ld_so, cls.loader)
cls.loader_args = []
@classmethod
@@ -83,11 +83,13 @@ class NativeHookProcExeTest(unittest.TestCase):
cls.tmp.cleanup()
def start(self, loader, real_exe=None, program=None):
env = {k: v for k, v in os.environ.items() if k not in ("LD_PRELOAD", "DDNATV_REAL_EXE")}
if real_exe:
env["DDNATV_REAL_EXE"] = real_exe
program = program or Path(self.tmp.name) / "sleeper"
cmd = ([str(self.loader), *self.loader_args] if loader else list(self.prefix)) + [str(program)]
return self.spawn(cmd, {"DDNATV_REAL_EXE": real_exe} if real_exe else {})
def spawn(self, cmd, extra_env):
env = {k: v for k, v in os.environ.items() if k not in ("LD_PRELOAD", "DDNATV_ROOT", "DDNATV_REAL_EXE")}
env.update(extra_env)
child = subprocess.Popen(cmd, env=env, stdout=subprocess.PIPE, text=True)
self.addCleanup(child.stdout.close)
self.addCleanup(child.wait)
@@ -141,6 +143,14 @@ class NativeHookProcExeTest(unittest.TestCase):
link = f"/proc/{pid}/exe"
self.assertEqual(os.readlink(link), self.readlink(link)[link])
@unittest.skipIf(runner()[1], "qemu answers /proc/self/cmdline from its own copy of the arguments")
def test_a_program_whose_hook_moved_its_arguments_is_still_named(self):
cmd = [self.ld_so, "--preload", str(self.hook), "--argv0", self.kwin.name, str(self.kwin)]
pid = self.spawn(cmd, {"DDNATV_ROOT": str(self.root), "DDNATV_REAL_EXE": str(self.kwin)})
self.assertEqual(b"kwin_wayland", Path(f"/proc/{pid}/cmdline").read_bytes().rstrip(b"\0"))
link = f"/proc/{pid}/exe"
self.assertEqual("/usr/bin/kwin_wayland", self.readlink(link)[link])
def test_a_loader_without_a_known_program_keeps_the_kernel_link(self):
pid = self.start(loader=True)
link = f"/proc/{pid}/exe"
+36
View File
@@ -261,6 +261,27 @@ class ImportsTest(unittest.TestCase):
imports.watch(str(self.steam), str(listing))
identify.assert_not_called()
def test_another_program_of_a_steam_install_stays_a_shortcut_beside_the_steam_app(self):
game, library = self.steam_install()
other = dict(game, name='Mod Launcher', exe=str(Path(game['folder']) / 'ModLauncher.exe'),
appid=0x87654322, route=False)
Path(other['exe']).write_bytes(b'mod')
imports.save_json(self.acct / 'config' / imports.STATE,
dict(account='123', owned={'42': True}, candidates={game['folder']: 42},
sources={game['folder']: imports.source_stamp(game)}))
games, routes = imports.route(self.steam, self.acct, [game, other])
self.assertEqual([other], games)
self.assertEqual({str(game['appid']): 42}, routes)
link = self.steam / 'steamapps/compatdata' / str(other['appid'] & 0xFFFFFFFF)
self.assertEqual(library / 'steamapps/compatdata/42', link.resolve())
def test_watch_never_looks_up_programs_that_are_not_the_steam_apps_own(self):
listing = self.root / 'games.json'
listing.write_text(json.dumps([dict(self.game, route=False)]))
with patch.object(imports, 'identify') as identify:
imports.watch(str(self.steam), str(listing))
identify.assert_not_called()
def test_native_programs_stay_shortcuts_and_are_never_looked_up(self):
self.snapshot()
game = dict(self.game, native=True)
@@ -692,6 +713,21 @@ class ImportsTest(unittest.TestCase):
self.assert_not_imported_as(480)
self.assertEqual(b'game', self.exe.read_bytes())
def test_spacewar_import_is_released_for_a_program_that_is_not_the_steam_apps_own(self):
self.import_as(480)
other = dict(self.game, appid=0x87654322, route=False)
with patch('builtins.print'):
self.assertEqual(([other], {}), imports.route(self.steam, self.acct, [other]))
self.assert_not_imported_as(480)
self.assertEqual(b'game', self.exe.read_bytes())
def test_a_steam_import_stays_when_another_program_of_the_install_is_listed(self):
self.snapshot()
imports.route(self.steam, self.acct, [self.game])
other = dict(self.game, appid=0x87654322, route=False)
imports.route(self.steam, self.acct, [other])
self.assertTrue((self.steam / 'steamapps/appmanifest_42.acf').is_file())
def test_import_follows_the_app_the_files_name_now(self):
self.snapshot()
imports.route(self.steam, self.acct, [self.game])
+56
View File
@@ -0,0 +1,56 @@
import os
from pathlib import Path
import subprocess
import tempfile
import unittest
SESSION = Path(__file__).resolve().parents[1] / 'linuxfs/overlay/usr/local/bin/droiddeck-session'
OUTPUT = '2184x1968'
GAME = '3498x1968'
class StretchGameScreenTest(unittest.TestCase):
def call(self, value):
source = SESSION.read_text()
start = source.index('dd_stretch_game_screen() {')
end = source.index('\n}\n', start) + 3
with tempfile.TemporaryDirectory() as directory:
log = Path(directory) / 'xprop.log'
fake = Path(directory) / 'xprop'
fake.write_text('#!/bin/bash\nprintf "%s\\n" "$*" >> "$XPROP_LOG"\n')
fake.chmod(0o755)
env = dict(os.environ, XPROP_LOG=str(log), PATH=directory + os.pathsep + os.environ['PATH'])
script = source[start:end] + f'dd_stretch_game_screen "{value}" {OUTPUT} {GAME}\n'
result = subprocess.run(['bash', '-c', script], env=env, capture_output=True, text=True, timeout=5)
written = log.read_text().splitlines() if log.exists() else []
return result.returncode, written
def test_the_game_screen_the_client_sizes_to_the_output_is_given_the_stretched_size(self):
status, written = self.call('1, 2184, 1968, 0')
self.assertEqual(0, status)
self.assertEqual(['-root -f GAMESCOPE_XWAYLAND_MODE_CONTROL 32c -set GAMESCOPE_XWAYLAND_MODE_CONTROL 1, 3498, 1968, 1'], written)
def test_a_game_resolution_chosen_in_steam_is_kept(self):
status, written = self.call('1, 1280, 720, 0')
self.assertNotEqual(0, status)
self.assertEqual([], written)
def test_the_clients_own_screen_is_left_alone(self):
status, written = self.call('0, 2184, 1968, 0')
self.assertNotEqual(0, status)
self.assertEqual([], written)
def test_the_stretched_size_is_not_rewritten_again(self):
status, written = self.call('1, 3498, 1968, 1')
self.assertNotEqual(0, status)
self.assertEqual([], written)
def test_a_missing_property_is_ignored(self):
status, written = self.call('')
self.assertNotEqual(0, status)
self.assertEqual([], written)
if __name__ == '__main__':
unittest.main()
+45
View File
@@ -0,0 +1,45 @@
import struct
import subprocess
import tempfile
import unittest
from pathlib import Path
SCRIPT = Path(__file__).resolve().parents[1] / "linuxfs/unwrap-dwarfs.sh"
class UnwrapDwarfsTest(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.dir = Path(self.temp.name)
self.output = self.dir / "dwarfsextract"
def wrapper(self, payload, magic=b"SQUEEZE!", packed=None):
compressed = subprocess.run(["zstd", "-q", "-c"], input=payload, capture_output=True, check=True).stdout
size = len(compressed) if packed is None else packed
path = self.dir / "wrapper"
path.write_bytes(b"\x7fELF stub" * 100 + compressed + magic + struct.pack("<QQQ", len(payload), size, 0))
return path
def unwrap(self, wrapper):
return subprocess.run(["bash", str(SCRIPT), str(wrapper), str(self.output)], capture_output=True, text=True)
def test_the_payload_behind_the_stub_is_unpacked(self):
payload = b"\x7fELF" + bytes(range(256)) * 64
run = self.unwrap(self.wrapper(payload))
self.assertEqual(run.returncode, 0, run.stderr)
self.assertEqual(self.output.read_bytes(), payload)
def test_a_file_without_the_trailer_is_refused(self):
run = self.unwrap(self.wrapper(b"payload", magic=b"NOTSQZ!!"))
self.assertNotEqual(run.returncode, 0)
self.assertIn("no SQUEEZE! trailer", run.stderr)
def test_a_payload_size_beyond_the_file_is_refused(self):
run = self.unwrap(self.wrapper(b"payload", packed=1 << 40))
self.assertNotEqual(run.returncode, 0)
self.assertIn("bad payload size", run.stderr)
if __name__ == "__main__":
unittest.main()