Compare commits

..
Author SHA1 Message Date
The412Banner 1861bd4b9a feat(dual-screen): game name in the stats strip; each Steam start opens on Chat
- The Tiles and Rings strips' top line has the DroidDeck mark and name on the
  left, the clock on the right and, in the middle, the running game's name
  (from its Steam app manifest or non-Steam shortcut), or "Steam Client ARM" /
  "Steam Client x86" while no game runs in a Steam session.
- The dashboard opens on Chat at every Steam session start. The tab picked
  during a session is remembered for that session only (the bottomPage
  preference is gone); a game start still switches to In-game stats.
2026-11-01 00:02:04 +00:00
The412Banner f8fb1db3c8 fix(dual-screen): DiRT stand-in put back for the Proton the game ran on
When a DiRT 3 / DiRT Showdown game was switched to another Proton, the first
launch swapped the stand-in in for the old Proton's ws2_32.dll link; Proton
then relinked the prefix's other DLLs to itself but left the stand-in, and
the old link went back after the game. With telemetry off the game would then
load the old Proton's ws2_32.dll under the new Wine. The launch now links the
running Proton's ws2_32.dll back instead when the saved link belongs to
another Proton (compared by real path, so esync packs that reach the stock
files through a linked folder count as the same Proton).
2026-10-31 23:39:19 +00:00
The412Banner e6e3673709 feat(dual-screen): speed leads the racing dashes, in mph or km/h
- Speedometer, Circuit and Glance show the speed as the big number; the
  unit and the gear sit under it.
- Speed units: Automatic (default), km/h or mph, a row on the In-game stats
  page; a tap moves to the next one. Automatic is mph where road speed limits
  are signed in mph (the United States and its territories, the United
  Kingdom and its Crown Dependencies, Liberia, the Bahamas, Belize) by the
  phone's region, else km/h. Every dash follows it: speed numbers, the
  speedometer dial (0-140 mph or 0-220 km/h), the Dials gauge and the Trace
  chart.
2026-10-31 22:40:29 +00:00
The412Banner 268dcef559 fix(dual-screen): DiRT 3 and DiRT Showdown telemetry no longer stops the game (error 10038)
DiRT 3 and DiRT Showdown keep sending motion telemetry on the UDP socket they
closed at the end of a race (and when leaving Joyride); sendto() fails with
WSAENOTSOCK and the game stops with "sendto failed with error 10038".

- tools/dirt-ws2: a 32-bit ws2_32.dll stand-in. Every export jumps to the
  same-ordinal export of Wine's own ws2_32.dll; only a sendto() failing with
  10038 reports 0 bytes sent. Built in CI (components recipe dirt-ws2, clang +
  lld) with its exports checked against Wine 11's list, staged to
  /usr/local/lib/droiddeck-dirt.
- droiddeck-game-env: for dirt3_game.exe / showdown.exe / showdown_avx.exe
  with the game's UDP/motion output on, and a Proton whose own ws2_32.dll lacks
  the fix, the stand-in replaces the prefix's syswow64/ws2_32.dll (Wine loads
  ws2_32 as a KnownDLL from there, so a copy beside the game is ignored) with
  WINEDLLOVERRIDES=ws2_32=n,b; the launch waits for the game and puts the
  prefix's own file back. A copy left by a killed launch is put back at the
  next launch in that prefix.
- Automatic turns DiRT 3 and DiRT Showdown on like the other games again; the
  crash warning and the switched-on-by-hand memory from the previous build
  are gone.

Same behaviour as DiRTTelemetryErrorFix by RoccoC (MIT), based on the fix by
Carsten Gottschling. DroidDeck-Proton gets the same rule in its own ws2_32
(branch fix/dirt-telemetry-sendto); the swap is skipped there.
2026-10-31 21:55:36 +00:00
The412Banner 66abf0c707 fix(dual-screen): tap-only In-game stats styles; Automatic leaves DiRT 3 and Showdown off
- The Layout row is gone; tapping the top strip or the dash changes its
  style, and one line under the page says so.
- DiRT 3 and DiRT Showdown can stop at the end of a race with WinSock error
  10038 while their UDP output is on (a known game bug; the community
  workaround by RoccoC/DiRTTelemetryErrorFix intercepts that error).
  Automatic now leaves those two off and puts back one it had switched on;
  their switch says why, and turning it on by hand is remembered.
- A switch locked while its game runs keeps its on colours instead of
  looking off.
- The Circuit dash hides the fuel and tyre cards when the game sends
  neither (DiRT Showdown).
