Compare commits

..
Author SHA1 Message Date
The412Banner 046f97bcdb fix(remote-play): decode into ION buffers on kernels without DMA heaps
Kernels that predate DMA heaps (4.19 and many 5.4 vendor kernels) only
have /dev/ion, so the Remote Play decoder turned itself off and Steam's
streaming client reported "Unsupported codec". The decoder now falls back
to /dev/ion and picks the ION ABI the same way Turnip's KGSL backend does.
ION fallback proposed and tested on hardware by iacob-mihail in #2102.
2026-11-25 21:20:01 +00:00
62 changed files with 276 additions and 1355 deletions

No files matched your search

@@ -620,8 +620,7 @@ static void cursor_publish_shown(void) {
static void cursor_publish_hidden(void) {
pthread_mutex_lock(&g_cursor_lock);
// A client that hides the cursor before ever showing one (gamescope drawing its own) must still be reported.
if (!g_cursor_hidden || g_cursor_serial == 0) { g_cursor_hidden = 1; g_cursor_serial++; }
if (!g_cursor_hidden) { g_cursor_hidden = 1; g_cursor_serial++; }
pthread_mutex_unlock(&g_cursor_lock);
}
@@ -169,7 +169,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
private var battleNetInstalled by mutableStateOf(false)
private var offlineAccount by mutableStateOf<String?>(null)
private var offline by mutableStateOf(false)
private var offlineAuto by mutableStateOf(true)
private var showPerformance by mutableStateOf(false)
private var clientOverride by mutableStateOf(false)
private var clientCores by mutableStateOf<Set<Int>>(emptySet())
@@ -1417,7 +1416,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
gameSyncFolder = gameSyncFolder,
busy = busy, stage = stage, percent = percent,
desktopInstalled = desktopInstalled, desktopPresent = desktopPresent,
offlineAccount = offlineAccount, offline = offline, offlineAuto = offlineAuto,
offlineAccount = offlineAccount, offline = offline,
frameGenLabel = frameGenLabel, romsDir = romsDir, logsEnabled = logsEnabled,
enhancedDiagnosticsArmed = enhancedDiagnosticsArmed,
gameDebugLogsEnabled = gameDebugLogsEnabled, gameDebugLogsNeedsRestart = gameDebugLogsNeedsRestart,
@@ -1755,11 +1754,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
OfflineMode.setEnabled(this, !OfflineMode.enabled(this))
offline = OfflineMode.enabled(this)
},
onOfflineAuto = {
OfflineMode.setAuto(this, !OfflineMode.auto(this))
offlineAuto = OfflineMode.auto(this)
offline = OfflineMode.enabled(this)
},
onPageBack = { showPerformance = false; showComponents = false; showMapping = false },
onSoundtracksIngame = { on ->
SessionPrefs.setSoundtracksIngame(this, on)
@@ -3325,7 +3319,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
battleNetInstalled = com.droiddeck.launcher.runtime.BattleNet.installed(this)
offlineAccount = OfflineMode.account(this)
offline = OfflineMode.enabled(this)
offlineAuto = OfflineMode.auto(this)
installed = LinuxRuntimeInstaller.installedVersion(this)
ready = LinuxRuntime.isInstalled(this)
vkBridge = SessionPrefs.vkBridge(this)
@@ -3414,7 +3414,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
if (status == 0) SessionState.takeRelaunch()?.let { next ->
next.putExtra(EXTRA_RETURN_HOME, intent.getBooleanExtra(EXTRA_RETURN_HOME, false))
next.putExtra(EXTRA_LINK_TASK, intent.getIntExtra(EXTRA_LINK_TASK, -1))
relaunch(next)
setIntent(next)
recreate()
return@runOnUiThread
}
showEnded(status, hint)
@@ -3422,16 +3423,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}, "session-end-hint").start()
}
// recreate() keeps this window, and Compose content added to it afterwards never recomposes, so the
// loading screen of the next session stays up over a running session. A new instance gets its own window.
// This instance finishes first because the activity is singleTask and would otherwise take the intent itself.
private fun relaunch(next: Intent) {
closeAtOnce = true
super.finish()
startActivity(next)
overridePendingTransition(0, 0)
}
private fun showEnded(status: Int, hint: EndHint?) {
if (status == 0 && hint?.evenOnSuccess != true) {
finish()
@@ -6059,7 +6050,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
Log.w(TAG, "ignoring agent start while session phase is ${SessionState.phase}")
return
}
relaunch(android.content.Intent(intent).setClass(this, SessionActivity::class.java))
setIntent(intent)
recreate()
return
}
if (this.intent.getBooleanExtra(EXTRA_RETURN_HOME, false)) intent.putExtra(EXTRA_RETURN_HOME, true)
@@ -33,13 +33,6 @@ object SocNames {
fun name(model: String, platform: String = GpuInfo.systemProperty("ro.board.platform")): String? =
MODELS[normalizedModel(model)] ?: PLATFORMS[platform.lowercase()]?.let { "$it family" }
// Without label's platform-family guess: a rebadged chip such as the Duo's CQ7790S reports a platform it is not.
fun plainName(model: String = model(), maker: String = manufacturer()): String =
MODELS[normalizedModel(model)]?.let { "$it ($model)" } ?: "$maker $model".trim()
private fun manufacturer(): String =
if (Build.VERSION.SDK_INT >= 31) Build.SOC_MANUFACTURER.takeIf { it != Build.UNKNOWN }.orEmpty() else ""
fun label(model: String = model(), platform: String = GpuInfo.systemProperty("ro.board.platform")): String {
val name = name(model, platform)
return when {
@@ -2,20 +2,16 @@ package com.droiddeck.launcher.session
import android.content.Context
import android.util.Log
import com.droiddeck.launcher.agent.AgentGuest
import com.droiddeck.launcher.runtime.LinuxRuntime
import java.io.File
object OfflineMode {
private const val TAG = "OfflineMode"
private const val KEY = "steam_offline"
private const val AUTO_KEY = "steam_offline_auto"
private const val NETWORK_KEY = "steam_offline_by_network"
private val WANTS = Regex("""^(\s*"WantsOfflineMode"\s*")([01])(".*)$""")
private val SKIP = Regex("""^(\s*"SkipOfflineModeWarning"\s*")([01])(".*)$""")
private val REMEMBER = Regex(""""RememberPassword"\s*"1"""")
private val PERSONA = Regex(""""PersonaName"\s*"([^"]*)"""")
private const val EVAL_TIMEOUT_MS = 10_000L
private fun prefs(context: Context) = context.getSharedPreferences("session", Context.MODE_PRIVATE)
@@ -23,12 +19,10 @@ object OfflineMode {
private fun x64LoginUsers(root: File) = File(root, "root/.droiddeck-x64/.local/share/Steam/config/loginusers.vdf")
private fun activeLoginUsers(context: Context, root: File) =
x64LoginUsers(root).takeIf { SessionPrefs.activeSteamClientArch(context) == "x86_64" && it.isFile }
?: loginUsers(root)
fun account(context: Context): String? {
val file = activeLoginUsers(context, LinuxRuntime.rootDir(context))
val root = LinuxRuntime.rootDir(context)
val file = x64LoginUsers(root).takeIf { SessionPrefs.activeSteamClientArch(context) == "x86_64" && it.isFile }
?: loginUsers(root)
val text = try {
if (file.isFile) file.readText() else return null
} catch (e: Exception) {
@@ -38,114 +32,21 @@ object OfflineMode {
return PERSONA.find(text)?.groupValues?.get(1)?.takeIf { it.isNotBlank() }.orEmpty()
}
private fun steamWants(context: Context, root: File): Boolean? {
val file = activeLoginUsers(context, root)
val lines = try {
if (file.isFile) file.readLines() else return null
} catch (e: Exception) {
Log.w(TAG, "could not read loginusers.vdf", e); return null
}
val values = lines.mapNotNull { WANTS.matchEntire(it)?.groupValues?.get(2) }
return if (values.isEmpty()) null else "1" in values
}
fun enabled(context: Context): Boolean = prefs(context).getBoolean(KEY, false)
internal fun manual(steamWants: Boolean?, automatic: Boolean, saved: Boolean): Boolean =
if (steamWants == null) saved else steamWants && !automatic
internal fun offline(manual: Boolean, online: Boolean, auto: Boolean = true): Boolean = manual || (auto && !online)
internal fun afterNetworkChange(manual: Boolean, online: Boolean): Boolean = manual && !online
fun auto(context: Context): Boolean = prefs(context).getBoolean(AUTO_KEY, true)
fun enabled(context: Context): Boolean = saved(context, LinuxRuntime.rootDir(context))
fun active(context: Context): Boolean =
offline(enabled(context), isOnline(context), auto(context))
@Synchronized
fun setEnabled(context: Context, on: Boolean) {
write(context, LinuxRuntime.rootDir(context), on)
SteamOfflineFollow.request()
prefs(context).edit().putBoolean(KEY, on).apply()
apply(context, LinuxRuntime.rootDir(context))
}
@Synchronized
fun setAuto(context: Context, on: Boolean) {
val manual = if (on) false else steamWants(context, LinuxRuntime.rootDir(context)) ?: active(context)
prefs(context).edit().putBoolean(AUTO_KEY, on).commit()
setEnabled(context, manual)
fun apply(context: Context, root: File) {
applyTo(context, loginUsers(root))
applyTo(context, x64LoginUsers(root))
}
fun apply(context: Context, root: File): Boolean = write(context, root, saved(context, root))
fun sync(context: Context): Boolean? {
val root = LinuxRuntime.rootDir(context)
val offline = synchronized(this) { write(context, root, saved(context, root)) }
return switchLive(context, offline)
}
fun follow(context: Context): Boolean? {
val root = LinuxRuntime.rootDir(context)
val (byNetwork, offline) = synchronized(this) {
if (!auto(context)) return false
prefs(context).getBoolean(NETWORK_KEY, false) to
write(context, root, afterNetworkChange(saved(context, root), isOnline(context)))
}
val result = switchLive(context, offline)
if (result == null && !offline && byNetwork) restoreNetworkOffline(context)
return result
}
@Synchronized
internal fun restoreNetworkOffline(context: Context) {
val prefs = prefs(context)
if (!auto(context) || prefs.getBoolean(KEY, false) || prefs.getBoolean(NETWORK_KEY, false)) return
prefs.edit().putBoolean(NETWORK_KEY, true).apply()
}
private fun isOnline(context: Context) = com.droiddeck.launcher.frontend.AutoComponents.isOnline(context)
private fun saved(context: Context, root: File): Boolean {
val prefs = prefs(context)
return manual(steamWants(context, root), prefs.getBoolean(NETWORK_KEY, false), prefs.getBoolean(KEY, false))
}
@Synchronized
private fun remember(context: Context, manual: Boolean): Boolean {
val online = isOnline(context)
val auto = auto(context)
val offline = offline(manual, online, auto)
prefs(context).edit().putBoolean(KEY, manual).putBoolean(NETWORK_KEY, offline && !manual).apply()
Log.i(TAG, "auto=$auto manual=$manual online=$online offline=$offline")
return offline
}
private fun switchLive(context: Context, offline: Boolean): Boolean? {
val answer = try {
AgentGuest.steamEval(context, "$SWITCH($offline)", EVAL_TIMEOUT_MS)
} catch (e: Exception) {
Log.w(TAG, "steam not reachable: ${e.javaClass.simpleName}: ${e.message}")
return null
}
val result = if (answer.optBoolean("ok")) answer.optString("value") else answer.optJSONObject("error")?.optString("message")
Log.i(TAG, "live offline=$offline: $result")
return when (result) {
"switched" -> true
"same" -> false
else -> null
}
}
private fun write(context: Context, root: File, manual: Boolean): Boolean {
val offline = remember(context, manual)
applyTo(loginUsers(root), offline)
applyTo(x64LoginUsers(root), offline)
return offline
}
private fun applyTo(file: File, offline: Boolean) {
private fun applyTo(context: Context, file: File) {
if (!file.isFile) return
val want = if (offline) "1" else "0"
val want = if (enabled(context)) "1" else "0"
try {
val lines = file.readLines()
val out = ArrayList<String>(lines.size + 4)
@@ -193,25 +94,4 @@ object OfflineMode {
Log.w(TAG, "could not write loginusers.vdf", e)
}
}
private val SWITCH = """(async want => {
const user = globalThis.SteamClient?.User;
if (typeof user?.GoOffline !== 'function' || typeof user?.GoOnline !== 'function') return "missing";
const seen = globalThis.__droiddeckSteamOffline ??= { value: null };
seen.want = want;
if (!seen.registered) {
seen.registered = true;
user.RegisterForCurrentUserChanges(u => { seen.value = !!u?.bIsOfflineMode; });
globalThis.SteamClient.GameSessions?.RegisterForAppLifetimeNotifications?.(n => {
if (n?.bRunning) return;
setTimeout(() => { if (seen.want === true && seen.value === false) user.GoOffline(); }, 2000);
});
}
for (let waited = 0; seen.value === null && waited < 4000; waited += 100) await new Promise(done => setTimeout(done, 100));
const current = seen.value;
if (current === null) return "unknown";
if (current === want) return "same";
if (want) user.GoOffline(); else user.GoOnline();
return "switched";
})"""
}
@@ -28,14 +28,12 @@ object SessionFiles {
"usr/local/bin/droiddeck-bottom-desktop" to "usr/local/bin/droiddeck-bottom-desktop",
"usr/local/bin/droiddeck-gpu" to "usr/local/bin/droiddeck-gpu",
"usr/local/bin/droiddeck-desktop-gpu" to "usr/local/bin/droiddeck-desktop-gpu",
"usr/local/bin/droiddeck-device-info" to "usr/local/bin/droiddeck-device-info",
"usr/local/bin/droiddeck-desktop-window-rules" to "usr/local/bin/droiddeck-desktop-window-rules",
"usr/local/bin/droiddeck-library-perms" to "usr/local/bin/droiddeck-library-perms",
"usr/local/bin/droiddeck-ime" to "usr/local/bin/droiddeck-ime",
"usr/local/bin/kwin_wayland_wrapper" to "usr/local/bin/kwin_wayland_wrapper",
"usr/lib/firefox/defaults/pref/droiddeck.js" to "usr/lib/firefox/defaults/pref/droiddeck.js",
"etc/xdg/autostart/droiddeck-clipboard.desktop" to "etc/xdg/autostart/droiddeck-clipboard.desktop",
"etc/xdg/fastfetch/config.jsonc" to "etc/xdg/fastfetch/config.jsonc",
)
private val SERVICE_PACKS = mapOf(
@@ -669,8 +669,6 @@ class SessionService : Service() {
guest.add("DROIDDECK_WSI_BYPASS_CHECK_MS=100")
guest.add("WINE_OFFSCREEN_CHECK_MS=100")
guest.add("DD_REFRESH=" + Math.round(SessionState.refreshHz))
guest.add("DD_DEVICE_NAME=" + android.os.Build.MODEL)
com.droiddeck.launcher.gpu.SocNames.plainName().takeIf { it.isNotEmpty() }?.let { guest.add("DD_SOC_NAME=$it") }
guest.add("DD_LOG=" + sessionLog.path)
guest.add("DD_DEBUG_DIR=" + sessionDir.path)
if (EnhancedDiagnostics.isActive(this, sessionDir)) guest.add("DROIDDECK_ENHANCED_DIAGNOSTICS=1")
@@ -696,7 +694,7 @@ class SessionService : Service() {
val added = SessionEvents.step("added-games-scan") { com.droiddeck.launcher.frontend.AddedGames.scan(this) }
val listing = SessionEvents.step("added-games-listing") { com.droiddeck.launcher.frontend.AddedGames.writeListing(this, added) }
guest.add("DD_ADDED_GAMES=" + listing.path)
if (OfflineMode.active(this)) guest.add("DD_STEAM_OFFLINE=1")
if (OfflineMode.enabled(this)) guest.add("DD_STEAM_OFFLINE=1")
if (com.droiddeck.launcher.gpu.Lossless.owned(this)) guest.add("DD_LOSSLESS_OWNED=1")
if (added.isNotEmpty()) Log.i(TAG, "added games: " + added.joinToString { "${it.name} (${it.exe.name})" })
}
@@ -815,11 +813,6 @@ class SessionService : Service() {
.onFailure { Log.w(TAG, "desktop language pack: $it") }
}
if (SessionState.mode == MODE_STEAM || SessionState.mode == MODE_DESKTOP) {
val steamOffline = SteamOfflineFollow()
steamOffline.attach(this)
components.add(steamOffline)
}
val networkLink = LinuxNetworkLinkComponent(this, root)
networkLink.attach(this)
networkLink.publish()
@@ -25,7 +25,7 @@ object SettingsReset {
"noXalia", "fastSync", "fsyncFirst", "syncFallback", "prootNoSeccomp", "prootFastPath", "nativeUserland", "cursorComposite",
"guestHostname", "fexPreset", "forceSsbs", "logs", "gameDebugLogsEnabled", "enhancedDiagnosticsNext", "storageDiagnostics", "buildWatermark",
"upscaler", "upscaleSharpness", "screenEffects", "blackFrameInsertion", "textureAnisotropy", "textureLodBias",
"steamDownloadsInBackground", "steam_offline", "steam_offline_auto", "steam_offline_by_network", "bootMovie", "bootMovieSound", "bootMovieVolume", "bootMovieSeconds", "skipBootMovie",
"steamDownloadsInBackground", "steam_offline", "bootMovie", "bootMovieSound", "bootMovieVolume", "bootMovieSeconds", "skipBootMovie",
"bootMovieApplyNext", "bootMovieSteamSeen", "bootMovieShuffle",
"questDefaultsV1", "telemetryAuto", "telemetryOff", "statsStrip", "statsHud", "bottomHud", "bottomStripMetrics", "bottomStripTabs", "statsDash", "statsSpeedUnit",
)
@@ -67,7 +67,7 @@ object SettingsReset {
}
QuestExperimental.initialize(context)
runCatching { OfflineMode.setEnabled(context, false) }
runCatching { OfflineMode.apply(context, LinuxRuntime.rootDir(context)) }
.onFailure { ok = false; Log.w(TAG, "Could not turn offline mode off", it) }
runCatching { GameEnvironmentStore.publish(context) }
.onFailure { ok = false; Log.w(TAG, "Could not update game environment", it) }
@@ -1,104 +0,0 @@
package com.droiddeck.launcher.session
import android.net.ConnectivityManager
import android.net.Network
import android.net.NetworkCapabilities
import android.os.Handler
import android.os.HandlerThread
import android.util.Log
import com.droiddeck.launcher.core.SessionPart
import com.droiddeck.launcher.frontend.AutoComponents
class SteamOfflineFollow : SessionPart() {
private var thread: HandlerThread? = null
@Volatile private var handler: Handler? = null
private var callback: ConnectivityManager.NetworkCallback? = null
private var online: Boolean? = null
private var retries = 0
private var requested = false
private val check = object : Runnable {
override fun run() {
val handler = handler ?: return
if (SessionState.running && SessionState.suspended) {
handler.postDelayed(this, SUSPENDED_POLL_MS)
return
}
val result = if (requested) OfflineMode.sync(app()) else OfflineMode.follow(app())
if (result != null) requested = false
if (result == null && retries < MAX_RETRIES) {
retries++
handler.postDelayed(this, RETRY_MS)
}
}
}
override fun start() {
val started = HandlerThread("steam-offline").also { it.start() }
val handler = Handler(started.looper)
thread = started
this.handler = handler
val registered = object : ConnectivityManager.NetworkCallback() {
override fun onCapabilitiesChanged(network: Network, capabilities: NetworkCapabilities) =
changed(capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) &&
capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED))
override fun onLost(network: Network) = changed(false)
}
callback = registered
active = this
online = AutoComponents.isOnline(app())
app().getSystemService(ConnectivityManager::class.java).registerDefaultNetworkCallback(registered, handler)
sync()
}
private fun changed(now: Boolean) {
val handler = handler ?: return
if (now == online) return
online = now
handler.removeCallbacks(check)
retries = 0
if (OfflineMode.auto(app())) requested = false
handler.postDelayed(check, if (now) ONLINE_DELAY_MS else OFFLINE_DELAY_MS)
}
private fun sync() {
handler?.post {
val handler = handler ?: return@post
handler.removeCallbacks(check)
retries = 0
requested = true
handler.post(check)
}
}
override fun stop() {
if (active === this) active = null
val registered = callback
callback = null
if (registered != null) {
try {
app().getSystemService(ConnectivityManager::class.java).unregisterNetworkCallback(registered)
} catch (e: IllegalArgumentException) {
Log.w(TAG, "network callback was already gone", e)
}
}
handler?.removeCallbacksAndMessages(null)
handler = null
thread?.quitSafely()
thread = null
}
companion object {
private const val TAG = "SteamOfflineFollow"
@Volatile private var active: SteamOfflineFollow? = null
const val ONLINE_DELAY_MS = 2_000L
const val OFFLINE_DELAY_MS = 10_000L
const val RETRY_MS = 15_000L
const val MAX_RETRIES = 8
const val SUSPENDED_POLL_MS = 1_000L
fun request() {
active?.sync()
}
}
}
@@ -24,7 +24,6 @@ object StoreLaunch {
"9d2d0eb64d5c44529cece33fe2a46482", "8769e24080ea413b8ebca3f1b8c50951", "Heather",
"c180bd9859624278aa20f1333918498a", "0828ecd4297c4f89bfcc45420e695b67",
"e5f031908d2e460b8757387d1a136e48", "afd9f29c1af44610b9e0f9b69742e257",
"7133a8c315324112a3eee2458f0a8242",
)
const val EA_ENV = ".droiddeck-ea-env"
/** A sleeping stand-in that the launch hook installs; older EA SDKs require a running Origin process. */
@@ -103,7 +103,6 @@ class FrontEndState(
val desktopPresent: Boolean = desktopInstalled,
val offlineAccount: String?,
val offline: Boolean,
val offlineAuto: Boolean = true,
val frameGenLabel: String,
val romsDir: String?,
val logsEnabled: Boolean,
@@ -274,7 +273,6 @@ class FrontEndActions(
val onClearLogs: () -> Unit = {},
val onResetSettings: () -> Unit = {},
val onOffline: () -> Unit,
val onOfflineAuto: () -> Unit = {},
val onPageBack: () -> Unit = {},
val onTheme: (String) -> Unit = {},
val onLanguage: (String) -> Unit = {},
@@ -115,11 +115,10 @@ internal fun SteamHome(s: FrontEndState, a: FrontEndActions, modifier: Modifier)
account = { host ->
SettingsGroup(stringResource(R.string.setup_account)) {
ToggleRow(
host, "offline-auto", stringResource(R.string.setup_offline_auto),
host, "offline", stringResource(R.string.setup_offline),
s.offlineAccount?.let { if (it.isEmpty()) stringResource(R.string.setup_signed_in_unnamed) else stringResource(R.string.setup_signed_in, it) } ?: stringResource(R.string.setup_sign_in_first),
s.offlineAuto, enabled = s.offlineAccount != null,
) { a.onOfflineAuto() }
if (!s.offlineAuto) ToggleRow(host, "offline", stringResource(R.string.setup_offline), null, s.offline, enabled = s.offlineAccount != null) { a.onOffline() }
s.offline, enabled = s.offlineAccount != null,
) { a.onOffline() }
}
},
)
-1
View File
@@ -934,7 +934,6 @@
<string name="setup_reset_settings_session_running">أوقف الجلسة قبل إعادة تعيين الإعدادات.</string>
<string name="setup_reset_settings_partial">أُعيد تعيين الإعدادات، لكن ليس كلها. التفاصيل في السجلات.</string>
<string name="setup_offline">وضع عدم الاتصال</string>
<string name="setup_offline_auto">وضع عدم الاتصال التلقائي</string>
<string name="setup_sign_in_first">سجّل الدخول إلى Steam أولًا</string>
<string name="setup_launcher">المشغّل</string>
<string name="setup_language">اللغة</string>
@@ -952,7 +952,6 @@
<string name="setup_reset_settings_session_running">Detén la sesión antes de restablecer los ajustes.</string>
<string name="setup_reset_settings_partial">Los ajustes se restablecieron, pero algunas partes no se pudieron restablecer. Los registros tienen los detalles.</string>
<string name="setup_offline">Modo sin conexión</string>
<string name="setup_offline_auto">Modo sin conexión automático</string>
<string name="setup_sign_in_first">Inicia sesión en Steam primero</string>
<string name="setup_launcher">Launcher</string>
<string name="setup_language">Idioma</string>
-1
View File
@@ -922,7 +922,6 @@
<string name="setup_reset_settings_session_running">Спри сесията, преди да нулираш настройките.</string>
<string name="setup_reset_settings_partial">Настройките са нулирани, но не всички. Подробностите са в логовете.</string>
<string name="setup_offline">Офлайн режим</string>
<string name="setup_offline_auto">Автоматичен офлайн режим</string>
<string name="setup_sign_in_first">Първо влезте в Steam</string>
<string name="setup_launcher">Лаунчър</string>
<string name="setup_language">Език</string>
-1
View File
@@ -928,7 +928,6 @@
<string name="setup_reset_settings_session_running">Před obnovením nastavení zastav relaci.</string>
<string name="setup_reset_settings_partial">Nastavení byla obnovena, ale ne všechna. Podrobnosti jsou v logech.</string>
<string name="setup_offline">Režim offline</string>
<string name="setup_offline_auto">Automatický režim offline</string>
<string name="setup_sign_in_first">Nejprve se přihlaste ke Steamu</string>
<string name="setup_launcher">Spouštěč</string>
<string name="setup_language">Jazyk</string>
-1
View File
@@ -922,7 +922,6 @@
<string name="setup_reset_settings_session_running">Stop sessionen, før du nulstiller indstillinger.</string>
<string name="setup_reset_settings_partial">Indstillingerne blev nulstillet, men ikke alle. Detaljerne står i loggen.</string>
<string name="setup_offline">Offlinetilstand</string>
<string name="setup_offline_auto">Automatisk offlinetilstand</string>
<string name="setup_sign_in_first">Log ind på Steam først</string>
<string name="setup_launcher">Launcher</string>
<string name="setup_language">Sprog</string>
-1
View File
@@ -914,7 +914,6 @@
<string name="setup_log_export_failed">Sitzungsprotokolle konnten nicht gespeichert werden.</string>
<string name="setup_log_delete_failed">Sitzungsprotokolle konnten nicht gelöscht werden.</string>
<string name="setup_offline">Offlinemodus</string>
<string name="setup_offline_auto">Automatischer Offlinemodus</string>
<string name="setup_sign_in_first">Melde dich zuerst bei Steam an</string>
<string name="setup_launcher">Launcher</string>
<string name="setup_language">Sprache</string>
-1
View File
@@ -922,7 +922,6 @@
<string name="setup_reset_settings_session_running">Σταμάτησε τη συνεδρία πριν κάνεις επαναφορά ρυθμίσεων.</string>
<string name="setup_reset_settings_partial">Οι ρυθμίσεις επαναφέρθηκαν, αλλά όχι όλες. Οι λεπτομέρειες είναι στα αρχεία καταγραφής.</string>
<string name="setup_offline">Λειτουργία εκτός σύνδεσης</string>
<string name="setup_offline_auto">Αυτόματη λειτουργία εκτός σύνδεσης</string>
<string name="setup_sign_in_first">Συνδεθείτε πρώτα στο Steam</string>
<string name="setup_launcher">Εκκινητής</string>
<string name="setup_language">Γλώσσα</string>
-1
View File
@@ -925,7 +925,6 @@
<string name="setup_reset_settings_session_running">Detén la sesión antes de restablecer los ajustes.</string>
<string name="setup_reset_settings_partial">Los ajustes se restablecieron, pero algunas partes no se pudieron restablecer. Los registros tienen los detalles.</string>
<string name="setup_offline">Modo sin conexión</string>
<string name="setup_offline_auto">Modo sin conexión automático</string>
<string name="setup_sign_in_first">Inicia sesión en Steam primero</string>
<string name="setup_launcher">Launcher</string>
<string name="setup_language">Idioma</string>
-1
View File
@@ -922,7 +922,6 @@
<string name="setup_reset_settings_session_running">Pysäytä istunto ennen asetusten palauttamista.</string>
<string name="setup_reset_settings_partial">Asetukset palautettiin, mutta ei kaikkia. Tiedot ovat lokeissa.</string>
<string name="setup_offline">Offline-tila</string>
<string name="setup_offline_auto">Automaattinen offline-tila</string>
<string name="setup_sign_in_first">Kirjaudu Steamiin ensin</string>
<string name="setup_launcher">Käynnistin</string>
<string name="setup_language">Kieli</string>
-1
View File
@@ -925,7 +925,6 @@
<string name="setup_reset_settings_session_running">Arrêtez la session avant de réinitialiser les paramètres.</string>
<string name="setup_reset_settings_partial">Les paramètres ont été réinitialisés, mais certaines parties n\'ont pas pu l\'être. Les journaux contiennent les détails.</string>
<string name="setup_offline">Mode hors ligne</string>
<string name="setup_offline_auto">Mode hors ligne automatique</string>
<string name="setup_sign_in_first">Veuillez d\'abord vous connecter à Steam</string>
<string name="setup_launcher">Lanceur</string>
<string name="setup_language">Langue</string>
-1
View File
@@ -922,7 +922,6 @@
<string name="setup_reset_settings_session_running">सेटिंग रीसेट करने से पहले सेशन रोकें।</string>
<string name="setup_reset_settings_partial">सेटिंग रीसेट हुईं, पर सभी नहीं। विवरण लॉग में हैं।</string>
<string name="setup_offline">ऑफ़लाइन मोड</string>
<string name="setup_offline_auto">स्वचालित ऑफ़लाइन मोड</string>
<string name="setup_sign_in_first">पहले Steam में साइन इन करें</string>
<string name="setup_launcher">लॉन्चर</string>
<string name="setup_language">भाषा</string>
-1
View File
@@ -922,7 +922,6 @@
<string name="setup_reset_settings_session_running">A beállítások visszaállítása előtt állítsd le a munkamenetet.</string>
<string name="setup_reset_settings_partial">A beállítások visszaálltak, de nem mindegyik. A részletek a naplókban vannak.</string>
<string name="setup_offline">Offline mód</string>
<string name="setup_offline_auto">Automatikus offline mód</string>
<string name="setup_sign_in_first">Előbb jelentkezzen be a Steambe</string>
<string name="setup_launcher">Indítóalkalmazás</string>
<string name="setup_language">Nyelv</string>
-1
View File
@@ -919,7 +919,6 @@
<string name="setup_reset_settings_session_running">Hentikan sesi sebelum menyetel ulang setelan.</string>
<string name="setup_reset_settings_partial">Setelan disetel ulang, tetapi tidak semuanya. Rinciannya ada di log.</string>
<string name="setup_offline">Mode luring</string>
<string name="setup_offline_auto">Mode luring otomatis</string>
<string name="setup_sign_in_first">Masuk ke Steam terlebih dahulu</string>
<string name="setup_launcher">Peluncur</string>
<string name="setup_language">Bahasa</string>
-1
View File
@@ -917,7 +917,6 @@
<string name="setup_log_export_failed">Impossibile salvare i log di sessione.</string>
<string name="setup_log_delete_failed">Impossibile eliminare i log di sessione.</string>
<string name="setup_offline">Modalità offline</string>
<string name="setup_offline_auto">Modalità offline automatica</string>
<string name="setup_sign_in_first">Accedi prima a Steam</string>
<string name="setup_launcher">Launcher</string>
<string name="setup_language">Lingua</string>
-1
View File
@@ -919,7 +919,6 @@
<string name="setup_reset_settings_session_running">設定をリセットする前にセッションを停止してください。</string>
<string name="setup_reset_settings_partial">設定はリセットされましたが、一部をリセットできませんでした。詳細はログを確認してください。</string>
<string name="setup_offline">オフラインモード</string>
<string name="setup_offline_auto">自動オフラインモード</string>
<string name="setup_sign_in_first">先にSteamにログインしてください</string>
<string name="setup_launcher">ランチャー</string>
<string name="setup_language">言語</string>
-1
View File
@@ -919,7 +919,6 @@
<string name="setup_reset_settings_session_running">설정을 초기화하기 전에 세션을 중지하세요.</string>
<string name="setup_reset_settings_partial">설정이 초기화되었지만 일부는 초기화하지 못했습니다. 자세한 내용은 로그를 확인하세요.</string>
<string name="setup_offline">오프라인 모드</string>
<string name="setup_offline_auto">자동 오프라인 모드</string>
<string name="setup_sign_in_first">먼저 Steam에 로그인하세요</string>
<string name="setup_launcher">런처</string>
<string name="setup_language">언어</string>
-1
View File
@@ -919,7 +919,6 @@
<string name="setup_reset_settings_session_running">Hentikan sesi sebelum menetap semula tetapan.</string>
<string name="setup_reset_settings_partial">Tetapan telah ditetap semula, tetapi bukan semuanya. Butirannya ada dalam log.</string>
<string name="setup_offline">Mod luar talian</string>
<string name="setup_offline_auto">Mod luar talian automatik</string>
<string name="setup_sign_in_first">Log masuk ke Steam dahulu</string>
<string name="setup_launcher">Pelancar</string>
<string name="setup_language">Bahasa</string>
-1
View File
@@ -922,7 +922,6 @@
<string name="setup_reset_settings_session_running">Stopp økten før du tilbakestiller innstillinger.</string>
<string name="setup_reset_settings_partial">Innstillingene ble tilbakestilt, men ikke alle. Detaljene står i loggen.</string>
<string name="setup_offline">Frakoblet modus</string>
<string name="setup_offline_auto">Automatisk frakoblet modus</string>
<string name="setup_sign_in_first">Logg inn på Steam først</string>
<string name="setup_launcher">Launcher</string>
<string name="setup_language">Språk</string>
-1
View File
@@ -922,7 +922,6 @@
<string name="setup_reset_settings_session_running">Stop de sessie voordat je instellingen reset.</string>
<string name="setup_reset_settings_partial">De instellingen zijn gereset, maar niet alles. De details staan in de logs.</string>
<string name="setup_offline">Offlinemodus</string>
<string name="setup_offline_auto">Automatische offlinemodus</string>
<string name="setup_sign_in_first">Meld je eerst aan bij Steam</string>
<string name="setup_launcher">Launcher</string>
<string name="setup_language">Taal</string>
-1
View File
@@ -928,7 +928,6 @@
<string name="setup_reset_settings_session_running">Zatrzymaj sesję, zanim zresetujesz ustawienia.</string>
<string name="setup_reset_settings_partial">Ustawienia zostały zresetowane, ale nie wszystkie. Szczegóły są w logach.</string>
<string name="setup_offline">Tryb offline</string>
<string name="setup_offline_auto">Automatyczny tryb offline</string>
<string name="setup_sign_in_first">Najpierw zaloguj się do Steam</string>
<string name="setup_launcher">Aplikacja</string>
<string name="setup_language">Język</string>
@@ -917,7 +917,6 @@
<string name="setup_log_export_failed">Não foi possível guardar os registos de sessão.</string>
<string name="setup_log_delete_failed">Não foi possível eliminar os registos de sessão.</string>
<string name="setup_offline">Modo offline</string>
<string name="setup_offline_auto">Modo offline automático</string>
<string name="setup_sign_in_first">Inicie sessão no Steam primeiro</string>
<string name="setup_launcher">Iniciador</string>
<string name="setup_language">Idioma</string>
-1
View File
@@ -924,7 +924,6 @@
<string name="setup_log_export_failed">Não foi possível salvar os registros de sessão.</string>
<string name="setup_log_delete_failed">Não foi possível excluir os registros de sessão.</string>
<string name="setup_offline">Modo offline</string>
<string name="setup_offline_auto">Modo offline automático</string>
<string name="setup_sign_in_first">Inicie sessão na Steam primeiro</string>
<string name="setup_launcher">Inicializador</string>
<string name="setup_language">Idioma</string>
-1
View File
@@ -925,7 +925,6 @@
<string name="setup_reset_settings_session_running">Oprește sesiunea înainte de a reseta setările.</string>
<string name="setup_reset_settings_partial">Setările au fost resetate, dar nu toate. Detaliile sunt în jurnale.</string>
<string name="setup_offline">Mod offline</string>
<string name="setup_offline_auto">Mod offline automat</string>
<string name="setup_sign_in_first">Autentifică-te mai întâi în Steam</string>
<string name="setup_launcher">Launcher</string>
<string name="setup_language">Limbă</string>
-1
View File
@@ -928,7 +928,6 @@
<string name="setup_reset_settings_session_running">Остановите сессию перед сбросом настроек.</string>
<string name="setup_reset_settings_partial">Настройки сброшены, но некоторые части сбросить не удалось. Подробности в журналах.</string>
<string name="setup_offline">Автономный режим</string>
<string name="setup_offline_auto">Автоматический автономный режим</string>
<string name="setup_sign_in_first">Сначала войдите в Steam</string>
<string name="setup_launcher">Лаунчер</string>
<string name="setup_language">Язык</string>
-1
View File
@@ -922,7 +922,6 @@
<string name="setup_reset_settings_session_running">Stoppa sessionen innan du återställer inställningar.</string>
<string name="setup_reset_settings_partial">Inställningarna återställdes, men inte alla. Detaljerna finns i loggen.</string>
<string name="setup_offline">Offlineläge</string>
<string name="setup_offline_auto">Automatiskt offlineläge</string>
<string name="setup_sign_in_first">Logga in på Steam först</string>
<string name="setup_launcher">Startprogram</string>
<string name="setup_language">Språk</string>
-1
View File
@@ -919,7 +919,6 @@
<string name="setup_reset_settings_session_running">หยุดเซสชันก่อนรีเซ็ตการตั้งค่า</string>
<string name="setup_reset_settings_partial">รีเซ็ตการตั้งค่าแล้ว แต่ไม่ทั้งหมด รายละเอียดอยู่ในล็อก</string>
<string name="setup_offline">โหมดออฟไลน์</string>
<string name="setup_offline_auto">โหมดออฟไลน์อัตโนมัติ</string>
<string name="setup_sign_in_first">ลงชื่อเข้าใช้ Steam ก่อน</string>
<string name="setup_launcher">ตัวเปิดแอป</string>
<string name="setup_language">ภาษา</string>
-1
View File
@@ -914,7 +914,6 @@
<string name="setup_log_export_failed">Oturum günlükleri kaydedilemedi.</string>
<string name="setup_log_delete_failed">Oturum günlükleri silinemedi.</string>
<string name="setup_offline">Çevrimdışı mod</string>
<string name="setup_offline_auto">Otomatik çevrimdışı mod</string>
<string name="setup_sign_in_first">Önce Steam\'de oturum açın</string>
<string name="setup_launcher">Başlatıcı</string>
<string name="setup_language">Dil</string>
-1
View File
@@ -928,7 +928,6 @@
<string name="setup_reset_settings_session_running">Зупиніть сеанс перед скиданням налаштувань.</string>
<string name="setup_reset_settings_partial">Налаштування скинуто, але не всі. Подробиці в журналах.</string>
<string name="setup_offline">Офлайн-режим</string>
<string name="setup_offline_auto">Автоматичний офлайн-режим</string>
<string name="setup_sign_in_first">Спершу увійдіть у Steam</string>
<string name="setup_launcher">Лаунчер</string>
<string name="setup_language">Мова</string>
-1
View File
@@ -919,7 +919,6 @@
<string name="setup_reset_settings_session_running">Dừng phiên trước khi đặt lại thiết lập.</string>
<string name="setup_reset_settings_partial">Đã đặt lại thiết lập, nhưng chưa phải tất cả. Chi tiết có trong log.</string>
<string name="setup_offline">Chế độ ngoại tuyến</string>
<string name="setup_offline_auto">Chế độ ngoại tuyến tự động</string>
<string name="setup_sign_in_first">Đăng nhập Steam trước</string>
<string name="setup_launcher">Launcher</string>
<string name="setup_language">Ngôn ngữ</string>
@@ -919,7 +919,6 @@
<string name="setup_reset_settings_session_running">请先停止会话再重置设置。</string>
<string name="setup_reset_settings_partial">设置已重置,但部分内容未能重置。详情请查看日志。</string>
<string name="setup_offline">离线模式</string>
<string name="setup_offline_auto">自动离线模式</string>
<string name="setup_sign_in_first">请先登录 Steam</string>
<string name="setup_launcher">启动器</string>
<string name="setup_language">语言</string>
@@ -918,7 +918,6 @@
<string name="setup_reset_settings_session_running">請先停止會話再重設設定。</string>
<string name="setup_reset_settings_partial">設定已重設,但部分項目未能重設。詳情請查看記錄。</string>
<string name="setup_offline">離線模式</string>
<string name="setup_offline_auto">自動離線模式</string>
<string name="setup_sign_in_first">請先登入 Steam</string>
<string name="setup_launcher">啟動器</string>
<string name="setup_language">語言</string>
@@ -918,7 +918,6 @@
<string name="setup_reset_settings_session_running">請先停止工作階段再重設設定。</string>
<string name="setup_reset_settings_partial">設定已重設,但部分項目無法重設。詳細資訊請查看日誌。</string>
<string name="setup_offline">離線模式</string>
<string name="setup_offline_auto">自動離線模式</string>
<string name="setup_sign_in_first">請先登入 Steam</string>
<string name="setup_launcher">啟動器</string>
<string name="setup_language">語言</string>
-1
View File
@@ -1004,7 +1004,6 @@
<string name="setup_reset_settings_session_running">Stop the session before resetting settings.</string>
<string name="setup_reset_settings_partial">Settings were reset, but some parts could not be. The logs have the details.</string>
<string name="setup_offline">Offline mode</string>
<string name="setup_offline_auto">Auto offline mode</string>
<string name="setup_sign_in_first">Sign in to Steam first</string>
<string name="setup_launcher">Launcher</string>
<string name="setup_language">Language</string>
@@ -1,18 +0,0 @@
package com.droiddeck.launcher
import org.junit.Assert.assertTrue
import org.junit.Test
import java.io.File
class SessionRelaunchTest {
// recreate() keeps the window, and Compose content set on it afterwards never recomposes (#2668):
// a session relaunched that way kept its loading screen up over a running desktop.
@Test fun sessionAndLauncherActivitiesNeverRecreateThemselves() {
listOf("SessionActivity.kt", "FrontEndActivity.kt").forEach { name ->
val code = File("src/main/java/com/droiddeck/launcher/$name").readLines()
.map { it.substringBefore("//") }
val calls = code.withIndex().filter { (_, line) -> Regex("""\brecreate\(\)""").containsMatchIn(line) }
assertTrue("$name calls recreate() at line(s) ${calls.map { it.index + 1 }}", calls.isEmpty())
}
}
}
@@ -32,9 +32,4 @@ class SocNamesTest {
assertNull(SocNames.name("SM8975-PRO", ""))
assertNull(SocNames.name("Qualcomm SM8975", ""))
}
@Test fun plainNameNeverGuessesFromThePlatform() {
assertEquals("Snapdragon 8 Gen 2 (SM8550)", SocNames.plainName("SM8550", "QTI"))
assertEquals("Moorechip CQ7790S", SocNames.plainName("CQ7790S", "Moorechip"))
assertEquals("CQ7790S", SocNames.plainName("CQ7790S", ""))
}
}
@@ -1,246 +0,0 @@
package com.droiddeck.launcher.session
import android.content.Context
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
import com.droiddeck.launcher.runtime.LinuxRuntime
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.Shadows.shadowOf
import org.robolectric.annotation.Config
import org.robolectric.shadows.ShadowNetworkCapabilities
import java.io.File
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class OfflineModeTest {
private val context: Context = RuntimeEnvironment.getApplication()
private val root get() = LinuxRuntime.rootDir(context)
private val vdf get() = File(root, "root/.local/share/Steam/config/loginusers.vdf")
@Before
fun setUp() {
context.getSharedPreferences("session", Context.MODE_PRIVATE).edit().clear().commit()
vdf.parentFile!!.mkdirs()
writeSteam("0")
network(online = true)
}
private fun writeSteam(wants: String) {
vdf.writeText(
"\"users\"\n{\n\t\"7656\"\n\t{\n\t\t\"AccountName\"\t\t\"player\"\n" +
"\t\t\"RememberPassword\"\t\t\"1\"\n\t\t\"WantsOfflineMode\"\t\t\"$wants\"\n" +
"\t\t\"SkipOfflineModeWarning\"\t\t\"$wants\"\n\t}\n}\n"
)
}
private fun steamWants(): String =
Regex(""""WantsOfflineMode"\s*"([01])"""").find(vdf.readText())!!.groupValues[1]
private fun network(online: Boolean) {
val cm = context.getSystemService(ConnectivityManager::class.java)
val caps = ShadowNetworkCapabilities.newInstance()
shadowOf(caps).addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
if (online) {
shadowOf(caps).addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
shadowOf(caps).addCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)
}
shadowOf(cm).setNetworkCapabilities(cm.activeNetwork, caps)
}
@Test
fun offlineWhenChosenOrWithoutInternet() {
assertFalse(OfflineMode.offline(manual = false, online = true))
assertTrue(OfflineMode.offline(manual = false, online = false))
assertTrue(OfflineMode.offline(manual = true, online = true))
assertTrue(OfflineMode.offline(manual = true, online = false))
}
@Test
fun steamsOwnChoiceWinsOverTheSavedSetting() {
assertTrue(OfflineMode.manual(steamWants = true, automatic = false, saved = false))
assertFalse(OfflineMode.manual(steamWants = false, automatic = false, saved = true))
assertFalse(OfflineMode.manual(steamWants = true, automatic = true, saved = false))
assertTrue(OfflineMode.manual(steamWants = null, automatic = false, saved = true))
}
@Test
fun startsOfflineWithoutInternetAndOnlineOnceItReturns() {
network(online = false)
assertTrue(OfflineMode.apply(context, root))
assertEquals("1", steamWants())
assertFalse(OfflineMode.enabled(context))
network(online = true)
assertFalse(OfflineMode.apply(context, root))
assertEquals("0", steamWants())
assertFalse(OfflineMode.enabled(context))
}
@Test
fun manualOfflineStaysOnWithInternet() {
OfflineMode.setEnabled(context, true)
assertEquals("1", steamWants())
assertTrue(OfflineMode.apply(context, root))
assertEquals("1", steamWants())
assertTrue(OfflineMode.enabled(context))
OfflineMode.setEnabled(context, false)
assertEquals("0", steamWants())
assertFalse(OfflineMode.enabled(context))
}
@Test
fun goingOfflineInsideSteamShowsInDroidDeckAndIsKept() {
writeSteam("1")
assertTrue(OfflineMode.enabled(context))
assertTrue(OfflineMode.apply(context, root))
assertEquals("1", steamWants())
}
@Test
fun goingOnlineInsideSteamAfterAnAutomaticOfflineStartIsKept() {
network(online = false)
OfflineMode.apply(context, root)
writeSteam("0")
network(online = true)
assertFalse(OfflineMode.apply(context, root))
assertFalse(OfflineMode.enabled(context))
assertEquals("0", steamWants())
}
@Test
fun turningTheToggleOffWithoutInternetStillStartsOfflineButNotAsAChoice() {
OfflineMode.setEnabled(context, true)
network(online = false)
OfflineMode.setEnabled(context, false)
assertEquals("1", steamWants())
assertFalse(OfflineMode.enabled(context))
network(online = true)
assertFalse(OfflineMode.apply(context, root))
assertEquals("0", steamWants())
}
@Test
fun steamGoingOfflineAfterANetworkDropIsNotTakenAsAChoice() {
assertFalse(OfflineMode.apply(context, root))
network(online = false)
OfflineMode.follow(context)
writeSteam("1")
assertFalse(OfflineMode.enabled(context))
network(online = true)
OfflineMode.follow(context)
writeSteam("0")
assertFalse(OfflineMode.enabled(context))
assertFalse(OfflineMode.apply(context, root))
}
@Test
fun autoGoesOnlineWhenTheNetworkReturnsEvenAfterChoosingOfflineInSteam() {
writeSteam("1")
assertTrue(OfflineMode.enabled(context))
network(online = false)
OfflineMode.follow(context)
assertEquals("1", steamWants())
network(online = true)
OfflineMode.follow(context)
assertEquals("0", steamWants())
assertFalse(OfflineMode.enabled(context))
}
@Test
fun anAutomaticOfflineStaysAutomaticWhenSteamCannotBeReachedOnReturn() {
network(online = false)
assertTrue(OfflineMode.apply(context, root))
network(online = true)
assertEquals(null, OfflineMode.follow(context))
writeSteam("1")
assertFalse(OfflineMode.enabled(context))
assertFalse(OfflineMode.apply(context, root))
assertEquals("0", steamWants())
}
@Test
fun aManualChoiceMadeAfterAFailedReturnIsNotMarkedAutomatic() {
network(online = false)
assertTrue(OfflineMode.apply(context, root))
network(online = true)
OfflineMode.setAuto(context, false)
OfflineMode.setEnabled(context, true)
OfflineMode.restoreNetworkOffline(context)
assertTrue(OfflineMode.enabled(context))
assertTrue(OfflineMode.apply(context, root))
assertEquals("1", steamWants())
}
@Test
fun autoIsOnByDefaultAndManualModeIgnoresTheNetwork() {
assertTrue(OfflineMode.auto(context))
OfflineMode.setAuto(context, false)
assertFalse(OfflineMode.auto(context))
network(online = false)
assertFalse(OfflineMode.apply(context, root))
assertFalse(OfflineMode.active(context))
assertEquals(false, OfflineMode.follow(context))
assertEquals("0", steamWants())
}
@Test
fun chosenOfflineInManualModeSurvivesANetworkDropAndReturn() {
OfflineMode.setAuto(context, false)
OfflineMode.setEnabled(context, true)
network(online = false)
OfflineMode.follow(context)
network(online = true)
OfflineMode.follow(context)
assertTrue(OfflineMode.enabled(context))
assertTrue(OfflineMode.apply(context, root))
assertEquals("1", steamWants())
}
@Test
fun turningAutoOffKeepsTheCurrentStateAsTheChoice() {
network(online = false)
assertTrue(OfflineMode.apply(context, root))
OfflineMode.setAuto(context, false)
assertTrue(OfflineMode.enabled(context))
network(online = true)
assertTrue(OfflineMode.apply(context, root))
assertEquals("1", steamWants())
}
@Test
fun turningAutoOffRightAfterTheNetworkReturnsKeepsSteamOffline() {
network(online = false)
assertTrue(OfflineMode.apply(context, root))
network(online = true)
OfflineMode.setAuto(context, false)
assertTrue(OfflineMode.enabled(context))
assertEquals("1", steamWants())
}
@Test
fun turningAutoOffWhileOnlineStaysOnline() {
OfflineMode.setAuto(context, false)
assertFalse(OfflineMode.enabled(context))
assertEquals("0", steamWants())
}
@Test
fun turningAutoOnFollowsTheNetworkAgain() {
OfflineMode.setAuto(context, false)
OfflineMode.setEnabled(context, true)
OfflineMode.setAuto(context, true)
assertFalse(OfflineMode.enabled(context))
assertEquals("0", steamWants())
network(online = false)
assertTrue(OfflineMode.apply(context, root))
assertFalse(OfflineMode.enabled(context))
}
}
@@ -173,7 +173,7 @@ class StoreGameSidecarTest {
)
@Test fun epicTitlesThatCheckTheirParentStartUnderTheStandIn() {
for (id in listOf("9d2d0eb64d5c44529cece33fe2a46482", "8769e24080ea413b8ebca3f1b8c50951", "Heather", "7133a8c315324112a3eee2458f0a8242")) {
for (id in listOf("9d2d0eb64d5c44529cece33fe2a46482", "8769e24080ea413b8ebca3f1b8c50951", "Heather")) {
val lines = StoreLaunch.launcherText(StoreGameSidecar(Store.EPIC, id, "Rockstar title", "PlayGTAV.exe")).split("\r\n")
val on = lines.indexOf("set \"DD_P=1\"")
assertTrue(id, on > lines.indexOf("cd /d \"%~dp0\""))
+2 -6
View File
@@ -38,9 +38,8 @@ python3 /usr/local/bin/droiddeck-desktop-programs 2>&1 | sed 's/^/[programs] /'
# start, and a panel made before this version (Kubuntu's own, or the first SteamOS one without the
# pager, clock and Plasma's stock pins) is set aside once so Plasma lays out the current one.
dd_layout=/usr/share/plasma/look-and-feel/com.valve.vapor.desktop/contents/layouts
dd_layout_installed=0
if [ -d "$dd_layout" ]; then
if cat > "$dd_layout/org.kde.plasma.desktop-layout.js" <<'LAYOUT'
cat > "$dd_layout/org.kde.plasma.desktop-layout.js" <<'LAYOUT'
var desktops = desktopsForActivity(currentActivity());
for (var i = 0; i < desktops.length; i++) {
desktops[i].wallpaperPlugin = "org.kde.image";
@@ -112,13 +111,10 @@ clock.currentConfigGroup = ["Appearance"];
clock.writeConfig("dateFormat", "isoDate");
panel.addWidget("org.kde.plasma.showdesktop");
LAYOUT
then
dd_layout_installed=1
fi
fi
dd_panel_rc="${XDG_CONFIG_HOME:-$HOME/.config}/plasma-org.kde.plasma.desktop-appletsrc"
dd_panel_stamp="${XDG_CONFIG_HOME:-$HOME/.config}/droiddeck-panel-layout"
if [ "$dd_layout_installed" -eq 1 ] && [ "$(cat "$dd_panel_stamp" 2>/dev/null)" != steamos-2 ]; then
if [ "$(cat "$dd_panel_stamp" 2>/dev/null)" != steamos-2 ]; then
dd_panel_backup="$dd_panel_rc.before-steamos-2"
[ -e "$dd_panel_backup" ] && dd_panel_backup="$dd_panel_backup.$$"
if [ ! -f "$dd_panel_rc" ] || mv "$dd_panel_rc" "$dd_panel_backup"; then
@@ -1,27 +0,0 @@
#!/bin/sh
# The device tree on Android handhelds names the SoC vendor's reference board ("Kera MTP") and an
# internal codename for the CPU, so the device and SoC names come from Android through the session.
case "$1" in
host)
if [ -n "$DD_DEVICE_NAME" ]; then
printf '%s\n' "$DD_DEVICE_NAME"
else
tr -d '\0' < /proc/device-tree/model 2>/dev/null
echo
fi
;;
cpu)
name=${DD_SOC_NAME:-$(cat /sys/devices/soc0/machine 2>/dev/null)}
cores=$(getconf _NPROCESSORS_CONF)
mhz=$(cat /sys/devices/system/cpu/cpu*/cpufreq/cpuinfo_max_freq 2>/dev/null | sort -n | tail -n 1)
if [ -n "$mhz" ]; then
printf '%s (%s) @ %s GHz\n' "$name" "$cores" "$(awk -v k="$mhz" 'BEGIN { printf "%.2f", k / 1000000 }')"
else
printf '%s (%s)\n' "$name" "$cores"
fi
;;
*)
echo "usage: droiddeck-device-info host|cpu" >&2
exit 2
;;
esac
-25
View File
@@ -1,25 +0,0 @@
{
"$schema": "https://github.com/fastfetch-cli/fastfetch/raw/dev/doc/json_schema.json",
"logo": {
"type": "file",
"source": "/usr/share/droiddeck/fastfetch/logo.txt",
"color": {
"1": "38;2;255;255;255",
"2": "38;2;26;159;255"
},
"padding": { "right": 3 }
},
"modules": [
"title", "separator", "os",
{ "type": "command", "key": "Host", "text": "droiddeck-device-info host" },
"kernel", "uptime", "packages", "shell",
"display", "de", "wm", "wmtheme", "theme", "icons", "font", "cursor",
"terminal",
{ "type": "command", "key": "CPU", "text": "droiddeck-device-info cpu" },
"gpu", "memory", "swap",
{ "type": "disk", "key": "Disk", "folders": "/", "format": "{size-used} / {size-total} ({size-percentage})" },
{ "type": "battery", "key": "Battery" },
"locale",
"break", "colors"
]
}
+77 -7
View File
@@ -40,6 +40,35 @@ struct vd_dma_heap_alloc {
};
#define VD_DMA_HEAP_IOCTL_ALLOC _IOWR('H', 0x0, struct vd_dma_heap_alloc)
struct vd_ion_alloc {
uint64_t len;
uint32_t heap_id_mask;
uint32_t flags;
uint32_t fd;
uint32_t unused;
};
struct vd_ion_legacy_alloc {
size_t len;
size_t align;
uint32_t heap_id_mask;
uint32_t flags;
int32_t handle;
};
struct vd_ion_fd {
int32_t handle;
int32_t fd;
};
struct vd_ion_handle {
int32_t handle;
};
#define VD_ION_IOC_ALLOC _IOWR('I', 0, struct vd_ion_alloc)
#define VD_ION_IOC_LEGACY_ALLOC _IOWR('I', 0, struct vd_ion_legacy_alloc)
#define VD_ION_IOC_FREE _IOWR('I', 1, struct vd_ion_handle)
#define VD_ION_IOC_SHARE _IOWR('I', 4, struct vd_ion_fd)
#define VD_ION_SYSTEM_HEAP_MASK (1u << 25)
enum { VD_HEAP_DMA, VD_HEAP_ION, VD_HEAP_ION_LEGACY };
struct vd_dma_buf_sync {
uint64_t flags;
};
@@ -172,6 +201,7 @@ static int vd_open_count;
static int vd_state;
static int vd_ffmpeg;
static int vd_heap = -1;
static int vd_heap_kind;
static int vd_dumb_fd[VDEC_DUMB];
static char vd_drm_handle;
@@ -226,15 +256,54 @@ static int vd_have_ffmpeg(void) {
__attribute__((visibility("hidden"))) int dd_venc_connect(void);
static int vd_open_heap(void) {
vd_heap = open("/dev/dma_heap/system", O_RDONLY | O_CLOEXEC);
if (vd_heap >= 0) {
vd_heap_kind = VD_HEAP_DMA;
return 1;
}
int heap_errno = errno;
vd_heap = open("/dev/ion", O_RDONLY | O_CLOEXEC);
if (vd_heap < 0) {
int ion_errno = errno;
vd_log("no /dev/dma_heap/system (%s) or /dev/ion (%s), Remote Play decoding stays off", strerror(heap_errno),
strerror(ion_errno));
return 0;
}
struct vd_ion_handle probe = { 0 };
vd_heap_kind = ioctl(vd_heap, VD_ION_IOC_FREE, &probe) >= 0 || errno != ENOTTY ? VD_HEAP_ION_LEGACY : VD_HEAP_ION;
vd_log("no /dev/dma_heap/system (%s), Remote Play buffers come from %s", strerror(heap_errno),
vd_heap_kind == VD_HEAP_ION ? "ION" : "legacy ION");
return 1;
}
static int vd_heap_alloc(uint64_t size) {
if (vd_heap_kind == VD_HEAP_DMA) {
struct vd_dma_heap_alloc a = { .len = size, .fd_flags = O_RDWR | O_CLOEXEC };
return ioctl(vd_heap, VD_DMA_HEAP_IOCTL_ALLOC, &a) == 0 ? (int)a.fd : -1;
}
if (vd_heap_kind == VD_HEAP_ION) {
struct vd_ion_alloc a = { .len = size, .heap_id_mask = VD_ION_SYSTEM_HEAP_MASK };
return ioctl(vd_heap, VD_ION_IOC_ALLOC, &a) == 0 ? (int)a.fd : -1;
}
struct vd_ion_legacy_alloc a = { .len = (size_t)size, .align = 4096, .heap_id_mask = VD_ION_SYSTEM_HEAP_MASK };
if (ioctl(vd_heap, VD_ION_IOC_LEGACY_ALLOC, &a) != 0) return -1;
struct vd_ion_fd share = { .handle = a.handle, .fd = -1 };
int shared = ioctl(vd_heap, VD_ION_IOC_SHARE, &share) == 0;
int share_errno = errno;
struct vd_ion_handle handle = { .handle = a.handle };
ioctl(vd_heap, VD_ION_IOC_FREE, &handle);
errno = share_errno;
return shared ? share.fd : -1;
}
static int vd_enabled(void) {
pthread_mutex_lock(&vd_lock);
if (vd_state == 0) {
const char *flag = getenv("DD_REMOTE_PLAY_DECODE"), *socket = getenv("DD_VENC_SOCKET");
vd_state = -1;
if (strcmp(program_invocation_short_name, "streaming_client") == 0 && (flag == NULL || strcmp(flag, "0") != 0)) {
vd_heap = open("/dev/dma_heap/system", O_RDONLY | O_CLOEXEC);
if (vd_heap < 0) vd_log("no /dev/dma_heap/system (%s), Remote Play decoding stays off", strerror(errno));
else if ((socket && *socket) || vd_have_ffmpeg()) vd_state = 1;
if (vd_open_heap() && ((socket && *socket) || vd_have_ffmpeg())) vd_state = 1;
for (int i = 0; i < VDEC_DUMB; i++) vd_dumb_fd[i] = -1;
}
}
@@ -1033,14 +1102,15 @@ static int drm_ioctl(int fd, unsigned long request, void *arg) {
uint64_t size = (pitch * c->height + 4095) & ~4095ull;
int slot = -1;
for (int i = 0; i < VDEC_DUMB && slot < 0; i++) if (vd_dumb_fd[i] < 0) slot = i;
struct vd_dma_heap_alloc a = { .len = size, .fd_flags = O_RDWR | O_CLOEXEC };
int buf = -1;
if (slot < 0 || size == 0 || size > (512ull << 20)) {
r = -ENOMEM;
} else if (ioctl(vd_heap, VD_DMA_HEAP_IOCTL_ALLOC, &a) != 0) {
} else if ((buf = vd_heap_alloc(size)) < 0) {
r = -errno;
vd_log("dma-heap allocation of %llu bytes failed: %s", (unsigned long long)size, strerror(errno));
vd_log("%s allocation of %llu bytes failed: %s", vd_heap_kind == VD_HEAP_DMA ? "dma-heap" : "ION",
(unsigned long long)size, strerror(errno));
} else {
vd_dumb_fd[slot] = (int)a.fd;
vd_dumb_fd[slot] = buf;
c->handle = (uint32_t)slot + 1;
c->pitch = (uint32_t)pitch;
c->size = size;
+8 -262
View File
@@ -44,7 +44,6 @@ struct ddnatv_bind {
char *src, *dst;
size_t src_len, dst_len;
int identity;
int links;
int order; // position in DDNATV_BINDS: the earlier of two mounts of one folder is its guest path
};
// as many as the session has: a fixed table dropped what came after its 128th entry
@@ -57,7 +56,6 @@ static char g_hostname[65];
// link targets as paths in it, as the kernel follows them there; in the sandbox they are guest paths
static char g_link_root[PATH_MAX];
static size_t g_link_root_len = 0;
static char g_mount_table[PATH_MAX] = "/proc/self/mountinfo";
static int ddnatv_bind_longer_first(const void *a, const void *b) {
const struct ddnatv_bind *x = a, *y = b;
@@ -299,243 +297,10 @@ static int relative_link_into_bind(const char *link, const char *target, const c
// /sys/devices/droiddeck/...): proot follows them inside the guest, the kernel on Android's own /sys.
// A link met on the way to a deeper path is replaced by its target, mapped again; the last component is
// left as it is (lstat() and readlink() must see the link).
#if defined(__aarch64__)
static long raw_open_path(const char *path, long flags) {
register long x8 __asm__("x8") = 56;
register long x0 __asm__("x0") = AT_FDCWD;
register long x1 __asm__("x1") = (long)path;
register long x2 __asm__("x2") = flags | O_PATH | O_CLOEXEC;
register long x3 __asm__("x3") = 0;
__asm__ volatile("svc #0" : "+r"(x0) : "r"(x8), "r"(x1), "r"(x2), "r"(x3) : "memory");
return x0;
}
static void raw_close_fd(long fd) {
register long x8 __asm__("x8") = 57;
register long x0 __asm__("x0") = fd;
__asm__ volatile("svc #0" : "+r"(x0) : "r"(x8) : "memory");
}
static __thread const char *t_plain_host = NULL;
static __thread size_t t_plain_len = 0;
static int fd_is_at(long fd, const char *path, size_t len) {
char link[32] = "/proc/self/fd/";
char digits[24];
int nd = 0;
for (long v = fd; nd == 0 || v > 0; v /= 10) digits[nd++] = (char)('0' + v % 10);
size_t at = 14;
while (nd > 0) link[at++] = digits[--nd];
link[at] = '\0';
char real[PATH_MAX];
long n = raw_readlinkat(AT_FDCWD, link, real, sizeof(real));
return n == (long)len && memcmp(real, path, len) == 0;
}
static int prefix_has_no_links(const char *host, size_t dir_len, size_t src_len) {
char dir[PATH_MAX];
if (dir_len <= src_len || dir_len >= sizeof(dir)) return 0;
memcpy(dir, host, dir_len);
dir[dir_len] = '\0';
size_t at = dir_len;
for (;;) {
long fd = raw_open_path(dir, O_NOFOLLOW);
if (fd >= 0) {
char target[2];
int plain = fd_is_at(fd, dir, at) && raw_readlinkat((int)fd, "", target, sizeof(target)) < 0;
raw_close_fd(fd);
return plain;
}
if (fd != -ENOENT && fd != -ENOTDIR) return 0;
while (at > src_len && dir[at] != '/') at--;
if (at <= src_len) return 0;
dir[at] = '\0';
}
}
static int path_has_no_links(const char *host, size_t len, size_t dir_len, size_t src_len) {
t_plain_host = NULL;
long fd = raw_open_path(host, O_NOFOLLOW);
if (fd >= 0) {
char target[2];
int plain = fd_is_at(fd, host, len) && raw_readlinkat((int)fd, "", target, sizeof(target)) < 0;
raw_close_fd(fd);
if (plain) {
t_plain_host = host;
t_plain_len = len;
return 1;
}
return prefix_has_no_links(host, dir_len, src_len);
}
if (!prefix_has_no_links(host, dir_len, src_len)) return 0;
if (fd == -ENOENT) {
t_plain_host = host;
t_plain_len = len;
}
return 1;
}
static int known_plain(const char *host) {
int plain = t_plain_host == host && strlen(host) == t_plain_len;
t_plain_host = NULL;
return plain;
}
static int fs_type_holds_no_links(const char *type) {
return strcmp(type, "vfat") == 0 || strcmp(type, "exfat") == 0 || strcmp(type, "msdos") == 0 ||
strcmp(type, "sdfat") == 0;
}
struct mount_scan {
const char *src;
size_t src_len;
size_t best_len;
int best_plain;
int best_fuse;
char best_name[256];
int nested_links;
int incomplete;
int ambiguous;
int lower_count;
char lower[16][256];
};
static int is_volume_fuse_point(const char *point, const char *name) {
static const char *const roots[] = {"/mnt/user/", "/mnt/installer/", "/mnt/androidwritable/"};
const char *rest = NULL;
if (strncmp(point, "/storage/", 9) == 0) {
rest = point + 9;
} else {
for (size_t i = 0; i < sizeof(roots) / sizeof(roots[0]) && !rest; i++) {
size_t len = strlen(roots[i]);
if (strncmp(point, roots[i], len) != 0) continue;
const char *p = point + len;
if (*p < '0' || *p > '9') return 0;
while (*p >= '0' && *p <= '9') p++;
if (*p != '/') return 0;
rest = p + 1;
}
}
return rest && rest == name && name[0];
}
static void mount_scan_line(struct mount_scan *scan, char *line) {
char *field[5];
char *p = line;
for (int i = 0; i < 5; i++) {
while (*p == ' ') p++;
field[i] = p;
while (*p && *p != ' ') p++;
if (!*p) return;
*p++ = '\0';
}
char *sep = strstr(p, " - ");
if (!sep) return;
char *type = sep + 3;
char *source = strchr(type, ' ');
if (!source) return;
*source++ = '\0';
char *end = strchr(source, ' ');
if (end) *end = '\0';
const char *point = field[4];
size_t point_len = strlen(point);
int plain = fs_type_holds_no_links(type);
const char *name = strrchr(point, '/');
name = name ? name + 1 : point;
if (plain && strncmp(point, "/mnt/media_rw/", 14) == 0 && !strchr(point + 14, '/') && name[0] &&
strlen(name) < sizeof(scan->lower[0]) && scan->lower_count < 16)
ddnatv_copy_cstr(scan->lower[scan->lower_count++], sizeof(scan->lower[0]), name);
if (point_len > scan->src_len && is_path_prefix(point, scan->src, scan->src_len)) {
if (!plain) scan->nested_links = 1;
return;
}
int covers = point_len == 1 ? point[0] == '/' : is_path_prefix(scan->src, point, point_len);
if (!covers || (point_len < scan->best_len && scan->best_len != 0)) return;
if (point_len == scan->best_len) scan->ambiguous = 1;
scan->best_len = point_len;
scan->best_plain = plain;
scan->best_fuse = strcmp(type, "fuse") == 0 && strcmp(source, "/dev/fuse") == 0 && is_volume_fuse_point(point, name);
ddnatv_copy_cstr(scan->best_name, sizeof(scan->best_name), strlen(name) < sizeof(scan->best_name) ? name : "");
}
static long raw_open_read(const char *path) {
register long x8 __asm__("x8") = 56;
register long x0 __asm__("x0") = AT_FDCWD;
register long x1 __asm__("x1") = (long)path;
register long x2 __asm__("x2") = O_RDONLY | O_CLOEXEC;
register long x3 __asm__("x3") = 0;
__asm__ volatile("svc #0" : "+r"(x0) : "r"(x8), "r"(x1), "r"(x2), "r"(x3) : "memory");
return x0;
}
static long raw_read_fd(long fd, char *buf, size_t size) {
register long x8 __asm__("x8") = 63;
register long x0 __asm__("x0") = fd;
register long x1 __asm__("x1") = (long)buf;
register long x2 __asm__("x2") = (long)size;
__asm__ volatile("svc #0" : "+r"(x0) : "r"(x8), "r"(x1), "r"(x2) : "memory");
return x0;
}
static int mount_holds_no_links(const char *src, size_t src_len) {
if (src_len == 0 || src_len >= PATH_MAX || strpbrk(src, " \t\n\\")) return 0;
long fd = raw_open_read(g_mount_table);
if (fd < 0) return 0;
struct mount_scan *scan = calloc(1, sizeof(*scan));
if (!scan) { raw_close_fd(fd); return 0; }
scan->src = src;
scan->src_len = src_len;
char line[4096];
size_t used = 0;
int skipping = 0;
char chunk[4096];
long n;
while ((n = raw_read_fd(fd, chunk, sizeof(chunk))) > 0 || n == -EINTR) {
for (long i = 0; i < n; i++) {
char c = chunk[i];
if (c == '\n') {
if (!skipping) {
line[used] = '\0';
mount_scan_line(scan, line);
}
used = 0;
skipping = 0;
} else if (used + 1 < sizeof(line)) {
line[used++] = c;
} else {
skipping = 1;
scan->incomplete = 1;
}
}
}
raw_close_fd(fd);
int none = 0;
if (n == 0 && used == 0 && !scan->incomplete && !scan->ambiguous && scan->best_len && !scan->nested_links) {
if (scan->best_plain) none = 1;
else if (scan->best_fuse && scan->best_name[0])
for (int i = 0; i < scan->lower_count && !none; i++) none = strcmp(scan->lower[i], scan->best_name) == 0;
}
free(scan);
return none;
}
static int bind_holds_no_links(struct ddnatv_bind *b) {
int state = __atomic_load_n(&b->links, __ATOMIC_RELAXED);
if (state == 0) {
state = mount_holds_no_links(b->src, b->src_len) ? 2 : 1;
__atomic_store_n(&b->links, state, __ATOMIC_RELAXED);
}
return state == 2;
}
#endif
static const char *resolve_links_after(const char *host, size_t src_len, char *buffer, size_t bufsize, int check_plain) {
static const char *resolve_bind_links(const char *host, size_t src_len, char *buffer, size_t bufsize) {
#if defined(__aarch64__)
size_t len = strlen(host);
if (len >= PATH_MAX || t_bind_link_depth >= 8) return host;
const char *last = strrchr(host, '/');
size_t dir_len = last ? (size_t)(last - host) : 0;
if (check_plain && dir_len > src_len && path_has_no_links(host, len, dir_len, src_len)) return host == buffer ? buffer : host;
for (size_t i = src_len + 1; i < len; i++) {
if (host[i] != '/') continue;
char prefix[PATH_MAX];
@@ -559,22 +324,18 @@ static const char *resolve_links_after(const char *host, size_t src_len, char *b
return buffer;
}
#else
(void)src_len; (void)bufsize; (void)check_plain;
(void)src_len; (void)bufsize;
#endif
return host == buffer ? buffer : host;
}
static const char *resolve_bind_links(const char *host, size_t src_len, char *buffer, size_t bufsize) {
return resolve_links_after(host, src_len, buffer, bufsize, 1);
}
// Wine opens every file through its prefix's drive link (dosdevices/z: -> /), so the link must be
// followed in the guest's view even where the prefix is plain rootfs: the kernel would look for the
// rest of the path on Android's own tree. Only that component is checked, not each one of every path.
static const char *resolve_drive_links(const char *host, char *buffer, size_t bufsize) {
const char *devices = strstr(host, "/dosdevices/");
if (!devices) return host;
return resolve_links_after(host, (size_t)(devices - host) + 11, buffer, bufsize, 0);
return resolve_bind_links(host, (size_t)(devices - host) + 11, buffer, bufsize);
}
// Maps an absolute Ubuntu path into the rootfs. Returns `path` (possibly advanced past
@@ -629,14 +390,7 @@ static const char *rewrite_path_in_root(const char *path, char *buffer, size_t b
if (strstr(path + b->dst_len, "/..") && climbs_past_root("", path + b->dst_len))
return rewrite_normalized_in_root(path, buffer, bufsize);
size_t n = ddnatv_append(buffer, bufsize, 0, b->src, b->src_len);
n = ddnatv_append(buffer, bufsize, n, path + b->dst_len, strlen(path + b->dst_len));
#if defined(__aarch64__)
if (bind_holds_no_links(&g_binds[i])) {
t_plain_host = buffer;
t_plain_len = n;
return buffer;
}
#endif
ddnatv_append(buffer, bufsize, n, path + b->dst_len, strlen(path + b->dst_len));
return resolve_bind_links(buffer, b->src_len, buffer, bufsize);
}
}
@@ -701,21 +455,17 @@ static size_t link_root_guest_target(char *target, size_t len) {
// view: the kernel resolves a relative target next to the link's real place, and in a mount that is
// elsewhere (Flatpak's /run/user/0/wayland-0 -> ../../flatpak/wayland-0, where /run/flatpak/wayland-0
// is another mount). Returns `path` when it is no link.
static const char *follow_guest_link_host(const char *path, char *out, size_t outsz, char *host_out, size_t host_outsz) {
static const char *follow_guest_link(const char *path, char *out, size_t outsz) {
#if defined(__aarch64__)
const char *cur = path;
for (int depth = 0; depth < 8; depth++) {
char host_buf[PATH_MAX];
t_plain_host = NULL;
const char *host = rewrite_path_in_root(cur, host_buf, sizeof(host_buf));
// /dev/stdin and /dev/fd are mounts of /proc/self/fd, whose links ("pipe:[123]") only the kernel opens
if (strncmp(host, "/proc/", 6) == 0) return cur;
char target[PATH_MAX];
long n = known_plain(host) ? -EINVAL : raw_readlinkat(AT_FDCWD, host, target, sizeof(target) - 1);
if (n <= 0) {
if (host_out && cur == path) ddnatv_copy_cstr(host_out, host_outsz, host);
return cur;
}
long n = raw_readlinkat(AT_FDCWD, host, target, sizeof(target) - 1);
if (n <= 0) return cur;
target[n] = '\0';
n = (long)link_root_guest_target(target, (size_t)n);
char joined[PATH_MAX];
@@ -754,15 +504,11 @@ static const char *follow_guest_link_host(const char *path, char *out, size_t ou
}
return cur;
#else
(void)out; (void)outsz; (void)host_out; (void)host_outsz;
(void)out; (void)outsz;
return path;
#endif
}
static const char *follow_guest_link(const char *path, char *out, size_t outsz) {
return follow_guest_link_host(path, out, outsz, NULL, 0);
}
// On ENOENT, stat()/lstat()/readlink() retry /usr/bin <-> /bin and /usr/sbin <-> /sbin, for
// rootfs trees where bin and sbin are real directories. Returns 1 for the bin pair, 2 for the
// sbin pair (with the other spelling in `alt`), 0 when `sub` is in neither.
+2 -10
View File
@@ -37,9 +37,6 @@ static void init_ddnatv_hook(void) {
}
}
ddnatv_load_binds(getenv("DDNATV_BINDS"));
const char *mount_table = getenv("DDNATV_MOUNTINFO");
if (mount_table && mount_table[0] == '/' && strlen(mount_table) < sizeof(g_mount_table))
ddnatv_copy_cstr(g_mount_table, sizeof(g_mount_table), mount_table);
const char *exec_loader = getenv("DDNATV_EXEC");
if (exec_loader && exec_loader[0] == '/' && strlen(exec_loader) < sizeof(g_exec_loader))
ddnatv_copy_cstr(g_exec_loader, sizeof(g_exec_loader), exec_loader);
@@ -779,16 +776,13 @@ static const char *rewrite_path_follow(const char *path, char *buffer, size_t bu
if (!best || b->src_len > best->src_len) best = b;
}
if (!best) {
#if defined(__aarch64__)
t_plain_host = NULL;
#endif
const char *host = rewrite_path_in_root(path, buffer, bufsize);
#if defined(__aarch64__)
// A link in the rootfs with an absolute guest target that the hook did not write (one made
// under proot, or copied from Proton's template prefix, as Wine's "z:" -> "/") is followed
// by the kernel on Android's own tree: Wine found no drive for any path and gave games
// \\?\unix\ names, which an NW.js game could not load its DLLs from.
if (is_android_host_path(path) || known_plain(host)) return host;
if (is_android_host_path(path)) return host;
char target[PATH_MAX];
long n = raw_readlinkat(AT_FDCWD, host, target, sizeof(target) - 1);
if (n <= 0 || target[0] != '/') return host;
@@ -811,9 +805,7 @@ static const char *rewrite_path_follow(const char *path, char *buffer, size_t bu
path = from_source;
}
char guest[PATH_MAX];
buffer[0] = '\0';
const char *followed = follow_guest_link_host(path, guest, sizeof(guest), buffer, bufsize);
if (followed == path && buffer[0]) return buffer;
const char *followed = follow_guest_link(path, guest, sizeof(guest));
char mapped[PATH_MAX];
const char *host = rewrite_path_in_root(followed, mapped, sizeof(mapped));
// the result may be `followed` or `path` itself, which can live here
+1 -3
View File
@@ -27,12 +27,10 @@ def source_assets(overlay=OVERLAY):
result = {source: 'assets/linuxfs/' + source.relative_to(overlay).as_posix() for source in sources}
if overlay == OVERLAY:
desktop = overlay.parent / 'desktop'
for name in ['droiddeck-desktop', 'droiddeck-gpu', 'droiddeck-desktop-gpu', 'droiddeck-device-info',
'kwin_wayland_wrapper']:
for name in ['droiddeck-desktop', 'droiddeck-gpu', 'droiddeck-desktop-gpu', 'kwin_wayland_wrapper']:
result[desktop / name] = 'assets/linuxfs/usr/local/bin/' + name
result[desktop / 'firefox-droiddeck.js'] = 'assets/linuxfs/usr/lib/firefox/defaults/pref/droiddeck.js'
result[desktop / 'droiddeck-clipboard.desktop'] = 'assets/linuxfs/etc/xdg/autostart/droiddeck-clipboard.desktop'
result[desktop / 'fastfetch.jsonc'] = 'assets/linuxfs/etc/xdg/fastfetch/config.jsonc'
result[overlay.parent.parent / 'mangoapp/mangoapp'] = 'assets/linuxfs/usr/local/bin/mangoapp'
return result
-28
View File
@@ -1,28 +0,0 @@
import json
import os
import re
import subprocess
import unittest
from pathlib import Path
DESKTOP = Path(__file__).resolve().parents[1] / "linuxfs/desktop"
class DesktopDeviceInfoTest(unittest.TestCase):
def run_info(self, what, **env):
return subprocess.run(["sh", str(DESKTOP / "droiddeck-device-info"), what], capture_output=True, text=True,
env={**os.environ, **env}, check=True).stdout
def test_names_come_from_the_session(self):
self.assertEqual(self.run_info("host", DD_DEVICE_NAME="Retroid Pocket Duo"), "Retroid Pocket Duo\n")
self.assertRegex(self.run_info("cpu", DD_SOC_NAME="Moorechip CQ7790S"),
r"^Moorechip CQ7790S \(\d+\)( @ \d+\.\d\d GHz)?\n$")
def test_fastfetch_uses_it_for_host_and_cpu(self):
text = re.sub(r"^\s*//.*$", "", (DESKTOP / "fastfetch.jsonc").read_text(), flags=re.M)
modules = {m["key"]: m["text"] for m in json.loads(text)["modules"] if isinstance(m, dict) and m.get("type") == "command"}
self.assertEqual(modules, {"Host": "droiddeck-device-info host", "CPU": "droiddeck-device-info cpu"})
if __name__ == "__main__":
unittest.main()
+2 -49
View File
@@ -19,11 +19,10 @@ def block(first, last):
return DESKTOP[start:DESKTOP.index(last, start) + len(last)]
def run(script, home, layout_installed=True):
def run(script, home):
environment = {key: value for key, value in os.environ.items() if key != 'XDG_CONFIG_HOME'}
environment['HOME'] = str(home)
prefix = 'dd_layout_installed=1\n' if layout_installed else ''
result = subprocess.run(['bash', '-c', prefix + script], env=environment, capture_output=True, text=True, timeout=5)
result = subprocess.run(['bash', '-c', script], env=environment, capture_output=True, text=True, timeout=5)
if result.returncode != 0:
raise AssertionError(result.stderr)
@@ -102,52 +101,6 @@ class DesktopSteamosPanelTest(unittest.TestCase):
for language in ('ja', 'ko', 'th', 'zh_CN', 'zh_TW', 'hi'):
self.assertIn('"' + language + '"', OVERLAY_LAYOUT)
def test_panel_migration_is_skipped_when_layout_directory_is_missing(self):
with tempfile.TemporaryDirectory() as home:
home = Path(home)
config = home / '.config'
config.mkdir()
(config / RC).write_text('existing panel\n')
layout_dir = home / 'missing-layout'
script = block('dd_layout=', '# startplasma applies this file')
script = script.replace('dd_layout=' + LAYOUT_DIR, 'dd_layout=' + layout_dir.as_posix())
run(script, home)
self.assertEqual('existing panel\n', (config / RC).read_text())
self.assertFalse((config / (RC + '.before-steamos-2')).exists())
self.assertFalse((config / STAMP).exists())
def test_panel_migration_is_skipped_when_layout_write_fails(self):
with tempfile.TemporaryDirectory() as home:
home = Path(home)
config = home / '.config'
config.mkdir()
(config / RC).write_text('existing panel\n')
layout_dir = home / 'layouts'
layout_dir.mkdir()
(layout_dir / 'org.kde.plasma.desktop-layout.js').mkdir()
script = block('dd_layout=', '# startplasma applies this file')
script = script.replace('dd_layout=' + LAYOUT_DIR, 'dd_layout=' + layout_dir.as_posix())
run(script, home)
self.assertEqual('existing panel\n', (config / RC).read_text())
self.assertFalse((config / (RC + '.before-steamos-2')).exists())
self.assertFalse((config / STAMP).exists())
def test_panel_migration_runs_after_layout_write_succeeds(self):
with tempfile.TemporaryDirectory() as home:
home = Path(home)
config = home / '.config'
config.mkdir()
(config / RC).write_text('old panel\n')
layout_dir = home / 'layouts'
layout_dir.mkdir()
script = block('dd_layout=', '# startplasma applies this file')
script = script.replace('dd_layout=' + LAYOUT_DIR, 'dd_layout=' + layout_dir.as_posix())
run(script, home)
self.assertTrue((layout_dir / 'org.kde.plasma.desktop-layout.js').is_file())
self.assertFalse((config / RC).exists())
self.assertEqual('old panel\n', (config / (RC + '.before-steamos-2')).read_text())
self.assertEqual('steamos-2', (config / STAMP).read_text().strip())
def test_the_panel_is_prepared_before_plasma_starts(self):
for marker in ('dd_layout=', 'dd_panel_rc='):
self.assertLess(DESKTOP.index(marker), DESKTOP.index('dbus-run-session -- startplasma-wayland'))
+5 -177
View File
@@ -1,7 +1,5 @@
import os
from pathlib import Path
import re
import shutil
import subprocess
import tempfile
import unittest
@@ -67,11 +65,6 @@ int main(int argc, char **argv) {
printf("%s\t%s\n", argv[i], ok ? cwd : "-");
continue;
}
if (strncmp(argv[i], "lstat:", 6) == 0) {
int ok = lstat(argv[i] + 6, &st) == 0;
printf("%s\t%d\t%d\n", argv[i], ok, ok && S_ISLNK(st.st_mode));
continue;
}
if (strncmp(argv[i], "at:", 3) == 0) {
int dfd = open(argv[i] + 3, O_RDONLY | O_DIRECTORY);
printf("%s\t%d\t%d\n", argv[i], fstatat(AT_FDCWD, argv[i] + 3, &st, 0) == 0, dfd >= 0);
@@ -156,18 +149,6 @@ class NativeHookMountTest(unittest.TestCase):
private_copy = cls.private / "456/pfx/dosdevices"
private_copy.mkdir(parents=True)
os.symlink("../" * 12 + "..", private_copy / "z:")
cls.links = tmp / "links"
(cls.links / "real/sub").mkdir(parents=True)
(cls.links / "real/sub/file.txt").write_text("deep")
(cls.links / "real/sub/deeper/more").mkdir(parents=True)
(cls.links / "real/sub/deeper/more/leaf.txt").write_text("leaf")
os.symlink("real", cls.links / "dir")
os.symlink(str(cls.links / "real"), cls.links / "hostdir")
os.symlink("/etc/hostname", cls.links / "guest")
os.symlink("real/sub/file.txt", cls.links / "file")
os.symlink("/mnt/links/real", cls.links / "real/up")
(cls.root / "pfx/card/dosdevices").mkdir(parents=True)
os.symlink("/mnt/links", cls.root / "pfx/card/dosdevices/d:")
cls.eqlen_src = tmp / "eqsrcdir"
cls.eqlen_dst = "/" + "d" * (len(str(cls.eqlen_src)) - 1)
eqlen_pfx = cls.eqlen_src / "123/pfx/dosdevices"
@@ -178,44 +159,20 @@ class NativeHookMountTest(unittest.TestCase):
def tearDownClass(cls):
cls.tmp.cleanup()
def run_probe(self, *args, binds=None, mounts=None, syscalls=False):
def run_probe(self, *args, binds=None):
if binds is None:
binds = f"{self.library}:/mnt/library|{self.private}:/mnt/private|{self.eqlen_src}:{self.eqlen_dst}"
hook_env = {"DDNATV_ROOT": str(self.root), "DDNATV_BINDS": binds, "LD_PRELOAD": str(self.hook)}
if mounts is not None:
table = Path(self.tmp.name) / f"mountinfo-{len(list(Path(self.tmp.name).glob('mountinfo-*')))}"
table.write_text("".join(f"{i + 20} 1 0:{i + 40} / {point} rw - {kind} {source} rw\n"
for i, (point, kind, source) in enumerate(mounts)))
hook_env["DDNATV_MOUNTINFO"] = str(table)
env = {k: v for k, v in os.environ.items() if k not in ("LD_PRELOAD", "LOCPATH", "GCONV_PATH")}
if self.prefix:
cmd = list(self.prefix[:1]) + (["-strace"] if syscalls else []) + list(self.prefix[1:])
cmd += [arg for key, value in hook_env.items() for arg in ("-E", f"{key}={value}")]
cmd = list(self.prefix) + [arg for key, value in hook_env.items() for arg in ("-E", f"{key}={value}")]
else:
if syscalls and not shutil.which("strace"):
self.skipTest("no strace")
if syscalls:
cmd = ["strace", "-f", "-qq", "-e", "trace=readlinkat"]
cmd += [arg for key, value in hook_env.items() for arg in ("-E", f"{key}={value}")]
else:
cmd = []
env.update(hook_env)
cmd = []
env.update(hook_env)
out = subprocess.run(cmd + [str(self.probe), *args], env=env, capture_output=True, text=True, timeout=120,
cwd=self.tmp.name)
self.assertEqual(out.returncode, 0, out.stderr)
result = {line.split("\t")[0]: line.split("\t")[1:] for line in out.stdout.splitlines()}
return (result, out.stderr) if syscalls else result
def readlinks_of(self, log, host):
return [line for line in log.splitlines()
if (m := re.search(r'readlinkat\([^,"]*,\s*"([^"]*)"', line)) and m.group(1) == host]
def test_readlink_lines_match_the_queried_path_only(self):
host = "/tmp/x/links/guest"
log = (f'readlinkat(AT_FDCWD, "/proc/self/fd/7", "{host}", 4096) = 18\n'
f'readlinkat(AT_FDCWD, "{host}", "/etc/hostname", 4095) = 13\n'
f'123 readlinkat(-100,"{host}",0x7f00,4095) = -1 errno=22\n')
self.assertEqual(len(self.readlinks_of(log, host)), 2)
return {line.split("\t")[0]: line.split("\t")[1:] for line in out.stdout.splitlines()}
def test_dev_fd_in_a_forked_child_names_the_child_descriptors(self):
out = self.run_probe("fork:/dev/fd", binds="/proc/self/fd:/dev/fd")
@@ -353,135 +310,6 @@ class NativeHookMountTest(unittest.TestCase):
self.assertEqual(result[path], ["1", "library"])
self.assertEqual(result[cd], [GAME])
def test_plain_paths_in_a_mount_reach_their_files(self):
binds = f"{self.links}:/mnt/links"
paths = ["/mnt/links/real/sub/file.txt", "/mnt/links/real/sub/../sub/file.txt", "/mnt/links//real/sub/file.txt"]
result = self.run_probe(*paths, binds=binds)
for path in paths:
self.assertEqual(result[path], ["1", "deep"], path)
def test_links_inside_a_mount_are_followed_in_the_guest_view(self):
binds = f"{self.links}:/mnt/links"
paths = {"/mnt/links/dir/sub/file.txt": ["1", "deep"], "/mnt/links/hostdir/sub/file.txt": ["1", "deep"],
"/mnt/links/file": ["1", "deep"], "/mnt/links/guest": ["1", "rootfs"],
"/mnt/links/real/up/sub/file.txt": ["1", "deep"], "/mnt/links/dir/up/up/sub/file.txt": ["1", "deep"]}
result = self.run_probe(*paths, binds=binds)
for path, want in paths.items():
self.assertEqual(result[path], want, path)
def test_last_link_in_a_mount_is_seen_by_lstat(self):
binds = f"{self.links}:/mnt/links"
cases = {"lstat:/mnt/links/guest": ["1", "1"], "lstat:/mnt/links/dir": ["1", "1"],
"lstat:/mnt/links/dir/sub/file.txt": ["1", "0"], "lstat:/mnt/links/real/sub": ["1", "0"],
"lstat:/mnt/links/dir/missing": ["0", "0"]}
result = self.run_probe(*cases, binds=binds)
for case, want in cases.items():
self.assertEqual(result[case], want, case)
def test_links_above_missing_folders_in_a_mount_are_still_followed(self):
binds = f"{self.links}:/mnt/links"
paths = {"/mnt/links/real/up/sub/deeper/more/leaf.txt": ["1", "leaf"],
"/mnt/links/dir/up/sub/deeper/more/leaf.txt": ["1", "leaf"],
"/mnt/links/real/up/no/such/folder/file.txt": ["0", "-"],
"/mnt/links/dir/up/sub/no/such/file.txt": ["0", "-"]}
result = self.run_probe(*paths, binds=binds)
for path, want in paths.items():
self.assertEqual(result[path], want, path)
def test_paths_below_missing_folders_in_a_mount_stay_missing(self):
binds = f"{self.links}:/mnt/links"
paths = ["/mnt/links/real/sub/no/such/folder/file.txt", "/mnt/links/real/sub/deeper/no/file.txt",
"/mnt/links/no/such/folder", "/mnt/links/real/sub/file.txt/more/deeper",
"/mnt/links/real/sub/deeper/more/leaf.txt/x/y"]
result = self.run_probe(*paths, binds=binds)
for path in paths:
self.assertEqual(result[path], ["0", "-"], path)
self.assertEqual(self.run_probe("/mnt/links/real/sub/deeper/more/leaf.txt", binds=binds)["/mnt/links/real/sub/deeper/more/leaf.txt"], ["1", "leaf"])
def test_missing_paths_in_a_mount_stay_missing(self):
binds = f"{self.links}:/mnt/links"
paths = ["/mnt/links/real/missing", "/mnt/links/dir/missing", "/mnt/links/missing/file.txt",
"/mnt/links/real/sub/file.txt/more"]
result = self.run_probe(*paths, binds=binds)
for path in paths:
self.assertEqual(result[path], ["0", "-"], path)
def links_volume(self):
real = os.path.realpath(self.links)
return real, os.path.dirname(real), os.path.basename(real)
def test_links_in_a_mount_on_a_link_capable_filesystem_are_followed(self):
real, parent, _ = self.links_volume()
binds = f"{self.links}:/mnt/links"
paths = {"/mnt/links/guest": ["1", "rootfs"], "/mnt/links/real/up/sub/file.txt": ["1", "deep"],
"/mnt/links/dir/sub/file.txt": ["1", "deep"]}
tables = [[("/", "ext4", "/dev/root")],
[("/", "ext4", "/dev/root"), (parent, "vfat", "/dev/sdb1"), (real, "f2fs", "/dev/sda2")],
[("/", "ext4", "/dev/root"), (real, "exfat", "/dev/sdb1"), (f"{real}/real", "ext4", "/dev/sda3")],
[("/", "ext4", "/dev/root"), (real, "fuse", "/dev/fuse")],
[("/", "ext4", "/dev/root"), ("/mnt/media_rw/other", "exfat", "/dev/sdb1"), (real, "fuse", "/dev/fuse")],
[("/", "ext4", "/dev/root"), ("/mnt/media_rw/" + os.path.basename(real), "exfat", "/dev/sdb1"),
(real, "fuse", "/dev/sdb9")],
[("/", "ext4", "/dev/root"), ("/mnt/media_rw/" + os.path.basename(real), "exfat", "/dev/sdb1"),
(real, "fuse", "/dev/fuse")],
[("/", "ext4", "/dev/root"), (real, "exfat", "/dev/sdb1"),
(f"{real}/real", "ext4", "/dev/" + "x" * 5000)],
[("/", "ext4", "/dev/root"), (real, "ext4", "/dev/sda2"), (real, "exfat", "/dev/sdb1")]]
for table in tables:
result = self.run_probe(*paths, binds=binds, mounts=table)
for path, want in paths.items():
self.assertEqual(result[path], want, (path, table))
def test_mounts_on_filesystems_without_links_skip_the_link_walk(self):
real, parent, _ = self.links_volume()
binds = f"{self.links}:/mnt/links"
tables = [[("/", "ext4", "/dev/root"), (real, "exfat", "/dev/sdb1")],
[("/", "ext4", "/dev/root"), (parent, "vfat", "/dev/sdb1")],
[("/", "ext4", "/dev/root"), (real, "vfat", "/dev/sdb1"), (f"{real}/real", "exfat", "/dev/sdc1")]]
for table in tables:
result = self.run_probe("/mnt/links/guest", "/mnt/links/real/up/sub/file.txt",
"/mnt/links/real/sub/file.txt", "/mnt/links/real/missing",
"lstat:/mnt/links/real/sub", binds=binds, mounts=table)
self.assertNotEqual(result["/mnt/links/guest"], ["1", "rootfs"], table)
self.assertEqual(result["/mnt/links/real/up/sub/file.txt"], ["0", "-"], table)
self.assertEqual(result["/mnt/links/real/sub/file.txt"], ["1", "deep"], table)
self.assertEqual(result["/mnt/links/real/missing"], ["0", "-"], table)
self.assertEqual(result["lstat:/mnt/links/real/sub"], ["1", "0"], table)
def test_a_mount_table_without_the_mount_keeps_the_link_walk(self):
binds = f"{self.links}:/mnt/links"
paths = {"/mnt/links/guest": ["1", "rootfs"], "/mnt/links/real/up/sub/file.txt": ["1", "deep"]}
result = self.run_probe(*paths, binds=binds, mounts=[])
for path, want in paths.items():
self.assertEqual(result[path], want, path)
def test_drive_links_into_mounts_without_links_skip_the_last_link_check(self):
real, parent, name = self.links_volume()
binds = f"{self.links}:/mnt/links"
tables = [[("/", "ext4", "/dev/root"), (real, "exfat", "/dev/sdb1")],
[("/", "ext4", "/dev/root"), (f"/mnt/media_rw/{name}", "exfat", "/dev/sdb1"), (real, "fuse", "/dev/fuse")]]
for table in tables:
result, log = self.run_probe("/pfx/card/dosdevices/d:/real/sub/file.txt", "/pfx/card/dosdevices/d:/real/missing",
"lstat:/pfx/card/dosdevices/d:/real/sub", binds=binds, mounts=table, syscalls=True)
self.assertEqual(result["/pfx/card/dosdevices/d:/real/sub/file.txt"], ["1", "deep"], table)
self.assertEqual(result["/pfx/card/dosdevices/d:/real/missing"], ["0", "-"], table)
self.assertEqual(result["lstat:/pfx/card/dosdevices/d:/real/sub"], ["1", "0"], table)
for host in (f"{self.links}/real/sub/file.txt", f"{self.links}/real/missing"):
self.assertEqual(self.readlinks_of(log, host), [], (host, table))
def test_drive_links_into_mounts_with_links_still_check_the_last_link(self):
real, _, _ = self.links_volume()
binds = f"{self.links}:/mnt/links"
paths = {"/pfx/card/dosdevices/d:/guest": ["1", "rootfs"], "/pfx/card/dosdevices/d:/file": ["1", "deep"],
"/pfx/card/dosdevices/d:/real/sub/file.txt": ["1", "deep"],
"/pfx/native/dosdevices/z:/etc/hostname": ["1", "rootfs"]}
for table in (None, [("/", "ext4", "/dev/root"), (real, "ext4", "/dev/sda2")]):
result, log = self.run_probe(*paths, binds=binds, mounts=table, syscalls=True)
for path, want in paths.items():
self.assertEqual(result[path], want, (path, table))
self.assertNotEqual(self.readlinks_of(log, f"{self.links}/guest"), [], table)
self.assertNotEqual(self.readlinks_of(log, f"{self.root}/etc/hostname"), [], table)
if __name__ == "__main__":
unittest.main()
+104 -21
View File
@@ -39,8 +39,19 @@ struct create_dumb { uint32_t height, width, bpp, flags, handle, pitch; uint64_t
struct prime_handle { uint32_t handle, flags; int32_t fd; };
struct destroy_dumb { uint32_t handle; };
struct drm_device { char **nodes; int available_nodes; };
struct ion_alloc { uint64_t len; uint32_t heap_id_mask, flags, fd, unused; };
struct ion_legacy_alloc { size_t len, align; uint32_t heap_id_mask, flags; int32_t handle; };
struct ion_fd { int32_t handle, fd; };
struct ion_handle { int32_t handle; };
#define HEAP_DMA 0
#define HEAP_ION 1
#define HEAP_ION_LEGACY 2
#define HEAP_NONE 3
#define HEAP_PATH (HEAP_MODE == HEAP_DMA ? "/dev/dma_heap/system" : HEAP_MODE == HEAP_NONE ? "" : "/dev/ion")
static int heap = -1;
static int ion_handles[8];
int open(const char *path, int flags, ...) {
static int (*real)(const char *, int, ...);
@@ -49,10 +60,62 @@ int open(const char *path, int flags, ...) {
int mode = va_arg(ap, int);
va_end(ap);
if (!real) real = dlsym(RTLD_NEXT, "open");
if (strcmp(path, "/dev/dma_heap/system") == 0) return heap = memfd_create("heap", 0);
if (strcmp(path, HEAP_PATH) == 0) return heap = memfd_create("heap", 0);
if (strcmp(path, "/dev/dma_heap/system") == 0 || strcmp(path, "/dev/ion") == 0) {
errno = ENOENT;
return -1;
}
return real(path, flags, mode);
}
static int new_buffer(uint64_t len) {
int buf = memfd_create("dmabuf", MFD_CLOEXEC);
if (buf < 0 || ftruncate(buf, (off_t)len) != 0) return -1;
return buf;
}
static int heap_ioctl(unsigned long req, void *arg) {
if (HEAP_MODE == HEAP_DMA && req == _IOWR('H', 0, struct heap_alloc)) {
struct heap_alloc *a = arg;
int buf = new_buffer(a->len);
if (buf < 0) return -1;
a->fd = (uint32_t)buf;
return 0;
}
if (HEAP_MODE == HEAP_ION && req == _IOWR('I', 0, struct ion_alloc)) {
struct ion_alloc *a = arg;
int buf = a->heap_id_mask == 1u << 25 ? new_buffer(a->len) : (errno = ENODEV, -1);
if (buf < 0) return -1;
a->fd = (uint32_t)buf;
return 0;
}
if (HEAP_MODE == HEAP_ION_LEGACY && req == _IOWR('I', 0, struct ion_legacy_alloc)) {
struct ion_legacy_alloc *a = arg;
if (a->heap_id_mask != 1u << 25 || a->align != 4096) return errno = ENODEV, -1;
for (int i = 0; i < 8; i++) {
if (ion_handles[i] >= 0) continue;
if ((ion_handles[i] = new_buffer(a->len)) < 0) return -1;
a->handle = i + 1;
return 0;
}
return errno = ENOMEM, -1;
}
if (HEAP_MODE == HEAP_ION_LEGACY && req == _IOWR('I', 4, struct ion_fd)) {
struct ion_fd *s = arg;
if (s->handle < 1 || s->handle > 8 || ion_handles[s->handle - 1] < 0) return errno = EINVAL, -1;
s->fd = fcntl(ion_handles[s->handle - 1], F_DUPFD_CLOEXEC, 0);
return s->fd < 0 ? -1 : 0;
}
if (HEAP_MODE == HEAP_ION_LEGACY && req == _IOWR('I', 1, struct ion_handle)) {
struct ion_handle *h = arg;
if (h->handle < 1 || h->handle > 8 || ion_handles[h->handle - 1] < 0) return errno = EINVAL, -1;
close(ion_handles[h->handle - 1]);
ion_handles[h->handle - 1] = -1;
return 0;
}
return errno = ENOTTY, -1;
}
int ioctl(int fd, unsigned long req, ...) {
static int (*real)(int, unsigned long, ...);
va_list ap;
@@ -60,13 +123,7 @@ int ioctl(int fd, unsigned long req, ...) {
void *arg = va_arg(ap, void *);
va_end(ap);
if (!real) real = dlsym(RTLD_NEXT, "ioctl");
if (fd == heap && req == _IOWR('H', 0, struct heap_alloc)) {
struct heap_alloc *a = arg;
int buf = memfd_create("dmabuf", 0);
if (ftruncate(buf, (off_t)a->len) != 0) return -1;
a->fd = (uint32_t)buf;
return 0;
}
if (fd >= 0 && fd == heap) return heap_ioctl(req, arg);
if (req == _IOW('b', 0, uint64_t)) return 0;
return real(fd, req, arg);
}
@@ -79,6 +136,7 @@ static int call(unsigned long req, void *arg) {
}
int main(void) {
for (int i = 0; i < 8; i++) ion_handles[i] = -1;
if (dd_vdec_open("/dev/video0", O_RDWR) != -2) return 2;
void *drm = SDL_LoadObject("libdrm.so.2");
if (!drm) return 3;
@@ -185,6 +243,7 @@ int main(void) {
unsigned char *m = mmap(NULL, size, PROT_READ, MAP_SHARED, bh.fd, 0);
printf("%ld %u %c%c\n", (long)db.timestamp.tv_usec, db.index, m[0], m[(size_t)4096 * 2304]);
dd_vdec_closed(vfd);
for (int i = 0; i < 8; i++) if (ion_handles[i] >= 0) return 38;
return 0;
}
'''
@@ -242,21 +301,27 @@ class FakeDecoder(threading.Thread):
conn.send(RESULT.pack(9, 0, 1))
HEAP_DMA, HEAP_ION, HEAP_ION_LEGACY, HEAP_NONE = range(4)
class VdecEmulatorTest(unittest.TestCase):
def test_remote_play_client_decodes_through_the_app_socket(self):
def run_client(self, tmp, heap):
driver = tmp / 'driver.c'
driver.write_text(DRIVER)
binary = tmp / 'streaming_client'
subprocess.run(['cc', '-O1', '-pthread', '-DDD_VDEC_ANY_ARCH', f'-DHEAP_MODE={heap}', '-o', str(binary),
str(driver), str(VDEC), str(VENC), '-ldl'], check=True)
sock = tmp / 'venc.sock'
server = FakeDecoder(str(sock))
self.addCleanup(server.listener.close)
server.start()
done = subprocess.run([str(binary)], env=dict(os.environ, DD_VENC_SOCKET=str(sock)),
capture_output=True, text=True, timeout=20)
return done, server
def assert_decodes(self, heap):
with tempfile.TemporaryDirectory() as tmp:
tmp = Path(tmp)
driver = tmp / 'driver.c'
driver.write_text(DRIVER)
binary = tmp / 'streaming_client'
subprocess.run(['cc', '-O1', '-pthread', '-DDD_VDEC_ANY_ARCH', '-o', str(binary), str(driver), str(VDEC),
str(VENC), '-ldl'], check=True)
sock = tmp / 'venc.sock'
server = FakeDecoder(str(sock))
self.addCleanup(server.listener.close)
server.start()
done = subprocess.run([str(binary)], env=dict(os.environ, DD_VENC_SOCKET=str(sock)),
capture_output=True, text=True, timeout=20)
done, server = self.run_client(Path(tmp), heap)
self.assertEqual(done.returncode, 0, done.stdout + done.stderr)
self.assertEqual(done.stdout.split('\n')[:6],
['1 0 bu 1', '2 1 cu 1', '3 2 du 1', '4 0 eu 1', '5 1 fu 1', '6 0 zu'])
@@ -264,6 +329,24 @@ class VdecEmulatorTest(unittest.TestCase):
[(1, 1280, 720, 4096, 2304), (1, 1280, 720, 4096, 2304)])
self.assertEqual([p[:3] for p in server.packets],
[(1, 101, 0), (2, 102, 1), (3, 103, 2), (0, 104, 0), (1, 105, 1), (2, 50, 0)])
return done.stderr
def test_remote_play_client_decodes_through_the_app_socket(self):
self.assertNotIn('ION', self.assert_decodes(HEAP_DMA))
def test_kernels_without_dma_heaps_decode_into_ion_buffers(self):
self.assertIn('Remote Play buffers come from ION', self.assert_decodes(HEAP_ION))
def test_kernels_with_legacy_ion_share_and_free_each_buffer(self):
self.assertIn('Remote Play buffers come from legacy ION', self.assert_decodes(HEAP_ION_LEGACY))
def test_decoding_stays_off_without_any_buffer_heap(self):
with tempfile.TemporaryDirectory() as tmp:
done, server = self.run_client(Path(tmp), HEAP_NONE)
self.assertEqual(done.returncode, 3, done.stdout + done.stderr)
self.assertIn('no /dev/dma_heap/system (No such file or directory) or /dev/ion (No such file or directory), '
'Remote Play decoding stays off', done.stderr)
self.assertEqual(server.configs, [])
def test_other_programs_keep_the_real_libdrm(self):
with tempfile.TemporaryDirectory() as tmp:
@@ -0,0 +1,18 @@
{
"$schema": "https://github.com/fastfetch-cli/fastfetch/raw/dev/doc/json_schema.json",
"logo": {
"type": "file",
"source": "/usr/share/droiddeck/fastfetch/logo.txt",
"color": {
"1": "38;2;255;255;255",
"2": "38;2;26;159;255"
},
"padding": { "right": 3 }
},
"modules": [
"title", "separator", "os", "host", "kernel", "uptime", "packages", "shell",
"display", "de", "wm", "wmtheme", "theme", "icons", "font", "cursor",
"terminal", "cpu", "gpu", "memory", "swap", "disk", "battery", "locale",
"break", "colors"
]
}
+33 -154
View File
@@ -154,7 +154,7 @@ new file mode 100755
index 0000000..d43c5fc
--- /dev/null
+++ b/crates/xodus-cli/src/commands/legacy_install.rs
@@ -0,0 +1,1527 @@
@@ -0,0 +1,1406 @@
+//! Installs a legacy Store title: resolve, license, download, extract.
+//!
+//! `streaming` only understands MSIXVC, where the container *is* the game and
@@ -739,7 +739,7 @@ index 0000000..d43c5fc
+ progress.bytes(high, total);
+ };
+ if extracted != ExitCode::SUCCESS {
+ return fail("extract-failed", "Could not unpack the package; retrying may require downloading the bundle again because containers are removed to save disk space");
+ return fail("extract-failed", "Could not unpack the package; the download is kept for a retry");
+ }
+ // Drop each container as soon as it is unpacked: a full title is tens of
+ // gigabytes, and holding the archive and its contents at once can fill
@@ -813,24 +813,15 @@ index 0000000..d43c5fc
+ let Ok(text) = std::fs::read_to_string(manifest) else {
+ return Vec::new();
+ };
+ use quick_xml::events::Event;
+ let mut reader = quick_xml::Reader::from_str(&text);
+ let mut names: Vec<String> = Vec::new();
+ loop {
+ match reader.read_event() {
+ Ok(Event::Start(tag)) | Ok(Event::Empty(tag)) if tag.local_name().as_ref() == "PackageDependency" => {
+ for attribute in tag.attributes().flatten() {
+ if attribute.key.local_name().as_ref() != "Name" { continue; }
+ let Ok(name) = attribute.unescape_value() else { continue };
+ let name = name.trim();
+ if !name.is_empty() && !names.iter().any(|seen| seen == name) {
+ names.push(name.to_string());
+ }
+ }
+ }
+ Ok(Event::Eof) => break,
+ Ok(_) => {}
+ Err(_) => return Vec::new(),
+ for chunk in text.split("<PackageDependency").skip(1) {
+ let Some(tag) = chunk.split('>').next() else { continue };
+ let Some(start) = tag.find("Name=\"") else { continue };
+ let rest = &tag[start + "Name=\"".len()..];
+ let Some(end) = rest.find('"') else { continue };
+ let name = rest[..end].trim();
+ if !name.is_empty() && !names.iter().any(|seen| seen == name) {
+ names.push(name.to_string());
+ }
+ }
+ names
@@ -1003,8 +994,8 @@ index 0000000..d43c5fc
+ for folder in level {
+ let manifest = folder.join(LEGACY_MANIFEST);
+ if manifest.is_file() {
+ let text = std::fs::read_to_string(&manifest).unwrap_or_default();
+ if identity_is_x64(&text) {
+ let text = std::fs::read_to_string(&manifest).unwrap_or_default().to_ascii_lowercase();
+ if text.contains("processorarchitecture=\"x64\"") {
+ return Some(folder);
+ }
+ }
@@ -1020,24 +1011,6 @@ index 0000000..d43c5fc
+ None
+}
+
+/// Reads ProcessorArchitecture only from an Identity element, ignoring comments and text.
+fn identity_is_x64(text: &str) -> bool {
+ use quick_xml::events::Event;
+ let mut reader = quick_xml::Reader::from_str(text);
+ loop {
+ match reader.read_event() {
+ Ok(Event::Start(tag)) | Ok(Event::Empty(tag)) if tag.local_name().as_ref() == "Identity" => {
+ return tag.attributes().flatten().any(|attribute| {
+ attribute.key.local_name().as_ref() == "ProcessorArchitecture"
+ && attribute.unescape_value().is_ok_and(|value| value.eq_ignore_ascii_case("x64"))
+ });
+ }
+ Ok(Event::Eof) | Err(_) => return false,
+ Ok(_) => {}
+ }
+ }
+}
+
+/// The Windows Update category of the framework's x64 package, or of whichever
+/// package the product lists first when no package names an architecture.
+fn framework_category(document: &serde_json::Value) -> Option<String> {
@@ -1084,18 +1057,8 @@ index 0000000..d43c5fc
+/// and records what it copied so a later attempt can take exactly that back.
+fn copy_libraries(from: &Path, to: &Path) -> Result<(), String> {
+ let mut copied: Vec<String> = Vec::new();
+ if let Err(error) = copy_libraries_into(from, to, &mut copied) {
+ for name in &copied {
+ let _ = std::fs::remove_file(to.join(name));
+ }
+ return Err(error);
+ }
+ if let Err(error) = std::fs::write(from.join(COPIED), copied.join("\n")) {
+ for name in &copied {
+ let _ = std::fs::remove_file(to.join(name));
+ }
+ return Err(format!("framework copy list failed: {error}"));
+ }
+ copy_libraries_into(from, to, &mut copied)?;
+ std::fs::write(from.join(COPIED), copied.join("\n")).map_err(|error| format!("framework copy list failed: {error}"))?;
+ Ok(())
+}
+
@@ -1116,16 +1079,7 @@ index 0000000..d43c5fc
+ if target.exists() {
+ continue;
+ }
+ let temporary = to.join(format!(".{}.copying-{}", file_name.to_string_lossy(), std::process::id()));
+ let _ = std::fs::remove_file(&temporary);
+ if let Err(error) = std::fs::copy(&path, &temporary) {
+ let _ = std::fs::remove_file(&temporary);
+ return Err(format!("framework copy failed: {error}"));
+ }
+ if let Err(error) = std::fs::rename(&temporary, &target) {
+ let _ = std::fs::remove_file(&temporary);
+ return Err(format!("framework publish failed: {error}"));
+ }
+ std::fs::copy(&path, &target).map_err(|error| format!("framework copy failed: {error}"))?;
+ copied.push(file_name.to_string_lossy().into_owned());
+ }
+ Ok(())
@@ -1165,19 +1119,10 @@ index 0000000..d43c5fc
+ ));
+ }
+ let inner = candidates.remove(0);
+ let entries: Vec<_> = std::fs::read_dir(&inner)
+ for entry in std::fs::read_dir(&inner)
+ .map_err(|error| format!("Could not list the package folder: {error}"))?
+ .filter_map(Result::ok)
+ .collect();
+ if !updating {
+ for entry in &entries {
+ let name = entry.file_name();
+ if !is_package_metadata(&name) && destination.join(&name).exists() {
+ return Err(format!("Extraction would overwrite {}", destination.join(name).display()));
+ }
+ }
+ }
+ for entry in entries {
+ {
+ let name = entry.file_name();
+ let target = destination.join(&name);
+ let metadata = is_package_metadata(&name);
@@ -1197,41 +1142,16 @@ index 0000000..d43c5fc
+ if !existing.is_empty() && !updating && !metadata {
+ return Err(format!("Extraction would overwrite {}", target.display()));
+ }
+ let mut backups: Vec<(PathBuf, PathBuf)> = Vec::new();
+ for (index, old) in existing.iter().enumerate() {
+ let backup = destination.join(format!(".droiddeck-replace-backup-{}-{}", std::process::id(), index));
+ if let Err(error) = std::fs::rename(old, &backup) {
+ let mut restore_error = None;
+ for (original, saved) in backups.iter().rev() {
+ if let Err(error) = std::fs::rename(saved, original) {
+ restore_error = Some(error);
+ break;
+ }
+ }
+ if let Some(restore_error) = restore_error {
+ return Err(format!("Could not preserve the installed entry ({error}); restoring a backup also failed ({restore_error})"));
+ }
+ return Err(format!("Could not preserve the installed entry: {error}"));
+ }
+ backups.push((old.clone(), backup));
+ }
+ if let Err(error) = std::fs::rename(entry.path(), &target) {
+ let mut restore_error = None;
+ for (original, saved) in backups.iter().rev() {
+ if let Err(error) = std::fs::rename(saved, original) {
+ restore_error = Some(error);
+ break;
+ }
+ }
+ if let Some(restore_error) = restore_error {
+ return Err(format!("Could not move extracted file ({error}); restoring a backup also failed ({restore_error})"));
+ }
+ return Err(format!("Could not move an extracted file: {error}"));
+ }
+ for (_, backup) in backups {
+ let removed = if backup.is_dir() { std::fs::remove_dir_all(&backup) } else { std::fs::remove_file(&backup) };
+ removed.map_err(|error| format!("Could not remove replaced backup: {error}"))?;
+ for old in existing {
+ let replaced = if old.is_dir() {
+ std::fs::remove_dir_all(&old)
+ } else {
+ std::fs::remove_file(&old)
+ };
+ replaced.map_err(|error| format!("Could not replace an installed file: {error}"))?;
+ }
+ std::fs::rename(entry.path(), &target)
+ .map_err(|error| format!("Could not move an extracted file: {error}"))?;
+ }
+ std::fs::remove_dir(&inner).map_err(|error| format!("Could not remove the package folder: {error}"))?;
+ Ok(())
@@ -1245,9 +1165,7 @@ index 0000000..d43c5fc
+ if applications.len() > 1 {
+ let x64: Vec<PathBuf> = applications
+ .iter()
+ .filter(|folder| {
+ identity_is_x64(&manifest_text_original(folder))
+ })
+ .filter(|folder| manifest_text(folder).contains("processorarchitecture=\"x64\""))
+ .cloned()
+ .collect();
+ if x64.len() == 1 {
@@ -1258,41 +1176,22 @@ index 0000000..d43c5fc
+}
+
+fn manifest_text(folder: &Path) -> String {
+ manifest_text_original(folder).to_ascii_lowercase()
+}
+
+fn manifest_text_original(folder: &Path) -> String {
+ [LEGACY_MANIFEST, MANIFEST]
+ .iter()
+ .filter_map(|name| std::fs::read_to_string(folder.join(name)).ok())
+ .collect::<Vec<_>>()
+ .join("\n")
+ .join("
+")
+ .to_ascii_lowercase()
+}
+
+fn declares_application(folder: &Path) -> bool {
+ use quick_xml::events::Event;
+ for (name, expected) in [
+ (LEGACY_MANIFEST, "Application"),
+ (MANIFEST, "Application"),
+ ("MicrosoftGame.config", "Executable"),
+ ] {
+ let Ok(text) = std::fs::read_to_string(folder.join(name)) else { continue };
+ let mut reader = quick_xml::Reader::from_str(&text);
+ loop {
+ match reader.read_event() {
+ Ok(Event::Start(tag)) | Ok(Event::Empty(tag))
+ if tag.local_name().as_ref() == expected => return true,
+ Ok(Event::Eof) | Err(_) => break,
+ Ok(_) => {}
+ }
+ }
+ }
+ false
+ let text = manifest_text(folder);
+ opens_element(&text, "<application") || opens_element(&text, "<executable")
+}
+
+/// Whether [text] opens [tag] as its own element, so `<Application Id=` and an attribute on the next
+/// line count and `<Applications>` does not. Used by the focused parser test only.
+#[cfg(test)]
+/// line count and `<Applications>` does not.
+fn opens_element(text: &str, tag: &str) -> bool {
+ text.match_indices(tag).any(|(at, _)| {
+ text[at + tag.len()..].chars().next().is_some_and(|next| next.is_whitespace() || next == '>' || next == '/')
@@ -1542,23 +1441,6 @@ index 0000000..d43c5fc
+ }
+
+ #[test]
+ fn x64_identity_ignores_architecture_text_in_comments_and_other_elements() {
+ assert!(!identity_is_x64(r#"<Package><!-- ProcessorArchitecture = "x64" --><Identity ProcessorArchitecture="x86"/></Package>"#));
+ assert!(!identity_is_x64(r#"<Package><Other ProcessorArchitecture="x64"/><Identity ProcessorArchitecture="x86"/></Package>"#));
+ assert!(identity_is_x64(r#"<Package><Identity ProcessorArchitecture = 'x64'/></Package>"#));
+ }
+
+ #[test]
+ fn application_scan_ignores_application_elements_inside_comments() {
+ let root = scratch("commented-app");
+ std::fs::write(root.join(LEGACY_MANIFEST), r#"<Package><!-- <Application Id="fake"/> --><Applications/></Package>"#).unwrap();
+ assert!(!declares_application(&root));
+ std::fs::write(root.join("MicrosoftGame.config"), r#"<Game><!-- <Executable Name="fake.exe"/> --></Game>"#).unwrap();
+ assert!(!declares_application(&root));
+ std::fs::remove_dir_all(&root).ok();
+ }
+
+ #[test]
+ fn hoist_still_refuses_when_several_packages_declare_an_application() {
+ let root = scratch("ambiguous-applications");
+ for name in ["One", "Two"] {
@@ -1583,9 +1465,6 @@ index 0000000..d43c5fc
+
+ assert!(hoist(&root).unwrap_err().contains("would overwrite"));
+ assert_eq!(std::fs::read(root.join("Game.exe")).unwrap(), b"other");
+ assert!(hoist(&root).unwrap_err().contains("would overwrite"));
+ assert_eq!(std::fs::read(root.join("Game.exe")).unwrap(), b"other");
+ assert!(!root.join(LEGACY_MANIFEST).exists(), "failed hoist must not partially publish the manifest");
+ std::fs::remove_dir_all(&root).ok();
+ }
+