2026-10-31 20:26:16 +00:00
The412Banner 5be04466af feat(dual-screen): In-game stats strips and dashes with the DroidDeck logo
The In-game stats page gets a top strip and a racing dash the user picks
separately; both are remembered and cleared by Reset settings.

Top strip, in FusionHUD's metric colors: Panel (an outlined panel with the
DroidDeck badge beside the FPS, frame time, a frame-time graph, CPU, GPU,
RAM and battery rows), Tiles (four tiles with a 30-second line) and Rings.
Tiles and Rings carry the DroidDeck mark, wordmark and clock above them.

Dash: Speedometer (speed dial with the rev band, gear, pedals, G-force and
steering), Circuit (shift lights, gear, timing with best lap, fuel, tire
temperatures), Trace (10 s of throttle and brake, speed below), Dials
(speed and rev dials, OutGauge dashboard lights, turbo and temperatures)
and Glance; Auto picks Speedometer for Codemasters, Circuit for Forza and
Dials for OutGauge. War Thunder gets a Flight layout (IAS and altitude
tapes, throttle, G, fuel) and Elite Dangerous a Ship layout (pips, fuel,
cargo, legal state, credits). Every readout card shows the DroidDeck mark
in its title, drawn with the HUD's own DroidDeckMark.

Tapping the strip or the dash moves to the next style; a Layout row at the
bottom of the page picks either directly.

Telemetry now also reads Codemasters steering and G-force (DiRT Showdown's
38 floats carry them), Forza best lap, steering, G-force and tire
temperatures (read as Fahrenheit, as community parsers do; unit not checked
on a device), and OutGauge turbo, engine and oil temperature and dashboard
lights. War Thunder keeps every number so the Flight layout finds fuel and
throttle; its list still shows the first 12.
2026-10-31 19:49:47 +00:00
The412Banner 63ad5a722f feat(dual-screen): Send dashboard data Automatic, on by default
Automatic keeps the data output on for every game the In-game stats page
finds. The session applies it whenever the focused game changes (session
start, a game starting, a game closing) on devices with a second screen,
skipping the running game. Games the user switches off by hand stay off;
switching Automatic off puts every game DroidDeck changed back to its own
setting. Both settings are cleared by Reset settings.
2026-10-31 19:49:47 +00:00
The412Banner f896d7fa75 feat(dual-screen): Send dashboard data switch on the In-game stats page
Codemasters games keep their UDP/motion output in
My Games/<game>/hardwaresettings/hardware_settings_config.xml inside the
game's Proton prefix. The page finds those files in every library's
compatdata and offers a switch per game: on points the udp (or motion) line
at 127.0.0.1:20777 with extradata 3 and keeps the file as it was beside it;
off puts that line back. Only that line changes, the file is replaced in one
rename, and a game's switch is locked while that game runs. Installed games
whose output is a menu setting only (Forza, BeamNG.drive) get a line with
what to turn on. Library.compatdataDirs shares protonPrefix's library roots.
2026-10-31 19:49:46 +00:00
The412Banner 995cbc411c fix(dual-screen): show the online friends above Steam chat's group chat list
Steam gives its group chat list a fixed 114 px height plus an empty-list
note, which covered the online friends in the bottom-screen chat. The list
now shrinks to its rows (at most a quarter of the panel) and the note is
hidden; the GROUP CHATS bar and its + button stay.
2026-10-31 19:49:46 +00:00
The412Banner 5045002de1 feat(dual-screen): Dashboard opens on Chat; a game start shows In-game stats
With no tab picked yet the Dashboard opens on Chat; the last tab the user
tapped still opens next time. When a game starts while the Dashboard is
showing it switches to In-game stats. That switch is not saved, so the
user's own pick is kept.
2026-10-31 19:49:45 +00:00
The412Banner e75505c019 feat(dual-screen): open the Dashboard on the bottom screen by default
When nothing has been picked in the menu yet, the bottom screen opens on
the Dashboard on every dual-screen device. A mode the user picked is still
remembered and opens as before; a pick that can't open right now (deck
controls without the deck pad, Dashboard without pages) keeps the old
fallback.
2026-10-31 19:49:45 +00:00
The412Banner 264c0fc0f6 fix(dual-screen): one-line hint on the In-game stats page
The user found the per-game port list too long. The page shows the hint only
while no game sends data; setup details belong in the docs.
2026-10-31 19:49:44 +00:00
The412Banner 0f93fd75c4 fix(dual-screen): call the race dash tab In-game stats
The user found "Telemetry" sounded like DroidDeck collects data. The help
text now says the numbers come from the game's own output setting and stay
on the device (the page only listens on 127.0.0.1 and reads local files).
2026-10-31 19:49:43 +00:00
The412Banner 4deff589e5 fix(dual-screen): give the Steam chat WebView a real height; open chat with its tab
Probe from build 6 (now reverted): <html> itself was 0 px tall even with
height:100%!important, i.e. the page had a 0 px tall viewport. Compose's
AndroidView gives the WebView WRAP_CONTENT layout params, which make WebView
lay pages out at zero height, so the WebView is now MATCH_PARENT and the
height rules from 5468ae37 are dropped (Steam's own full-height layout should
then apply; not device-tested yet).

The chat now opens as soon as its tab is shown (user request), and after
Android ends its renderer in picture-in-picture it reopens on resume.
2026-10-31 19:49:43 +00:00
The412Banner 97853d0fde Revert "test(dual-screen): record the Steam chat element tree to events.jsonl"
This reverts commit cd452edca8.
2026-10-31 19:49:42 +00:00
The412Banner 2d5061c986 test(dual-screen): record the Steam chat element tree to events.jsonl
Test-only probe (sizes, flex settings, inline heights under .chat_main; no
text) to measure what still limits the friends column. Revert before merge.
2026-10-31 19:49:42 +00:00
The412Banner 6dab2cef17 fix(dual-screen): fill Steam chat's friends column; close the chat when its renderer ends
Build 5 hid the header but the friends column stayed short, so the full-height
rule now also covers .chat_main_flex, .friendsListContainer and .friendlist.

On the Retroid Pocket Duo Android ends the WebView renderer about a second after
DroidDeck goes to picture-in-picture (am_kill 'isolated not needed', seen twice);
the page left on the bottom screen was dead. Handle onRenderProcessGone by closing
the chat with a note to open it again.
2026-10-31 19:49:42 +00:00
The412Banner 3a4866e2ea fix(dual-screen): give Steam chat its full height and hide its site header
Measured on the Retroid Pocket Duo (layout probe, now removed): in the
WebView body, #friendslist-container and .chat_main came out 0 px tall,
which folded the friends list, and the site header is the element before
.chat_main_flex (its class name is generated, #global_header is not on
this page). Removes the test-only probe from 083bdc05/ac08f48b.
2026-10-31 19:49:42 +00:00
The412Banner 499b06ff2c test(dual-screen): write the chat layout probe to events.jsonl
The Retroid Pocket Duo's logcat keeps only error-level app lines, so the
Log.i probe from 083bdc05 never showed up. Test-only; remove with the fix.
2026-10-31 19:49:42 +00:00
The412Banner abca04336a test(dual-screen): log the Steam chat page's layout structure
Temporary, for the next device test only: 4 s and 12 s after the chat page
loads, log the element chain at the top, at the friends list and at the
bottom of the page, plus the body's children (tag, id, classes, position,
height; no text, long digit runs masked). Steam's header is not
#global_header there and the friends list stops short of the bottom, so
the real elements are needed before fixing it. To be removed with that fix.
2026-10-31 19:49:42 +00:00
The412Banner 5eaa6a76cc fix(dual-screen): listen for game telemetry on 127.0.0.1, not ::1
Android's InetAddress.getLoopbackAddress() always returns the IPv6
loopback (libcore InetAddress.java, "Android-changed"), so the listeners
were bound to [::1] and never saw the games' IPv4 packets to 127.0.0.1.
A listener bound to 127.0.0.1:20777 on the same Duo received DiRT
Showdown's packets.
2026-10-31 19:49:41 +00:00
The412Banner 42df3a78b3 fix(dual-screen): give the bottom-screen Steam chat room to lay out
At the panel's own scale Steam's desktop chat got about 600x300 CSS
pixels and its friends list collapsed under the group chats bar. The page
is now laid out wider and drawn at 0.75 of the panel's scale, Steam's site
header is hidden, and while the chat is open Close, mic and volume share
one row so the chat gets the rest of the screen.
2026-10-31 19:49:41 +00:00
The412Banner 30e009a651 fix(dual-screen): read DiRT Showdown's shorter telemetry packet
DiRT Showdown sends 152-byte packets (38 floats) on port 20777 even with
extradata 3; the page only accepted 256 bytes and stayed empty. The first
38 floats carry speed, rpm, gear, pedals, lap and lap time in the same
places, so they are read now and the rest (lap count, position, fuel, max
rpm) stays empty for these games. The page also says when a port gets
packets it cannot read, with their count and size.
2026-10-31 19:49:41 +00:00
The412Banner 9e28a11270 feat(dual-screen): bottom-screen Steam chat uses the Steam client's sign-in
Open Steam Chat copies the web sign-in Steam's built-in browser already
holds (its Chromium cookie store under config/htmlcache, "v10" values) for
steamcommunity.com and steam-chat.com into the chat page before it loads,
so no second login is needed. Values are never logged; the copy of the
store is deleted right after reading. With no Steam web sign-in yet, the
page shows Steam's sign-in as before.
2026-10-31 19:49:41 +00:00
The412Banner ed3cfaf9c6 fix(dual-screen): notification access page was hidden under the dashboard
Android opens the settings page on the bottom screen, under the dashboard
window, so the button seemed to do nothing. Open DroidDeck's own switch
there (Android 11+), hide the dashboard, and bring it back once access is
on (or when Dashboard is chosen again). The Chat page now says how to turn
the microphone on when the session has none.
2026-10-31 19:49:41 +00:00
The412Banner 082ea000dc fix(dual-screen): avoid name clashes in the bottom-screen pages; stop a telemetry listener on socket errors 2026-10-31 19:49:41 +00:00
The412Banner a251e8cc23 fix(dual-screen): close the screenshot folder comment 2026-10-31 19:49:41 +00:00
The412Banner 60184418ba feat(dual-screen): Telemetry page on the bottom screen
DroidDeck's own numbers (FPS while the HUD runs, CPU, GPU, battery, from
the HUD's sources) plus a live dash for racing games that send UDP
telemetry to 127.0.0.1: Codemasters "extradata 3" (DiRT Rally, DiRT 4,
GRID) on 20777, Forza Data Out (Motorsport 7/2023, Horizon 4/5) on 5300,
OutGauge (BeamNG.drive, Live for Speed) on 4444. War Thunder's local
state page and Elite Dangerous' Status.json show without setup. The
listeners and readers run only while the page is shown.
2026-10-31 19:49:41 +00:00
The412Banner 125e39ea9c feat(dual-screen): Chat & voice page on the bottom screen
Mic on/off for the session and game volume buttons (no Android volume
panel over the game), plus Steam's web chat, loaded only when opened and
kept to Steam's own sites. Keyboard keys typed on the dashboard stay on
the bottom screen; controller buttons still go to the game.
2026-10-31 19:49:40 +00:00
The412Banner ee8911a382 feat(dual-screen): Screenshots page on the bottom screen
A Take screenshot button copies the game frame (without the overlay) and
saves it to Pictures/DroidDeck. The gallery shows those plus the
screenshots Steam keeps under userdata; tap one to see it full size.
2026-10-31 19:49:40 +00:00
The412Banner 3be85906e9 feat(dual-screen): Downloads and Notifications pages on the bottom screen
Downloads: Steam downloads and updates (read from Steam's appmanifests,
including SD-card libraries), shader-cache downloads from the content log,
and DroidDeck store downloads, with progress and speed.

Notifications: other apps' notifications, after the user allows
notification access once. Kept in memory only, never saved or logged;
ongoing, summary and empty ones are skipped.
2026-10-31 19:49:40 +00:00
The412Banner e76592ba4e feat(dual-screen): Dashboard mode for the bottom screen
A new bottom-screen mode that holds pages (downloads, screenshots,
telemetry and more come in the next commits). It sizes itself from the
bottom display it is shown on, is offered only while it has pages, and
follows the existing Dual screen Auto/On/Off setting and display pick.
The last page is remembered.
2026-10-31 19:49:40 +00:00
14 changed files with 48 additions and 837 deletions

No files matched your search

-10
View File
@@ -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 {
@@ -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()
}
@@ -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
@@ -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)
}
}
@@ -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)))
}
@@ -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"
@@ -831,9 +813,8 @@ 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."""
That is the prefix's own one, unless 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 the running Proton's ws2_32.dll goes back instead."""
target = prefix_ws2(prefix)
saved = target.with_name(target.name + DIRT_SAVED)
own = proton_ws2(proton)
@@ -842,7 +823,7 @@ def restore_dirt_ws2(prefix, proton):
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 not own.is_file() or os.path.realpath(saved) == os.path.realpath(own):
os.replace(saved, target)
return True
os.unlink(saved)
@@ -856,55 +837,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 +844,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 +856,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 +937,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 +954,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 +971,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__":
-199
View File
@@ -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()
-157
View File
@@ -159,22 +159,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 +171,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 +181,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 +736,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})