Compare commits

...
16 Commits
Author SHA1 Message Date
MaxsTechReview 46f99b9e08 fix(nativeguest): Downloads and Documents are writable in the desktop file manager (#3274)
fix(nativeguest): shared storage files are root's like the SD card's

Android's internal shared storage reports its files as owned by the media
provider with the media_rw group, so desktop file managers saw Downloads and
Documents as someone else's and showed them read-only, with rename, delete and
new folder unavailable. Files in the media_rw group are now presented as
owned by root, as the SD card already is; the group is kept.
2026-11-26 10:30:32 -05:00
MaxsTechReview dcb1a3001b fix(desktop): Downloads, Documents and game folder links work again without proot (#3273)
Links made in a proot session store the guest path as their target, which the
kernel cannot follow in the middle of a path once the session runs without
proot: the folders listed, but nothing inside them could be opened or created.
The desktop setup now makes a link again when it cannot be walked into, so it
is stored in the form the current mode follows.
2026-11-26 10:30:28 -05:00
MaxsTechReview dbfcd764f3 perf(nativeguest): keep relative parent walks relative inside mounts without links (#3249)
* perf(nativeguest): keep relative parent walks relative inside mounts without links

A relative path with .. made the hook rebuild the full absolute host
path, so every component was looked up again from the root of the card.
Inside a mount that cannot hold symlinks, a path that never climbs
above the mount resolves the same way relative to the working
directory, so the kernel now gets it unchanged.

* Keep the absolute walk when another guest bind sits inside the mount

* Check every guest path of the card's folder for nested binds

* Keep the absolute walk inside the rootfs and under identity binds

* Keep the absolute walk when two binds share a guest path
2026-11-26 09:48:56 -05:00
MaxsTechReview 96e4bd4eab fix(fex): x86-64 programs on Wayland render on the GPU (#3174)
* fix(fex): x86-64 programs on Wayland render on the GPU

* fix(fex): address review on the Wayland and EGL thunks

Keep the GLES overlay on the 64-bit EGL thunk only, filter EGL extensions
whose entrypoints the guest lacks, accept EGLDeviceEXT displays, make the
Wayland display check thread-safe, bound event signature copies, reject a
second listener without freeing the first and guard wl_array_add growth.

The FEX updater now removes thunk libraries a new build no longer ships, so
an older 32-bit Wayland or EGL thunk cannot be enabled by the new config.

* fix(fex): check every EGL extension entrypoint and every host device

EGL_EXTENSIONS now hides an extension unless the guest exports all of its
entrypoints, using a table built from the EGL registry. eglGetDisplay asks
the host for its device count before matching EGLDeviceEXT handles.

* fix(fex): pick the eglGetDisplay platform the way Mesa does

A legacy eglGetDisplay handle now follows EGL_PLATFORM or EGL_DISPLAY first,
then Wayland detection, and only then the X11 mapping, so device handles no
longer depend on enumerating host devices.
2026-11-26 05:34:42 -05:00
Kurt Himebauch d788afc126 fix(gamescope): enter Steam at the corner it is reset to (#3253)
* fix(gamescope): enter Steam at the corner it is reset to

* docs(gamescope): explain the corner entry patch
2026-11-26 02:28:42 -05:00
Kurt Himebauch 50a7b1b9f5 fix(compositor): report a client's first hidden cursor (#3245) 2026-11-25 23:23:38 -05:00
MaxsTechReview 79027970e1 perf(nativeguest): skip the symlink walk for plain paths and link-less SD card mounts (#3233)
* Skip per-component link walk for plain paths in binds

Open the translated host path with O_PATH and compare /proc/self/fd
against it; when no link was crossed, return it without walking each
component. follow_guest_link reuses the result instead of rewriting the
path a second time. Cuts stat/open on deep SD-card files from about
5.7 ms to 1.4 ms.

* Test link handling and plain paths inside native binds

* Check missing paths in binds from their deepest existing folder

A path below folders that do not exist fell back to a readlink of every component, one full lookup each; on a FUSE card that cost up to 8 ms per probe. The check now climbs to the deepest folder that exists and verifies that one, so links before it are still followed and nothing below it can be a link.

* Skip the link walk for mounts on file systems that cannot hold links

A mount whose source is on vfat or exFAT, or on a FUSE volume backed by
one (Android's SD card), cannot hold symbolic links, so every path in it
is plain. Each mount checks the mount table once, then its paths skip
the link walk and the follow readlink. On the SD card this removes about
two FUSE lookups per file operation.

* Keep the link walk for truncated mount tables and non-volume FUSE mounts

* Skip the last link check for drive paths into mounts that hold no links

Wine reaches games on an SD card library through a drive link in the
prefix (dosdevices/d: -> /mnt/droiddeck-sd). Every stat, open and
access that follows links paid one more readlinkat on the card path
after the rewrite had already found the mount holds no links, and on
Android's storage layer each extra lookup of a deep path costs about a
millisecond. The rewrite now keeps the plain answer it already has, so
the check runs only where a link can exist.

* Keep the link walk when stacked mounts share the covering path

* Trace readlinkat without loading the hook into strace and match the queried path
2026-11-25 22:56:17 -05:00
MaxsTechReview 6e9853add5 fix(steam): follow the device network with live offline mode switching (#3230)
* Start Steam offline automatically when the device has no internet

OfflineMode now reads Steam's own WantsOfflineMode as the user's choice, so going offline inside Steam shows on DroidDeck's toggle and is no longer reset on the next start. When Android has no validated internet, Steam starts in offline mode for that start only and goes back online once a connection returns, without changing the saved choice.

* Test automatic and manual Steam offline mode

* Switch Steam offline and back live when the network drops or returns mid-session

* Apply Steam offline changes after a game exits and when the session resumes

* Add an Auto offline mode toggle above Offline mode

* Keep an automatic offline automatic when Steam cannot be reached, and reconcile once when the session starts

* Keep a manual Offline choice made while a live switch is in flight

* Read the saved offline state and write it under one lock

* Check the Auto setting inside the offline state lock

* Keep Steam's current offline state when Auto is turned off
2026-11-25 22:56:13 -05:00
Kurt Himebauch 07f2dc8e8f fix(desktop): fastfetch shows the device, SoC and data disk (#3231)
fix(desktop): fastfetch shows the device, SoC and data disk instead of the reference board and Android mounts
2026-11-25 21:10:51 -05:00
LunaDL 0f924aebb0 fix(xbox): add legacy Store installer and fix SteamOS panel migration (#3229)
* Separate unrelated droiddeck-desktop fix from zoom PR

* Separate unrelated test_desktop_steamos_panel.py fix from zoom PR

* Separate unrelated droiddeck-legacy-install.patch fix from zoom PR

* Fix legacy installer review findings

* Prevent partial framework DLL copies

* Fix legacy installer review findings

* Correct embedded installer patch hunk size

* Test SteamOS panel migration failure paths

* Fix newline literals in panel regression tests

* Fix embedded declaration and retry message

* Fix Xbox package selection and rollback

* Ignore commented Xbox package declarations
2026-11-25 21:04:20 -05:00
Kurt Himebauch 8ec499ae3f fix(session): relaunch into a fresh activity so Switch to Desktop does not leave the loader up (#3227) 2026-11-25 17:34:53 -05:00
The412Banner 53c1933ac8 feat(steam): DroidDeck-Proton first, Valve's ARM64 Proton only when needed (#3217)
New Steam setting "Valve Proton only when needed", on by default. While it is on and DroidDeck-Proton has not been removed by the user:

- the app installs DroidDeck-Proton before the client first starts instead of seeding Valve's Proton Experimental (ARM64) (2.09 GB on disk, 398 MB download); a stop request cancels that download
- the session no longer asks the client for appid 4427310 at every start
- the live helper fetches it only once the default or a title is set to a tool built from it ("Proton Experimental ARM64 (Compatible)"), or while no DroidDeck-Proton build is installed

FEX and the Steam Linux Runtimes are still fetched as before. An installed copy of Valve's Proton is kept and updated. Off, or with DroidDeck-Proton declined, everything works as before (DD_VALVE_PROTON=1). Fresh install on a Pocket FIT: 8.28 GB after first Steam start and tool downloads, was 10.4 GB.
2026-11-25 15:54:48 -05:00
The412Banner 4df3f775e1 fix(runtime): first-run setup no longer crashes when the app is in the background (#3212)
With targetSdk 34, Android refuses startForeground() while the app is in the background. RuntimeInstallService called it unguarded on the main thread, so the refusal (ForegroundServiceStartNotAllowedException) killed the app during first-run setup when the runtime finished while DroidDeck-Proton was still downloading (RuntimeInstallService.kt:49 via onStartCommand :22).

Both foreground starts now catch the refusal: a package hold stops the service and the downloads go on in the app, as when startForegroundService() itself is refused; a runtime install or removal still runs, without progress notifications.
2026-11-25 15:15:49 -05:00
Kurt Himebauch 6b570c573b fix(tabs): Apps tab shows when DroidDeck is the home app (#3215)
fix(tabs): Apps tab sits in the rail but hidden, and shows when DroidDeck becomes the home app
2026-11-25 14:47:18 -05:00
Kurt Himebauch d164749a7f fix(ci): save Robolectric's Android jars even when the test step fails on a Maven 429 (#3209) 2026-11-25 13:33:28 -05:00
Kurt Himebauch 50c5fd79f7 docs: point README downloads at 0.7.11 (#3210) 2026-11-25 13:25:43 -05:00
86 changed files with 3106 additions and 124 deletions

No files matched your search

+36 -3
View File
@@ -754,12 +754,17 @@ jobs:
ln -sfn "$(cd "$jars" && pwd)" "$m2"
echo "cache=true" >> "$GITHUB_OUTPUT"
fi
- name: Cache Robolectric's Android jars
- name: Restore Robolectric's Android jars
id: robolectric-cache
if: steps.robolectric-jars.outputs.cache == 'true'
uses: actions/cache@v4
uses: actions/cache/restore@v4
with:
path: ../robolectric-jars
key: robolectric-android-all-v2-${{ steps.robolectric.outputs.version }}
key: robolectric-android-all-v3-${{ steps.robolectric.outputs.version }}-${{ github.run_id }}
restore-keys: robolectric-android-all-v3-${{ steps.robolectric.outputs.version }}-
- name: Count the restored Robolectric jars
if: steps.robolectric-jars.outputs.cache == 'true'
run: echo "ROBOLECTRIC_JARS_BEFORE=$(find "$GITHUB_WORKSPACE/../robolectric-jars" -name '*.jar' | wc -l)" >> "$GITHUB_ENV"
- name: Unit tests
id: unit-tests
env:
@@ -770,6 +775,34 @@ jobs:
mkdir -p app/build
./gradlew testReleaseUnitTest --console=plain --info --stacktrace -Drobolectric.logging=stderr -PndkVersion="$NDK_VERSION" 2>&1 | tee app/build/unit-tests.log
# actions/cache only saves when the job succeeds, so a run whose tests died on a Maven 429 never filled the cache.
# Save the complete jars even after a failed test step, when this run added some; a partial download is dropped first.
- name: Save Robolectric's Android jars
id: robolectric-jars-final
if: always() && steps.robolectric-jars.outputs.cache == 'true'
run: |
python3 - <<'PY'
import glob, os, zipfile
root = os.path.join(os.environ['GITHUB_WORKSPACE'], '..', 'robolectric-jars')
for f in glob.glob(os.path.join(root, '**', '*'), recursive=True):
if not os.path.isfile(f):
continue
try:
ok = f.endswith('.jar') and zipfile.ZipFile(f).testzip() is None
except Exception:
ok = False
if not ok:
os.remove(f)
PY
after=$(find "$GITHUB_WORKSPACE/../robolectric-jars" -name '*.jar' | wc -l)
[ "$after" -gt "${ROBOLECTRIC_JARS_BEFORE:-0}" ] && echo "save=true" >> "$GITHUB_OUTPUT" || true
- name: Store Robolectric's Android jars
if: always() && steps.robolectric-jars-final.outputs.save == 'true'
uses: actions/cache/save@v4
with:
path: ../robolectric-jars
key: robolectric-android-all-v3-${{ steps.robolectric.outputs.version }}-${{ github.run_id }}
- name: Upload unit test diagnostics
id: unit-test-diagnostics
if: always() && steps.unit-tests.outcome != 'skipped'
+3 -2
View File
@@ -10,7 +10,7 @@ DroidDeck brings the SteamOS experience to Android: Steam Gaming Mode, full Linu
<p align="center"><b>100% open source. No ads. No Subscriptions. No telemetry. No proprietary components. No source withheld.</b></p>
<p align="center">
<a href="https://github.com/Droid-Deck/DroidDeck/releases/download/0.7.1/DroidDeck-0.7.1.apk"><img src="https://img.shields.io/badge/Download-DroidDeck%200.7.1%20APK-3DDC84?style=for-the-badge&logo=android&logoColor=white" alt="Download DroidDeck 0.7.1"></a>
<a href="https://github.com/Droid-Deck/DroidDeck/releases/download/0.7.11/DroidDeck-0.7.11.apk"><img src="https://img.shields.io/badge/Download-DroidDeck%200.7.11%20APK-3DDC84?style=for-the-badge&logo=android&logoColor=white" alt="Download DroidDeck 0.7.11"></a>
<a href="https://discord.gg/JRGAvawjsm"><img src="https://img.shields.io/badge/Discord-Join%20us-5865F2?style=for-the-badge&logo=discord&logoColor=white" alt="Join the DroidDeck Discord"></a>
</p>
@@ -38,7 +38,7 @@ DroidDeck brings the SteamOS experience to Android: Steam Gaming Mode, full Linu
1. Android 9 or newer on Adreno 730 or newer, or any 8xx. Adreno 6xx, Mali, Xclipse and PowerVR are experimental. Adreno 710 is currently unsupported. No root needed.
2. About 3 GB free for the runtime, plus 1.1 GB for the desktop and emulators.
3. Install the [APK](https://github.com/Droid-Deck/DroidDeck/releases/download/0.7.1/DroidDeck-0.7.1.apk), install the Linux runtime, press **Play** and sign in to Steam.
3. Install the [APK](https://github.com/Droid-Deck/DroidDeck/releases/download/0.7.11/DroidDeck-0.7.11.apk), install the Linux runtime, press **Play** and sign in to Steam.
4. On Android 14 and newer, turn on **Disable child process restrictions** in Developer options. On Android 12 and 13, Steam's first launch shows a **Fix it for me** button that walks you through it.
Smart glasses setup is in the [support matrix](docs/smart-glasses-support.md). Release notes are in [docs/releases](docs/releases).
@@ -68,6 +68,7 @@ DroidDeck is [GPL-3.0](LICENSE). Steam and Proton belong to Valve Corporation. V
- Runtime, shim, input and controller work build on WinNative and Bannerlator by maxjivi05.
- mmap ring buffer controller input by ribbit384 ([WinNative #345](https://github.com/WinNative-Emu/WinNative/pull/345)).
- [FEX](https://github.com/FEX-Emu/FEX) (MIT) runs x86 code. DroidDeck's build puts the platform name under `AT_PLATFORM` so [sharun](https://github.com/VHSgunzo/sharun) AppImages by VHSgunzo (MIT) start through its [userland-execve](https://crates.io/crates/userland-execve) loader (MIT), and its GL thunk hands X errors to the program's own error handler. FEX's code disk cache was checked in its source. The fix for host stack left behind when a program leaves a signal handler without returning follows the approach suggested in [FEX-Emu/FEX#2487](https://github.com/FEX-Emu/FEX/issues/2487). The host stack fix for system calls that end a block is a backport of Ryan Houdek's [FEX-Emu/FEX#6122](https://github.com/FEX-Emu/FEX/pull/6122).
- x86-64 programs on Wayland reach the GPU through FEX's Wayland client, wayland-egl and EGL thunks. The guest `wl_list` and `wl_array` helpers follow [libwayland](https://gitlab.freedesktop.org/wayland/wayland)'s `src/wayland-util.c` (MIT). The EGL extension table comes from the [Khronos EGL registry](https://github.com/KhronosGroup/EGL-Registry) (Apache-2.0) and Mesa's `egl_other.xml` (MIT).
- x86 AppImages, and arm64 ones whose runtime can't unpack on Android, are unpacked with [uruntime](https://github.com/VHSgunzo/uruntime) by VHSgunzo (MIT), shipped unmodified with its licence.
- DwarFS AppImages are unpacked without proot by `dwarfsextract` from [DwarFS](https://github.com/mhx/dwarfs) by Marcus Holland-Moritz (MIT), the release binary uruntime embeds, taken out of its self-extracting wrapper and shipped with its licence.
- x86 programs linking OpenSSL 3 use the copy in the [Steam Linux Runtime 4.0](https://gitlab.steamos.cloud/steamrt/steamrt). x86 Linux games get the `/etc/asound.conf` that [pressure-vessel](https://gitlab.steamos.cloud/steamrt/steam-runtime-tools) writes.
@@ -620,7 +620,8 @@ static void cursor_publish_shown(void) {
static void cursor_publish_hidden(void) {
pthread_mutex_lock(&g_cursor_lock);
if (!g_cursor_hidden) { g_cursor_hidden = 1; g_cursor_serial++; }
// 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++; }
pthread_mutex_unlock(&g_cursor_lock);
}
@@ -141,6 +141,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
private var glThread by mutableStateOf(true)
private var noGlError by mutableStateOf(true)
private var returnAfterGame by mutableStateOf(true)
private var valveProtonOnDemand by mutableStateOf(true)
private var shaderPrecache by mutableStateOf<Boolean?>(null)
private var steamRepairQueued by mutableStateOf(false)
private var mangoapp by mutableStateOf(true)
@@ -168,6 +169,7 @@ 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())
@@ -1415,7 +1417,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,
offlineAccount = offlineAccount, offline = offline, offlineAuto = offlineAuto,
frameGenLabel = frameGenLabel, romsDir = romsDir, logsEnabled = logsEnabled,
enhancedDiagnosticsArmed = enhancedDiagnosticsArmed,
gameDebugLogsEnabled = gameDebugLogsEnabled, gameDebugLogsNeedsRestart = gameDebugLogsNeedsRestart,
@@ -1753,6 +1755,11 @@ 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)
@@ -2384,6 +2391,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
homeScreenEnabled = HomeApp.isHomeScreenEnabled(this)
homeAppSelected = homeScreenEnabled && HomeApp.isDefault(this)
defaultHomeLabel = HomeApp.defaultLabel(this)
com.droiddeck.launcher.ui.NavTabs.syncHomeApps(this, homeAppSelected)
refreshAndroidApps()
integrationState = readIntegration()
}
@@ -2784,6 +2792,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
steamClientArch = if (mode == SessionService.MODE_STEAM) steamClientArch else null,
returnAfterGame = if (mode == SessionService.MODE_STEAM) returnAfterGame else null,
shaderPrecache = if (mode == SessionService.MODE_STEAM) shaderPrecache else null,
valveProtonOnDemand = if (mode == SessionService.MODE_STEAM) valveProtonOnDemand else null,
steamRepairQueued = steamRepairQueued,
mangoapp = mangoapp,
steamController = if (mode == SessionService.MODE_STEAM) steamController else null,
@@ -2891,6 +2900,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
onMangoapp = { on -> SessionPrefs.setMangoapp(this, on); mangoapp = on },
onReturnAfterGame = { on -> SessionPrefs.setReturnAfterGame(this, on); returnAfterGame = on },
onShaderPrecache = { on -> SessionPrefs.setShaderPrecache(this, on); shaderPrecache = on },
onValveProtonOnDemand = { on -> SessionPrefs.setValveProtonOnDemand(this, on); valveProtonOnDemand = on },
onSteamController = { id -> SessionPrefs.setSteamController(this, id); steamController = id },
onStartupSession = { id ->
SessionPrefs.setStartupSession(this, id)
@@ -3163,6 +3173,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
steamRepairQueued = SteamRepair.queued(this)
mangoapp = SessionPrefs.mangoapp(this)
returnAfterGame = SessionPrefs.returnAfterGame(this)
valveProtonOnDemand = SessionPrefs.valveProtonOnDemand(this)
loadShaderPrecache(mode)
steamController = SessionPrefs.steamController(this)
startupSession = SessionPrefs.startupSession(this)
@@ -3314,6 +3325,7 @@ 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)
@@ -49,7 +49,7 @@ internal class ProtonMenu(
@VisibleForTesting internal var latestCheck: (Boolean) -> Boolean = { force -> ProtonExtras.checkLatest(activity, force) }
@VisibleForTesting internal var experimentalRefresh: () -> List<ExperimentalProtons.Release>? = { ExperimentalProtons.refresh(activity) }
@VisibleForTesting internal var installer: (ProtonExtras.Tool, (String, Int) -> Unit) -> String? =
{ tool, progress -> ProtonExtras.install(activity, tool, progress) }
{ tool, progress -> ProtonExtras.install(activity, tool, onProgress = progress) }
fun installProton(id: String, automatic: Boolean = false) {
val tool = ProtonExtras.tools.firstOrNull { it.id == id } ?: return
@@ -2834,6 +2834,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
private fun installProton(): String? {
uiHandler.post { loading.percent = -1; loading.say(getString(PROTON_LINES.downloading), PROTON_LINES.topic, readable = true) }
if (com.droiddeck.launcher.session.SessionPrefs.ownProtonFirst(this)) return installOwnProton()
val catalog = com.droiddeck.launcher.runtime.DesktopCatalog
val cancellation = com.droiddeck.launcher.core.Downloader.Cancellation { SessionState.stopRequested }
SessionState.installCancellation = cancellation
@@ -2846,6 +2847,24 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
}
private fun installOwnProton(): String? {
val extras = com.droiddeck.launcher.session.ProtonExtras
while ((extras.prefetching || extras.installInProgress) && !SessionState.stopRequested) {
try { Thread.sleep(250) } catch (_: InterruptedException) { Thread.currentThread().interrupt(); return "interrupted" }
}
if (SessionState.stopRequested) return "cancelled"
if (!com.droiddeck.launcher.runtime.DesktopCatalog.ownProtonMissing(this)) return null
val cancellation = com.droiddeck.launcher.core.Downloader.Cancellation { SessionState.stopRequested }
SessionState.installCancellation = cancellation
return try {
extras.install(this, extras.tools.first { it.id == extras.OWN }, cancellation) { label, percent ->
uiHandler.post { loading.percent = percent; loading.say(label, PROTON_LINES.topic, readable = true) }
}.also { if (it == null) com.droiddeck.launcher.session.Onboarding.recheck(this) }
} finally {
if (SessionState.installCancellation === cancellation) SessionState.installCancellation = null
}
}
override fun surfaceCreated(holder: SurfaceHolder) {
if (holder !== outputHolder()) return
if (installingRuntime || SessionState.stopRequested || ended) return
@@ -3395,8 +3414,7 @@ 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))
setIntent(next)
recreate()
relaunch(next)
return@runOnUiThread
}
showEnded(status, hint)
@@ -3404,6 +3422,16 @@ 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()
@@ -6031,8 +6059,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
Log.w(TAG, "ignoring agent start while session phase is ${SessionState.phase}")
return
}
setIntent(intent)
recreate()
relaunch(android.content.Intent(intent).setClass(this, SessionActivity::class.java))
return
}
if (this.intent.getBooleanExtra(EXTRA_RETURN_HOME, false)) intent.putExtra(EXTRA_RETURN_HOME, true)
@@ -293,6 +293,7 @@ object DeviceReport {
k("Stretch 16:9 to panel", SessionPrefs.stretch16x9(context))
k("Avoid notch", SessionPrefs.avoidNotch(context))
k("Return to launcher after a game", SessionPrefs.returnAfterGame(context))
k("Valve Proton only when needed", SessionPrefs.valveProtonOnDemand(context))
k("Microphone", SessionPrefs.micEnabled(context))
k("On-screen controls", SessionPrefs.oscMode(context))
k("Touch mode", SessionPrefs.touchMode(context))
@@ -33,6 +33,13 @@ 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 {
@@ -109,9 +109,15 @@ object DesktopCatalog {
FileUtils.readString(marker(context, id))?.trim()?.takeIf { it.isNotEmpty() }
fun protonSeedNeeded(context: Context): Boolean =
installed(context, PROTON_SEED_ID) == null &&
if (com.droiddeck.launcher.session.SessionPrefs.ownProtonFirst(context)) ownProtonMissing(context)
else installed(context, PROTON_SEED_ID) == null &&
!File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/steamapps/appmanifest_4427310.acf").isFile
fun ownProtonMissing(context: Context): Boolean {
val extras = com.droiddeck.launcher.session.ProtonExtras
return extras.installedAll(context, extras.tools.first { it.id == extras.OWN }).isEmpty()
}
const val DESKTOP_ID = "desktop-kde"
const val EMULATORS_ID = "emulators"
private const val EMULATORS_SCRIPT = "/usr/local/bin/droiddeck-emulators"
@@ -22,7 +22,7 @@ class RuntimeInstallService : Service() {
if (intent?.action == ACTION_PACKAGE) return holdPackage(startId)
val removal = intent?.action == ACTION_REMOVE
val release = intent?.let(::releaseFrom)
startForeground(NOTIFICATION_ID, notification(getString(if (LinuxRuntimeInstaller.isMaintaining()) R.string.desktop_removing else if (removal) R.string.rtinst_removing else R.string.user_apps_starting), -1))
val foreground = enterForeground(notification(getString(if (LinuxRuntimeInstaller.isMaintaining()) R.string.desktop_removing else if (removal) R.string.rtinst_removing else R.string.user_apps_starting), -1))
if (release == null && !removal) {
stopSelf(startId)
return START_NOT_STICKY
@@ -31,7 +31,7 @@ class RuntimeInstallService : Service() {
val manager = getSystemService(NotificationManager::class.java)
var shown = ""
val progress = LinuxRuntimeInstaller.ProgressListener { stage, percent ->
if ("$stage:$percent" != shown) {
if (foreground && "$stage:$percent" != shown) {
shown = "$stage:$percent"
manager?.notify(NOTIFICATION_ID, notification(stage, percent))
}
@@ -46,7 +46,10 @@ class RuntimeInstallService : Service() {
}
private fun holdPackage(startId: Int): Int {
startForeground(NOTIFICATION_ID, notification(packageStage, packagePercent, packageTitle))
if (!enterForeground(notification(packageStage, packagePercent, packageTitle))) {
stopSelf(startId)
return START_NOT_STICKY
}
Thread({
val manager = getSystemService(NotificationManager::class.java)
var shown = ""
@@ -65,6 +68,15 @@ class RuntimeInstallService : Service() {
return START_NOT_STICKY
}
/** Android 12+ refuses a foreground start while the app is in the background; the work then goes on without the notification. */
private fun enterForeground(notification: Notification): Boolean = try {
startForeground(NOTIFICATION_ID, notification)
true
} catch (e: IllegalStateException) {
android.util.Log.w("RuntimeInstallService", "running without a foreground service: $e")
false
}
private fun notification(stage: String, percent: Int, title: String? = null): Notification {
val manager = getSystemService(NotificationManager::class.java)
manager?.createNotificationChannel(NotificationChannel(CHANNEL_ID, getString(R.string.setup_runtime),
@@ -2,16 +2,20 @@ 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)
@@ -19,10 +23,12 @@ object OfflineMode {
private fun x64LoginUsers(root: File) = File(root, "root/.droiddeck-x64/.local/share/Steam/config/loginusers.vdf")
fun account(context: Context): String? {
val root = LinuxRuntime.rootDir(context)
val file = x64LoginUsers(root).takeIf { SessionPrefs.activeSteamClientArch(context) == "x86_64" && it.isFile }
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 text = try {
if (file.isFile) file.readText() else return null
} catch (e: Exception) {
@@ -32,21 +38,114 @@ object OfflineMode {
return PERSONA.find(text)?.groupValues?.get(1)?.takeIf { it.isNotBlank() }.orEmpty()
}
fun enabled(context: Context): Boolean = prefs(context).getBoolean(KEY, false)
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
}
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) {
prefs(context).edit().putBoolean(KEY, on).apply()
apply(context, LinuxRuntime.rootDir(context))
write(context, LinuxRuntime.rootDir(context), on)
SteamOfflineFollow.request()
}
fun apply(context: Context, root: File) {
applyTo(context, loginUsers(root))
applyTo(context, x64LoginUsers(root))
@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)
}
private fun applyTo(context: Context, file: File) {
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) {
if (!file.isFile) return
val want = if (enabled(context)) "1" else "0"
val want = if (offline) "1" else "0"
try {
val lines = file.readLines()
val out = ArrayList<String>(lines.size + 4)
@@ -94,4 +193,25 @@ 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";
})"""
}
@@ -249,21 +249,24 @@ object ProtonExtras {
}
@Synchronized
fun install(context: Context, tool: Tool, onProgress: (String, Int) -> Unit): String? {
fun install(context: Context, tool: Tool, cancelled: java.util.function.BooleanSupplier? = null,
onProgress: (String, Int) -> Unit): String? {
if (installInProgress || prefetching) return context.getString(R.string.pextra_busy)
installInProgress = true
return try { installNow(context, tool, onProgress) } finally { installInProgress = false }
return try { installNow(context, tool, cancelled, onProgress) } finally { installInProgress = false }
}
private fun fetchArchive(context: Context, tool: Tool, asset: Asset, archive: File, onProgress: (String, Int) -> Unit): String? {
private fun fetchArchive(context: Context, tool: Tool, asset: Asset, archive: File, onProgress: (String, Int) -> Unit,
cancelled: java.util.function.BooleanSupplier? = null): String? {
val downloading = context.getString(R.string.pextra_downloading, tool.name, asset.tag)
onProgress(downloading, 0)
var downloaded = false
for (attempt in 0 until 5) {
downloaded = Downloader.downloadFile(asset.url, archive, true, asset.sha256) { fraction ->
downloaded = Downloader.downloadFile(asset.url, archive, true, asset.sha256, cancelled) { fraction ->
onProgress(downloading, if (fraction < 0) -1 else (fraction * 100f).toInt().coerceIn(0, 100))
}
if (downloaded) break
if (cancelled?.asBoolean == true) return context.getString(R.string.pextra_interrupted)
if (attempt < 4) {
onProgress(context.getString(R.string.pextra_retrying, attempt + 2, 5), -1)
try { Thread.sleep(3_000) } catch (_: InterruptedException) {
@@ -297,7 +300,8 @@ object ProtonExtras {
return problem
}
private fun installNow(context: Context, tool: Tool, onProgress: (String, Int) -> Unit): String? {
private fun installNow(context: Context, tool: Tool, cancelled: java.util.function.BooleanSupplier?,
onProgress: (String, Int) -> Unit): String? {
if (SessionState.running) return context.getString(R.string.pextra_stop_session)
if (!LinuxRuntime.isInstalled(context)) return context.getString(R.string.user_apps_runtime_required)
@@ -312,7 +316,7 @@ object ProtonExtras {
val checked = asset.sha256 != null && asset.size > 0 && checkedArchive == fingerprint(archive) &&
checkedDigest.equals(asset.sha256, ignoreCase = true)
if (!checked) fetchArchive(context, tool, asset, archive, onProgress)?.let { return it }
if (!checked) fetchArchive(context, tool, asset, archive, onProgress, cancelled)?.let { return it }
if (asset.size > 0 && archive.length() != asset.size) {
if (archive.length() > asset.size) {
archive.delete()
@@ -28,12 +28,14 @@ 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(
@@ -448,6 +448,13 @@ object SessionPrefs {
prefs(context).edit().putString("navTabHidden", keys.joinToString(",")).apply()
}
fun appsTabHomeSeen(context: Context): Boolean? =
prefs(context).takeIf { it.contains("appsTabHomeSeen") }?.getBoolean("appsTabHomeSeen", false)
fun setAppsTabHomeSeen(context: Context, seen: Boolean) {
prefs(context).edit().putBoolean("appsTabHomeSeen", seen).apply()
}
private fun idList(raw: String?): List<String> = raw.orEmpty().split(',').map { it.trim() }.filter { it.isNotEmpty() }
val STORES_SORTS = listOf("lastPlayed", "recentlyInstalled", "titleAsc", "titleDesc", "sizeDesc", "sizeAsc", "releaseDateDesc")
@@ -838,6 +845,15 @@ object SessionPrefs {
fun returnAfterGame(context: Context): Boolean = prefs(context).getBoolean("returnAfterGame", true)
fun valveProtonOnDemand(context: Context): Boolean = prefs(context).getBoolean("valveProtonOnDemand", true)
fun setValveProtonOnDemand(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("valveProtonOnDemand", on).apply()
}
/** DroidDeck-Proton is the Proton placed before the client starts; Valve's ARM64 Proton waits for a title that needs it. */
fun ownProtonFirst(context: Context): Boolean = valveProtonOnDemand(context) && !ProtonExtras.declined(context)
fun setReturnAfterGame(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("returnAfterGame", on).apply()
}
@@ -669,6 +669,8 @@ 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")
@@ -694,7 +696,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.enabled(this)) guest.add("DD_STEAM_OFFLINE=1")
if (OfflineMode.active(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})" })
}
@@ -813,6 +815,11 @@ 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()
@@ -1002,6 +1009,7 @@ class SessionService : Service() {
))
guest.add("TZ=" + java.util.TimeZone.getDefault().id)
if (SessionState.mode == MODE_STEAM) SessionPrefs.pendingShaderPrecache(this)?.let { guest.add("DD_SHADER_PRECACHE=" + if (it) "1" else "0") }
guest.add("DD_VALVE_PROTON=" + if (SessionPrefs.ownProtonFirst(this)) "0" else "1")
guest.add("XDG_RUNTIME_DIR=" + LinuxRuntime.GUEST_RUNTIME_DIR)
guest.add("XDG_SESSION_TYPE=wayland")
guest.add("WAYLAND_DISPLAY=wayland-0")
@@ -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", "bootMovie", "bootMovieSound", "bootMovieVolume", "bootMovieSeconds", "skipBootMovie",
"steamDownloadsInBackground", "steam_offline", "steam_offline_auto", "steam_offline_by_network", "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.apply(context, LinuxRuntime.rootDir(context)) }
runCatching { OfflineMode.setEnabled(context, false) }
.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) }
@@ -0,0 +1,104 @@
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()
}
}
}
@@ -103,6 +103,7 @@ 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,
@@ -273,6 +274,7 @@ 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 = {},
@@ -93,6 +93,7 @@ class ModeSettings(
val steamClientArch: String? = null,
val returnAfterGame: Boolean? = null,
val shaderPrecache: Boolean? = null,
val valveProtonOnDemand: Boolean? = null,
val steamRepairQueued: Boolean = false,
val mangoapp: Boolean = true,
val steamController: String? = null,
@@ -158,6 +159,7 @@ class ModeSettingsActions(
val onMangoapp: (Boolean) -> Unit = {},
val onReturnAfterGame: (Boolean) -> Unit = {},
val onShaderPrecache: (Boolean) -> Unit = {},
val onValveProtonOnDemand: (Boolean) -> Unit = {},
val onSteamController: (String) -> Unit = {},
val onUnfoldedControls: (Boolean) -> Unit = {},
val onUnfoldedControlsWithController: (Boolean) -> Unit = {},
@@ -534,6 +536,10 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras:
stringResource(R.string.mode_shader_precache_hint),
s.shaderPrecache, onChange = a.onShaderPrecache,
)
if (s.valveProtonOnDemand != null) ToggleRow(
host, "valveprotonondemand", stringResource(R.string.mode_valve_proton_on_demand), null,
s.valveProtonOnDemand, onChange = a.onValveProtonOnDemand,
)
SettingsRow(
stringResource(R.string.mode_steam_repair),
stringResource(if (s.steamRepairQueued) R.string.mode_steam_repair_queued else R.string.mode_steam_repair_hint),
@@ -27,9 +27,9 @@ internal object DeveloperTools {
internal object NavTabs {
const val MORE = "more"
val ALL = listOf("steam", "desktop", "games", "downloads", "setup", "updates", "stores", "soundtracks", "components", "storage", "sync", "decky", "boot-movies", "android-apps", "agent")
val DEFAULT_SHELVED = setOf("soundtracks", "components", "storage", "sync", "decky", "boot-movies", "android-apps", "agent")
val DEFAULT_SHELVED = setOf("soundtracks", "components", "storage", "sync", "decky", "boot-movies", "agent")
val DEFAULT_HIDDEN = setOf("android-apps", "agent")
private val SHELVED_WHEN_NEW = setOf("storage", "sync", "decky", "boot-movies", "android-apps", "agent")
private val SHELVED_WHEN_NEW = setOf("storage", "sync", "decky", "boot-movies", "agent")
private val OLD_ORDER = listOf("steam", "games", "soundtracks", "stores", "downloads", "desktop", "agent", "components", "android-apps", "storage", "sync", "setup", "updates")
private val OLD_SHELVED = setOf("soundtracks", "agent", "storage", "sync")
private const val LAYOUT_VERSION = 2
@@ -95,6 +95,15 @@ internal object NavTabs {
else -> true
}
// Apps only has content when DroidDeck is the home app, so it follows that state on each change and
// otherwise stays wherever the user put it.
fun syncHomeApps(context: Context, homeSelected: Boolean) {
val seen = SessionPrefs.appsTabHomeSeen(context)
SessionPrefs.setAppsTabHomeSeen(context, homeSelected)
if (seen == homeSelected || (seen == null && !homeSelected)) return
setHidden(context, "android-apps", !homeSelected)
}
fun hideable(key: String) = key != "setup"
fun place(s: FrontEndState, key: String): TabPlace = when {
@@ -115,10 +115,11 @@ internal fun SteamHome(s: FrontEndState, a: FrontEndActions, modifier: Modifier)
account = { host ->
SettingsGroup(stringResource(R.string.setup_account)) {
ToggleRow(
host, "offline", stringResource(R.string.setup_offline),
host, "offline-auto", stringResource(R.string.setup_offline_auto),
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.offline, enabled = s.offlineAccount != null,
) { a.onOffline() }
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() }
}
},
)
+1
View File
@@ -934,6 +934,7 @@
<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,6 +952,7 @@
<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,6 +922,7 @@
<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,6 +928,7 @@
<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,6 +922,7 @@
<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,6 +914,7 @@
<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,6 +922,7 @@
<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,6 +925,7 @@
<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,6 +922,7 @@
<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,6 +925,7 @@
<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,6 +922,7 @@
<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,6 +922,7 @@
<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,6 +919,7 @@
<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,6 +917,7 @@
<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,6 +919,7 @@
<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,6 +919,7 @@
<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,6 +919,7 @@
<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,6 +922,7 @@
<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,6 +922,7 @@
<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,6 +928,7 @@
<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,6 +917,7 @@
<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,6 +924,7 @@
<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,6 +925,7 @@
<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,6 +928,7 @@
<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,6 +922,7 @@
<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,6 +919,7 @@
<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,6 +914,7 @@
<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,6 +928,7 @@
<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,6 +919,7 @@
<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,6 +919,7 @@
<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,6 +918,7 @@
<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,6 +918,7 @@
<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>
+2
View File
@@ -383,6 +383,7 @@
<string name="mode_return_after_game">Return to DroidDeck after a game</string>
<string name="mode_return_after_game_hint">When a game you started from DroidDeck or another launcher closes, Steam exits cleanly (cloud saves finish first) and you go back there. Off: stay in Steam.</string>
<string name="mode_shader_precache">Shader pre-caching</string>
<string name="mode_valve_proton_on_demand">Valve Proton only when needed</string>
<string name="mode_shader_precache_hint">Steam downloads shaders prebuilt for your games and processes them in the background, so games stutter less. Off saves data, storage and battery; games build shaders as they play instead. The same setting as Steam’s Downloads > Shader Pre-Caching. Applies next session.</string>
<string name="mode_steam_repair">Repair Steam client</string>
<string name="mode_steam_repair_hint">Downloads the Steam client again the next time Steam starts. Use it if Steam stays on its loading screen. Games, sign-in and settings are kept.</string>
@@ -1003,6 +1004,7 @@
<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>
@@ -0,0 +1,18 @@
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,4 +32,9 @@ 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", ""))
}
}
@@ -0,0 +1,246 @@
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))
}
}
@@ -48,6 +48,21 @@ class NavTabsTest {
assertTrue(NavTabs.isDefault())
}
@Test fun appsFollowsTheHomeAppOnEachChangeAndOtherwiseKeepsTheUsersChoice() {
NavTabs.syncHomeApps(ctx, false)
assertEquals(TabPlace.HIDDEN, NavTabs.place(state(), "android-apps"))
NavTabs.syncHomeApps(ctx, true)
assertEquals(TabPlace.BAR, NavTabs.place(state(), "android-apps"))
NavTabs.setHidden(ctx, "android-apps", true)
NavTabs.syncHomeApps(ctx, true)
assertEquals(TabPlace.HIDDEN, NavTabs.place(state(), "android-apps"))
NavTabs.syncHomeApps(ctx, false)
NavTabs.syncHomeApps(ctx, true)
assertEquals(TabPlace.BAR, NavTabs.place(state(), "android-apps"))
NavTabs.syncHomeApps(ctx, false)
assertEquals(TabPlace.HIDDEN, NavTabs.place(state(), "android-apps"))
}
@Test fun showingMusicOnceKeepsItShownAfterReload() {
place("soundtracks", TabPlace.BAR)
NavTabs.load(ctx)
@@ -219,12 +234,12 @@ class NavTabsTest {
}
}
}
val last = navigationKeys(state()).last { it != NavTabs.MORE }
val last = NavTabs.listed(state()).last { it !in NavTabs.shelved }
compose.onNodeWithTag("tab-row-$last").requestFocus()
compose.onNodeWithTag("tab-row-$last").performKeyPress(pad(android.view.KeyEvent.KEYCODE_BUTTON_Y))
compose.onNodeWithTag("tab-row-$last").performKeyPress(pad(android.view.KeyEvent.KEYCODE_DPAD_DOWN))
compose.onNodeWithTag("tab-row-$last").performKeyPress(pad(android.view.KeyEvent.KEYCODE_BUTTON_Y))
compose.runOnIdle { assertEquals(last, NavTabs.more(state()).first()) }
compose.runOnIdle { assertTrue(last in NavTabs.shelved) }
compose.onNodeWithTag("tab-shown-desktop").performClick()
compose.runOnIdle { assertFalse("desktop" in navigationKeys(state())) }
compose.onNodeWithTag("tab-shown-setup").performClick()
@@ -0,0 +1,982 @@
diff --git a/Data/ThunksDB.json b/Data/ThunksDB.json
index 886379a..7844b27 100644
--- a/Data/ThunksDB.json
+++ b/Data/ThunksDB.json
@@ -49,6 +49,24 @@
"@PREFIX_LIB@/libwayland-client.so.0.20.0"
]
},
+ "EGL": {
+ "Library" : "libEGL-guest.so",
+ "Overlay": [
+ "@PREFIX_LIB@/libEGL.so",
+ "@PREFIX_LIB@/libEGL.so.1",
+ "@PREFIX_LIB@/libEGL.so.1.1.0",
+ "@PREFIX_LIB@/libGLESv2.so.2",
+ "@PREFIX_LIB@/libGLESv2.so.2.1.0"
+ ]
+ },
+ "WaylandEGL": {
+ "Library" : "libwayland-egl-guest.so",
+ "Overlay": [
+ "@PREFIX_LIB@/libwayland-egl.so",
+ "@PREFIX_LIB@/libwayland-egl.so.1",
+ "@PREFIX_LIB@/libwayland-egl.so.1.0.0"
+ ]
+ },
"cuda": {
"Library" : "libcuda-guest.so",
"Overlay": [
diff --git a/ThunkLibs/GuestLibs/CMakeLists.txt b/ThunkLibs/GuestLibs/CMakeLists.txt
index bf666d9..72b0832 100644
--- a/ThunkLibs/GuestLibs/CMakeLists.txt
+++ b/ThunkLibs/GuestLibs/CMakeLists.txt
@@ -211,6 +211,21 @@ if (BITNESS EQUAL 64)
target_include_directories_from_pkgconfig(libasound-guest-deps alsa)
add_guest_lib(asound "libasound.so.2")
+ generate(libwayland-client ${CMAKE_CURRENT_SOURCE_DIR}/../libwayland-client/libwayland-client_interface.cpp)
+ add_guest_lib(wayland-client "libwayland-client.so.0.20.0")
+ target_include_directories_from_pkgconfig(libwayland-client-guest-deps wayland-client /usr/include/wayland)
+
+ generate(libwayland-egl ${CMAKE_CURRENT_SOURCE_DIR}/../libwayland-egl/libwayland-egl_interface.cpp)
+ add_guest_lib(wayland-egl "libwayland-egl.so.1")
+ target_include_directories_from_pkgconfig(libwayland-egl-guest-deps wayland-egl /usr/include/wayland)
+
+ generate(libEGL ${CMAKE_CURRENT_SOURCE_DIR}/../libEGL/libEGL_interface.cpp)
+ target_include_directories_from_pkgconfig(libEGL-guest-deps egl)
+ add_guest_lib(EGL "libEGL.so.1")
+ target_link_libraries(EGL-guest PRIVATE GL-guest)
+ target_link_libraries(EGL-guest PRIVATE PlaceholderX11)
+ target_include_directories_from_pkgconfig(libEGL-guest-deps "xcb;x11")
+
# disabled for now, headers are platform specific
# find_package(SDL2 REQUIRED)
# generate(libSDL2)
@@ -229,10 +244,6 @@ if (BITNESS EQUAL 64)
add_guest_lib(drm "libdrm.so.2")
endif()
-generate(libwayland-client ${CMAKE_CURRENT_SOURCE_DIR}/../libwayland-client/libwayland-client_interface.cpp)
-add_guest_lib(wayland-client "libwayland-client.so.0.20.0")
-target_include_directories_from_pkgconfig(libwayland-client-guest-deps wayland-client /usr/include/wayland)
-
generate(libVDSO ${CMAKE_CURRENT_SOURCE_DIR}/../libVDSO/libVDSO_interface.cpp)
add_guest_lib(VDSO "linux-vdso.so.1")
# Can't use a stack protector because otherwise cross-compiling fails
@@ -271,11 +282,6 @@ target_include_directories_from_pkgconfig(libGL-guest-deps gl)
target_include_directories_from_pkgconfig(libGL-guest-deps "xcb;x11;xrandr;xrender")
add_guest_lib(GL "libGL.so.1")
-generate(libEGL ${CMAKE_CURRENT_SOURCE_DIR}/../libEGL/libEGL_interface.cpp)
-target_include_directories_from_pkgconfig(libEGL-guest-deps egl)
-add_guest_lib(EGL "libEGL.so.1")
-target_link_libraries(EGL-guest PRIVATE GL-guest)
-
# libGL must pull in libX11.so, so generate a placeholder libX11.so to link against
add_library(PlaceholderX11 SHARED ../libX11/libX11_NativeGuest.cpp)
target_link_options(PlaceholderX11 PRIVATE "LINKER:-soname,libX11.so.6")
diff --git a/ThunkLibs/HostLibs/CMakeLists.txt b/ThunkLibs/HostLibs/CMakeLists.txt
index 8d18d0e..c10066f 100644
--- a/ThunkLibs/HostLibs/CMakeLists.txt
+++ b/ThunkLibs/HostLibs/CMakeLists.txt
@@ -167,13 +167,19 @@ foreach(GUEST_BITNESS IN LISTS BITNESS_LIST)
target_include_directories_from_pkgconfig(libvulkan-${GUEST_BITNESS}-deps "xcb;x11;xrandr;xrender")
add_host_lib(vulkan ${GUEST_BITNESS})
- generate(libwayland-client ${CMAKE_CURRENT_SOURCE_DIR}/../libwayland-client/libwayland-client_interface.cpp ${GUEST_BITNESS})
- add_host_lib(wayland-client ${GUEST_BITNESS})
- target_include_directories_from_pkgconfig(libwayland-client-${GUEST_BITNESS}-deps wayland-client /usr/include/wayland)
-
- generate(libEGL ${CMAKE_CURRENT_SOURCE_DIR}/../libEGL/libEGL_interface.cpp ${GUEST_BITNESS})
- target_include_directories_from_pkgconfig(libEGL-${GUEST_BITNESS}-deps egl)
- add_host_lib(EGL ${GUEST_BITNESS})
+ if (GUEST_BITNESS EQUAL 64)
+ generate(libwayland-client ${CMAKE_CURRENT_SOURCE_DIR}/../libwayland-client/libwayland-client_interface.cpp ${GUEST_BITNESS})
+ add_host_lib(wayland-client ${GUEST_BITNESS})
+ target_include_directories_from_pkgconfig(libwayland-client-${GUEST_BITNESS}-deps wayland-client /usr/include/wayland)
+
+ generate(libwayland-egl ${CMAKE_CURRENT_SOURCE_DIR}/../libwayland-egl/libwayland-egl_interface.cpp ${GUEST_BITNESS})
+ add_host_lib(wayland-egl ${GUEST_BITNESS})
+ target_include_directories_from_pkgconfig(libwayland-egl-${GUEST_BITNESS}-deps wayland-egl /usr/include/wayland)
+
+ generate(libEGL ${CMAKE_CURRENT_SOURCE_DIR}/../libEGL/libEGL_interface.cpp ${GUEST_BITNESS})
+ target_include_directories_from_pkgconfig(libEGL-${GUEST_BITNESS}-deps "egl;xcb;x11")
+ add_host_lib(EGL ${GUEST_BITNESS})
+ endif()
generate(libGL ${CMAKE_CURRENT_SOURCE_DIR}/../libGL/libGL_interface.cpp ${GUEST_BITNESS})
target_include_directories_from_pkgconfig(libGL-${GUEST_BITNESS}-deps gl)
diff --git a/ThunkLibs/libEGL/libEGL_Guest.cpp b/ThunkLibs/libEGL/libEGL_Guest.cpp
index c157f00..196c7e8 100644
--- a/ThunkLibs/libEGL/libEGL_Guest.cpp
+++ b/ThunkLibs/libEGL/libEGL_Guest.cpp
@@ -5,11 +5,22 @@ desc: Depends on glXGetProcAddress thunk
$end_info$
*/
+#define EGL_EGLEXT_PROTOTYPES 1
#include <GL/glx.h>
#include <EGL/egl.h>
+#include <EGL/eglext.h>
+#include <X11/Xlib.h>
+#ifndef _GNU_SOURCE
+#define _GNU_SOURCE
+#endif
+#include <dlfcn.h>
#include <stdio.h>
#include <cstring>
+#include <mutex>
+#include <set>
+#include <string>
+#include <string_view>
#include "common/Guest.h"
@@ -17,12 +28,128 @@ $end_info$
typedef void voidFunc();
+static void* Self() {
+ static void* self = [] {
+ Dl_info info {};
+ return dladdr(reinterpret_cast<void*>(&Self), &info) && info.dli_fname ? dlopen(info.dli_fname, RTLD_LAZY | RTLD_NOLOAD) : nullptr;
+ }();
+ return self;
+}
+
+static constexpr std::pair<std::string_view, std::string_view> ExtensionEntrypoints[] = {
+ {"EGL_ANDROID_blob_cache", "eglSetBlobCacheFuncsANDROID"},
+ {"EGL_ANDROID_create_native_client_buffer", "eglCreateNativeClientBufferANDROID"},
+ {"EGL_ANDROID_get_frame_timestamps", "eglGetCompositorTimingSupportedANDROID eglGetCompositorTimingANDROID eglGetNextFrameIdANDROID eglGetFrameTimestampSupportedANDROID eglGetFrameTimestampsANDROID"},
+ {"EGL_ANDROID_get_native_client_buffer", "eglGetNativeClientBufferANDROID"},
+ {"EGL_ANDROID_native_fence_sync", "eglDupNativeFenceFDANDROID"},
+ {"EGL_ANDROID_presentation_time", "eglPresentationTimeANDROID"},
+ {"EGL_ANGLE_query_surface_pointer", "eglQuerySurfacePointerANGLE"},
+ {"EGL_ANGLE_sync_control_rate", "eglGetMscRateANGLE"},
+ {"EGL_EXT_client_sync", "eglClientSignalSyncEXT"},
+ {"EGL_EXT_compositor", "eglCompositorSetContextListEXT eglCompositorSetContextAttributesEXT eglCompositorSetWindowListEXT eglCompositorSetWindowAttributesEXT eglCompositorBindTexWindowEXT eglCompositorSetSizeEXT eglCompositorSwapPolicyEXT"},
+ {"EGL_EXT_device_base", "eglQueryDeviceAttribEXT eglQueryDeviceStringEXT eglQueryDevicesEXT eglQueryDisplayAttribEXT"},
+ {"EGL_EXT_device_enumeration", "eglQueryDevicesEXT"},
+ {"EGL_EXT_device_persistent_id", "eglQueryDeviceBinaryEXT"},
+ {"EGL_EXT_device_query", "eglQueryDeviceAttribEXT eglQueryDeviceStringEXT eglQueryDisplayAttribEXT"},
+ {"EGL_EXT_image_dma_buf_import_modifiers", "eglQueryDmaBufFormatsEXT eglQueryDmaBufModifiersEXT"},
+ {"EGL_EXT_output_base", "eglGetOutputLayersEXT eglGetOutputPortsEXT eglOutputLayerAttribEXT eglQueryOutputLayerAttribEXT eglQueryOutputLayerStringEXT eglOutputPortAttribEXT eglQueryOutputPortAttribEXT eglQueryOutputPortStringEXT"},
+ {"EGL_EXT_platform_base", "eglGetPlatformDisplayEXT eglCreatePlatformWindowSurfaceEXT eglCreatePlatformPixmapSurfaceEXT"},
+ {"EGL_EXT_stream_consumer_egloutput", "eglStreamConsumerOutputEXT"},
+ {"EGL_EXT_surface_compression", "eglQuerySupportedCompressionRatesEXT"},
+ {"EGL_EXT_swap_buffers_with_damage", "eglSwapBuffersWithDamageEXT"},
+ {"EGL_EXT_sync_reuse", "eglUnsignalSyncEXT"},
+ {"EGL_HI_clientpixmap", "eglCreatePixmapSurfaceHI"},
+ {"EGL_KHR_cl_event2", "eglCreateSync64KHR"},
+ {"EGL_KHR_debug", "eglDebugMessageControlKHR eglQueryDebugKHR eglLabelObjectKHR"},
+ {"EGL_KHR_display_reference", "eglQueryDisplayAttribKHR"},
+ {"EGL_KHR_fence_sync", "eglCreateSyncKHR eglDestroySyncKHR eglClientWaitSyncKHR eglGetSyncAttribKHR"},
+ {"EGL_KHR_image", "eglCreateImageKHR eglDestroyImageKHR"},
+ {"EGL_KHR_image_base", "eglCreateImageKHR eglDestroyImageKHR"},
+ {"EGL_KHR_lock_surface", "eglLockSurfaceKHR eglUnlockSurfaceKHR"},
+ {"EGL_KHR_lock_surface3", "eglLockSurfaceKHR eglUnlockSurfaceKHR eglQuerySurface64KHR"},
+ {"EGL_KHR_partial_update", "eglSetDamageRegionKHR"},
+ {"EGL_KHR_reusable_sync", "eglCreateSyncKHR eglDestroySyncKHR eglClientWaitSyncKHR eglSignalSyncKHR eglGetSyncAttribKHR"},
+ {"EGL_KHR_stream", "eglCreateStreamKHR eglDestroyStreamKHR eglStreamAttribKHR eglQueryStreamKHR eglQueryStreamu64KHR"},
+ {"EGL_KHR_stream_attrib", "eglCreateStreamAttribKHR eglSetStreamAttribKHR eglQueryStreamAttribKHR eglStreamConsumerAcquireAttribKHR eglStreamConsumerReleaseAttribKHR"},
+ {"EGL_KHR_stream_consumer_gltexture", "eglStreamConsumerGLTextureExternalKHR eglStreamConsumerAcquireKHR eglStreamConsumerReleaseKHR"},
+ {"EGL_KHR_stream_cross_process_fd", "eglGetStreamFileDescriptorKHR eglCreateStreamFromFileDescriptorKHR"},
+ {"EGL_KHR_stream_fifo", "eglQueryStreamTimeKHR"},
+ {"EGL_KHR_stream_producer_eglsurface", "eglCreateStreamProducerSurfaceKHR"},
+ {"EGL_KHR_swap_buffers_with_damage", "eglSwapBuffersWithDamageKHR"},
+ {"EGL_KHR_wait_sync", "eglWaitSyncKHR"},
+ {"EGL_MESA_drm_image", "eglCreateDRMImageMESA eglExportDRMImageMESA"},
+ {"EGL_MESA_image_dma_buf_export", "eglExportDMABUFImageQueryMESA eglExportDMABUFImageMESA"},
+ {"EGL_MESA_query_driver", "eglGetDisplayDriverConfig eglGetDisplayDriverName"},
+ {"EGL_NOK_swap_region", "eglSwapBuffersRegionNOK"},
+ {"EGL_NOK_swap_region2", "eglSwapBuffersRegion2NOK"},
+ {"EGL_NV_native_query", "eglQueryNativeDisplayNV eglQueryNativeWindowNV eglQueryNativePixmapNV"},
+ {"EGL_NV_post_sub_buffer", "eglPostSubBufferNV"},
+ {"EGL_NV_stream_consumer_eglimage", "eglStreamImageConsumerConnectNV eglQueryStreamConsumerEventNV eglStreamAcquireImageNV eglStreamReleaseImageNV"},
+ {"EGL_NV_stream_consumer_gltexture_yuv", "eglStreamConsumerGLTextureExternalAttribsNV"},
+ {"EGL_NV_stream_flush", "eglStreamFlushNV"},
+ {"EGL_NV_stream_metadata", "eglQueryDisplayAttribNV eglSetStreamMetadataNV eglQueryStreamMetadataNV"},
+ {"EGL_NV_stream_reset", "eglResetStreamNV"},
+ {"EGL_NV_stream_sync", "eglCreateStreamSyncNV"},
+ {"EGL_NV_sync", "eglCreateFenceSyncNV eglDestroySyncNV eglFenceNV eglClientWaitSyncNV eglSignalSyncNV eglGetSyncAttribNV"},
+ {"EGL_NV_system_time", "eglGetSystemTimeFrequencyNV eglGetSystemTimeNV"},
+ {"EGL_WL_bind_wayland_display", "eglBindWaylandDisplayWL eglUnbindWaylandDisplayWL eglQueryWaylandBufferWL"},
+ {"EGL_WL_create_wayland_buffer_from_image", "eglCreateWaylandBufferFromImageWL"},
+};
+
+static bool GuestHasEntrypoints(std::string_view extension) {
+ for (const auto& [name, entrypoints] : ExtensionEntrypoints) {
+ if (name != extension) {
+ continue;
+ }
+ std::string_view rest = entrypoints;
+ while (!rest.empty()) {
+ auto end = rest.find(' ');
+ if (!Self() || !dlsym(Self(), std::string {rest.substr(0, end)}.c_str())) {
+ return false;
+ }
+ rest = end == std::string_view::npos ? std::string_view {} : rest.substr(end + 1);
+ }
+ return true;
+ }
+ return true;
+}
extern "C" {
voidFunc* eglGetProcAddress(const char* procname) {
- // TODO: Fix this HACK
+ if (strncmp(procname, "egl", 3) == 0) {
+ return Self() ? reinterpret_cast<voidFunc*>(dlsym(Self(), procname)) : nullptr;
+ }
return glXGetProcAddress((const GLubyte*)procname);
}
+
+const char* eglQueryString(EGLDisplay display, EGLint name) {
+ const char* result = fexfn_pack_eglQueryString(display, name);
+ if (!result || name != EGL_EXTENSIONS) {
+ return result;
+ }
+ std::string filtered;
+ std::string_view all {result};
+ while (!all.empty()) {
+ auto end = all.find(' ');
+ auto extension = all.substr(0, end);
+ if (!extension.empty() && GuestHasEntrypoints(extension)) {
+ if (!filtered.empty()) {
+ filtered += ' ';
+ }
+ filtered += extension;
+ }
+ all = end == std::string_view::npos ? std::string_view {} : all.substr(end + 1);
+ }
+ static std::mutex mutex;
+ static std::set<std::string> strings;
+ std::lock_guard lock(mutex);
+ return strings.insert(std::move(filtered)).first->c_str();
+}
+}
+
+static void OnInit() {
+ fexfn_pack_EGL_SetGuestXSync((uintptr_t)XSync, (uintptr_t)CallbackUnpack<decltype(XSync)>::Unpack);
+ fexfn_pack_EGL_SetGuestXDisplayString((uintptr_t)XDisplayString, (uintptr_t)CallbackUnpack<decltype(XDisplayString)>::Unpack);
}
-LOAD_LIB(libEGL)
+LOAD_LIB_INIT(libEGL, OnInit)
diff --git a/ThunkLibs/libEGL/libEGL_Host.cpp b/ThunkLibs/libEGL/libEGL_Host.cpp
index ac8a87e..9b154b8 100644
--- a/ThunkLibs/libEGL/libEGL_Host.cpp
+++ b/ThunkLibs/libEGL/libEGL_Host.cpp
@@ -4,14 +4,163 @@ tags: thunklibs|EGL
$end_info$
*/
+#include <atomic>
#include <cstdio>
+#include <cstdlib>
#include <dlfcn.h>
+#include <mutex>
+#include <string_view>
+#include <unordered_map>
+#define EGL_EGLEXT_PROTOTYPES 1
#include <EGL/egl.h>
+#include <EGL/eglext.h>
#include "common/Host.h"
-#include <dlfcn.h>
+#include <X11/Xutil.h>
+#include "common/X11Manager.h"
+
+static X11Manager x11_manager;
+static std::mutex x11_displays_mutex;
+static std::unordered_map<EGLDisplay, _XDisplay*> x11_displays;
+
+static void* fex_egl_get_proc_address(void* so, const char* name) {
+ static auto get_proc_address = reinterpret_cast<void* (*)(const char*)>(dlsym(so, "eglGetProcAddress"));
+ return get_proc_address ? get_proc_address(name) : nullptr;
+}
+
+static void fexfn_impl_libEGL_EGL_SetGuestXSync(uintptr_t GuestTarget, uintptr_t GuestUnpacker) {
+ MakeHostTrampolineForGuestFunctionAt(GuestTarget, GuestUnpacker, &x11_manager.GuestXSync);
+}
+
+static void fexfn_impl_libEGL_EGL_SetGuestXDisplayString(uintptr_t GuestTarget, uintptr_t GuestUnpacker) {
+ MakeHostTrampolineForGuestFunctionAt(GuestTarget, GuestUnpacker, &x11_manager.GuestXDisplayString);
+}
#include "thunkgen_host_libEGL.inl"
+static bool IsWaylandDisplay(void* native) {
+ static std::atomic<void*> cached_interface {nullptr};
+ void* wl_display_interface = cached_interface.load(std::memory_order_acquire);
+ if (!wl_display_interface) {
+ if (void* so = dlopen("libwayland-client.so.0", RTLD_LAZY | RTLD_NOLOAD)) {
+ wl_display_interface = dlsym(so, "wl_display_interface");
+ dlclose(so);
+ cached_interface.store(wl_display_interface, std::memory_order_release);
+ }
+ }
+ return wl_display_interface && *reinterpret_cast<void**>(native) == wl_display_interface;
+}
+
+static std::string_view EnvPlatform() {
+ const char* name = getenv("EGL_PLATFORM");
+ if (!name || !*name) {
+ name = getenv("EGL_DISPLAY");
+ }
+ return name ? std::string_view {name} : std::string_view {};
+}
+
+static void* HostNativeDisplay(EGLenum platform, void* native, _XDisplay** guest_x11) {
+ if (!native) {
+ return nullptr;
+ }
+ switch (platform) {
+ case EGL_PLATFORM_X11_KHR: break;
+#ifdef EGL_PLATFORM_XCB_EXT
+ case EGL_PLATFORM_XCB_EXT: return x11_manager.GuestToHostConnection(static_cast<xcb_connection_t*>(native));
+#endif
+ case 0:
+ if (auto env = EnvPlatform(); !env.empty()) {
+ if (env == "xcb") {
+ return x11_manager.GuestToHostConnection(static_cast<xcb_connection_t*>(native));
+ }
+ if (env != "x11") {
+ return native;
+ }
+ break;
+ }
+ if (IsWaylandDisplay(native)) {
+ return native;
+ }
+ break;
+ default: return native;
+ }
+ *guest_x11 = static_cast<_XDisplay*>(native);
+ return x11_manager.GuestToHostDisplay(*guest_x11);
+}
+
+static EGLDisplay TrackDisplay(EGLDisplay display, _XDisplay* guest_x11) {
+ if (display != EGL_NO_DISPLAY && guest_x11) {
+ std::lock_guard lock(x11_displays_mutex);
+ x11_displays[display] = guest_x11;
+ }
+ return display;
+}
+
+static void SyncGuestDisplay(EGLDisplay display) {
+ _XDisplay* guest_x11 = nullptr;
+ {
+ std::lock_guard lock(x11_displays_mutex);
+ if (auto it = x11_displays.find(display); it != x11_displays.end()) {
+ guest_x11 = it->second;
+ }
+ }
+ if (guest_x11) {
+ x11_manager.GuestXSync(guest_x11, 0);
+ }
+}
+
+EGLDisplay fexfn_impl_libEGL_eglGetDisplay(guest_layout<EGLNativeDisplayType> native) {
+ _XDisplay* guest_x11 = nullptr;
+ auto host = HostNativeDisplay(0, native.force_get_host_pointer(), &guest_x11);
+ return TrackDisplay(fexldr_ptr_libEGL_eglGetDisplay(static_cast<EGLNativeDisplayType>(host)), guest_x11);
+}
+
+EGLDisplay fexfn_impl_libEGL_eglGetPlatformDisplay(EGLenum platform, void* native, const EGLAttrib* attribs) {
+ _XDisplay* guest_x11 = nullptr;
+ auto host = HostNativeDisplay(platform, native, &guest_x11);
+ return TrackDisplay(fexldr_ptr_libEGL_eglGetPlatformDisplay(platform, host, attribs), guest_x11);
+}
+
+EGLDisplay fexfn_impl_libEGL_eglGetPlatformDisplayEXT(EGLenum platform, void* native, const EGLint* attribs) {
+ _XDisplay* guest_x11 = nullptr;
+ auto host = HostNativeDisplay(platform, native, &guest_x11);
+ return TrackDisplay(fexldr_ptr_libEGL_eglGetPlatformDisplayEXT(platform, host, attribs), guest_x11);
+}
+
+EGLSurface fexfn_impl_libEGL_eglCreateWindowSurface(EGLDisplay display, EGLConfig config, EGLNativeWindowType window, const EGLint* attribs) {
+ SyncGuestDisplay(display);
+ return fexldr_ptr_libEGL_eglCreateWindowSurface(display, config, window, attribs);
+}
+
+EGLSurface fexfn_impl_libEGL_eglCreatePixmapSurface(EGLDisplay display, EGLConfig config, EGLNativePixmapType pixmap, const EGLint* attribs) {
+ SyncGuestDisplay(display);
+ return fexldr_ptr_libEGL_eglCreatePixmapSurface(display, config, pixmap, attribs);
+}
+
+EGLSurface fexfn_impl_libEGL_eglCreatePlatformWindowSurface(EGLDisplay display, EGLConfig config, void* window, const EGLAttrib* attribs) {
+ SyncGuestDisplay(display);
+ return fexldr_ptr_libEGL_eglCreatePlatformWindowSurface(display, config, window, attribs);
+}
+
+EGLSurface fexfn_impl_libEGL_eglCreatePlatformPixmapSurface(EGLDisplay display, EGLConfig config, void* pixmap, const EGLAttrib* attribs) {
+ SyncGuestDisplay(display);
+ return fexldr_ptr_libEGL_eglCreatePlatformPixmapSurface(display, config, pixmap, attribs);
+}
+
+EGLSurface fexfn_impl_libEGL_eglCreatePlatformWindowSurfaceEXT(EGLDisplay display, EGLConfig config, void* window, const EGLint* attribs) {
+ SyncGuestDisplay(display);
+ return fexldr_ptr_libEGL_eglCreatePlatformWindowSurfaceEXT(display, config, window, attribs);
+}
+
+EGLSurface fexfn_impl_libEGL_eglCreatePlatformPixmapSurfaceEXT(EGLDisplay display, EGLConfig config, void* pixmap, const EGLint* attribs) {
+ SyncGuestDisplay(display);
+ return fexldr_ptr_libEGL_eglCreatePlatformPixmapSurfaceEXT(display, config, pixmap, attribs);
+}
+
+EGLBoolean fexfn_impl_libEGL_eglCopyBuffers(EGLDisplay display, EGLSurface surface, EGLNativePixmapType pixmap) {
+ SyncGuestDisplay(display);
+ return fexldr_ptr_libEGL_eglCopyBuffers(display, surface, pixmap);
+}
+
EXPORTS(libEGL)
diff --git a/ThunkLibs/libEGL/libEGL_interface.cpp b/ThunkLibs/libEGL/libEGL_interface.cpp
index 27de16d..19f8b86 100644
--- a/ThunkLibs/libEGL/libEGL_interface.cpp
+++ b/ThunkLibs/libEGL/libEGL_interface.cpp
@@ -1,51 +1,170 @@
#include <common/GeneratorInterface.h>
+#define EGL_EGLEXT_PROTOTYPES 1
#include <EGL/egl.h>
+#include <EGL/eglext.h>
+#include <X11/Xlib.h>
template<auto>
struct fex_gen_config {
unsigned version = 1;
};
-// Function, parameter index, parameter type [optional]
template<auto, int, typename = void>
struct fex_gen_param {};
+template<typename>
+struct fex_gen_type {};
+
+template<>
+struct fex_gen_type<void> : fexgen::opaque_type {};
+template<>
+struct fex_gen_type<_XDisplay> : fexgen::opaque_type {};
+
+void EGL_SetGuestXSync(uintptr_t, uintptr_t);
+void EGL_SetGuestXDisplayString(uintptr_t, uintptr_t);
+template<>
+struct fex_gen_config<EGL_SetGuestXSync> : fexgen::custom_guest_entrypoint, fexgen::custom_host_impl {};
+template<>
+struct fex_gen_config<EGL_SetGuestXDisplayString> : fexgen::custom_guest_entrypoint, fexgen::custom_host_impl {};
+
template<>
struct fex_gen_config<eglBindAPI> {};
template<>
+struct fex_gen_config<eglBindTexImage> {};
+template<>
struct fex_gen_config<eglChooseConfig> {};
template<>
+struct fex_gen_config<eglClientWaitSync> {};
+template<>
+struct fex_gen_config<eglCreateContext> {};
+template<>
+struct fex_gen_config<eglCreateImage> {};
+template<>
+struct fex_gen_config<eglCreatePbufferFromClientBuffer> {};
+template<>
+struct fex_gen_config<eglCreatePbufferSurface> {};
+template<>
+struct fex_gen_config<eglCreateSync> {};
+template<>
struct fex_gen_config<eglDestroyContext> {};
template<>
+struct fex_gen_config<eglDestroyImage> {};
+template<>
struct fex_gen_config<eglDestroySurface> {};
template<>
+struct fex_gen_config<eglDestroySync> {};
+template<>
+struct fex_gen_config<eglGetConfigAttrib> {};
+template<>
+struct fex_gen_config<eglGetConfigs> {};
+template<>
+struct fex_gen_config<eglGetCurrentContext> {};
+template<>
+struct fex_gen_config<eglGetCurrentDisplay> {};
+template<>
+struct fex_gen_config<eglGetCurrentSurface> {};
+template<>
+struct fex_gen_config<eglGetError> {};
+template<>
+struct fex_gen_config<eglGetSyncAttrib> {};
+template<>
struct fex_gen_config<eglInitialize> {};
template<>
struct fex_gen_config<eglMakeCurrent> {};
template<>
+struct fex_gen_config<eglQueryAPI> {};
+template<>
+struct fex_gen_config<eglQueryContext> {};
+template<>
+struct fex_gen_config<eglQueryString> : fexgen::custom_guest_entrypoint {};
+template<>
struct fex_gen_config<eglQuerySurface> {};
template<>
+struct fex_gen_config<eglReleaseTexImage> {};
+template<>
+struct fex_gen_config<eglReleaseThread> {};
+template<>
struct fex_gen_config<eglSurfaceAttrib> {};
template<>
struct fex_gen_config<eglSwapBuffers> {};
template<>
+struct fex_gen_config<eglSwapInterval> {};
+template<>
struct fex_gen_config<eglTerminate> {};
template<>
-struct fex_gen_config<eglGetError> {};
+struct fex_gen_config<eglWaitClient> {};
template<>
-struct fex_gen_config<eglCreateContext> {};
+struct fex_gen_config<eglWaitGL> {};
template<>
-struct fex_gen_config<eglCreateWindowSurface> {};
+struct fex_gen_config<eglWaitNative> {};
template<>
-struct fex_gen_config<eglGetCurrentContext> {};
+struct fex_gen_config<eglWaitSync> {};
template<>
-struct fex_gen_config<eglGetCurrentDisplay> {};
+struct fex_gen_config<eglGetDisplay> : fexgen::custom_host_impl {};
template<>
-struct fex_gen_config<eglGetCurrentSurface> {};
+struct fex_gen_config<eglGetPlatformDisplay> : fexgen::custom_host_impl {};
+template<>
+struct fex_gen_config<eglCreateWindowSurface> : fexgen::custom_host_impl {};
+template<>
+struct fex_gen_config<eglCreatePixmapSurface> : fexgen::custom_host_impl {};
+template<>
+struct fex_gen_config<eglCreatePlatformWindowSurface> : fexgen::custom_host_impl {};
+template<>
+struct fex_gen_config<eglCreatePlatformPixmapSurface> : fexgen::custom_host_impl {};
+template<>
+struct fex_gen_config<eglCopyBuffers> : fexgen::custom_host_impl {};
+template<>
+struct fex_gen_param<eglGetDisplay, 0, EGLNativeDisplayType> : fexgen::ptr_passthrough {};
+
+namespace ext {
+template<auto>
+struct fex_gen_config {
+ const char* load_host_endpoint_via = "fex_egl_get_proc_address";
+};
-// EGLNativeDisplayType is a pointer to opaque data (wl_display/(X)Display/...)
template<>
-struct fex_gen_config<eglGetDisplay> {};
+struct fex_gen_config<eglSwapBuffersWithDamageKHR> {};
+template<>
+struct fex_gen_config<eglSwapBuffersWithDamageEXT> {};
+template<>
+struct fex_gen_config<eglSetDamageRegionKHR> {};
+template<>
+struct fex_gen_config<eglCreateImageKHR> {};
+template<>
+struct fex_gen_config<eglDestroyImageKHR> {};
+template<>
+struct fex_gen_config<eglCreateSyncKHR> {};
+template<>
+struct fex_gen_config<eglDestroySyncKHR> {};
+template<>
+struct fex_gen_config<eglClientWaitSyncKHR> {};
+template<>
+struct fex_gen_config<eglGetSyncAttribKHR> {};
+template<>
+struct fex_gen_config<eglWaitSyncKHR> {};
+template<>
+struct fex_gen_config<eglDupNativeFenceFDANDROID> {};
+template<>
+struct fex_gen_config<eglQueryDmaBufFormatsEXT> {};
+template<>
+struct fex_gen_config<eglQueryDmaBufModifiersEXT> {};
+template<>
+struct fex_gen_config<eglExportDMABUFImageMESA> {};
+template<>
+struct fex_gen_config<eglExportDMABUFImageQueryMESA> {};
+template<>
+struct fex_gen_config<eglQueryDisplayAttribEXT> {};
+template<>
+struct fex_gen_config<eglQueryDeviceStringEXT> {};
+template<>
+struct fex_gen_config<eglQueryDeviceAttribEXT> {};
+template<>
+struct fex_gen_config<eglQueryDevicesEXT> {};
+template<>
+struct fex_gen_config<eglGetPlatformDisplayEXT> : fexgen::custom_host_impl {};
+template<>
+struct fex_gen_config<eglCreatePlatformWindowSurfaceEXT> : fexgen::custom_host_impl {};
template<>
-struct fex_gen_param<eglGetDisplay, 0, EGLNativeDisplayType> : fexgen::assume_compatible_data_layout {};
+struct fex_gen_config<eglCreatePlatformPixmapSurfaceEXT> : fexgen::custom_host_impl {};
+}
diff --git a/ThunkLibs/libwayland-client/Guest.cpp b/ThunkLibs/libwayland-client/Guest.cpp
index 2f887a6..8fa6476 100644
--- a/ThunkLibs/libwayland-client/Guest.cpp
+++ b/ThunkLibs/libwayland-client/Guest.cpp
@@ -42,8 +42,11 @@ extern "C" const wl_interface wl_subsurface_interface {};
#include <charconv>
#include <cstdio>
#include <cstdarg>
+#include <cstdint>
+#include <cstdlib>
#include <cstring>
#include <string>
+#include <utility>
#include "common/Guest.h"
@@ -92,18 +95,39 @@ static uint64_t WaylandAllocateHostTrampolineForGuestListener(void (*callback)()
}
#define WL_CLOSURE_MAX_ARGS 20
+#define WAYLAND_UNIFORM_MAX_ARGS 17
+
+template<std::size_t... I>
+static uint64_t WaylandAllocateUniformHostTrampoline(void (*callback)(), std::index_sequence<I...>) {
+ using cb = void(void*, wl_proxy*, std::conditional_t<true, uintptr_t, std::integral_constant<std::size_t, I>>...);
+ return (uint64_t)(uintptr_t)(void*)AllocateHostTrampolineForGuestFunction((cb*)callback);
+}
+
+template<std::size_t... Counts>
+static uint64_t WaylandAllocateUniformHostTrampoline(void (*callback)(), std::size_t count, std::index_sequence<Counts...>) {
+ using allocator = uint64_t (*)(void (*)());
+ static constexpr allocator allocators[] = {
+ [](void (*cb)()) { return WaylandAllocateUniformHostTrampoline(cb, std::make_index_sequence<Counts> {}); }...};
+ return allocators[count](callback);
+}
extern "C" int wl_proxy_add_listener(wl_proxy* proxy, void (**callback)(void), void* data) {
// Replace guest-provided callback table with host-callable function pointers
// NOTE: A reference to this table is stored in the wl_proxy, so the data
// must remain valid until the proxy is destroyed (or another listener
// is added)
- delete[] (uint64_t*)wl_proxy_get_listener(proxy); // Delete previous substitute, if any
- auto host_callbacks = new uint64_t[WL_CLOSURE_MAX_ARGS];
+ if (wl_proxy_get_listener(proxy)) {
+ fprintf(stderr, "proxy %p already has listener\n", proxy);
+ return -1;
+ }
+ auto host_callbacks = new uint64_t[std::max(fex_wl_get_interface_event_count(proxy), WL_CLOSURE_MAX_ARGS)];
for (int i = 0; i < fex_wl_get_interface_event_count(proxy); ++i) {
- char event_signature[16];
- fex_wl_get_interface_event_signature(proxy, i, event_signature);
+ char event_signature[64];
+ if (fex_wl_get_interface_event_signature(proxy, i, event_signature, sizeof(event_signature)) >= sizeof(event_signature)) {
+ fprintf(stderr, "TODO: Unknown wayland event signature descriptor %s\n", event_signature);
+ std::abort();
+ }
auto signature2 = std::string_view {event_signature};
// A leading number indicates the minimum protocol version
@@ -227,13 +251,19 @@ extern "C" int wl_proxy_add_listener(wl_proxy* proxy, void (**callback)(void), v
} else if (signature == "sii") {
// E.g. zwp_text_input_v3::preedit_string
host_callbacks[i] = WaylandAllocateHostTrampolineForGuestListener<'s', 'i', 'i'>(callback[i]);
+ } else if (signature.size() <= WAYLAND_UNIFORM_MAX_ARGS) {
+ host_callbacks[i] = WaylandAllocateUniformHostTrampoline(callback[i], signature.size(), std::make_index_sequence<WAYLAND_UNIFORM_MAX_ARGS + 1> {});
} else {
fprintf(stderr, "TODO: Unknown wayland event signature descriptor %s\n", signature.data());
std::abort();
}
}
- return fexfn_pack_wl_proxy_add_listener(proxy, (void (**)())host_callbacks, data);
+ int result = fexfn_pack_wl_proxy_add_listener(proxy, (void (**)())host_callbacks, data);
+ if (result != 0) {
+ delete[] host_callbacks;
+ }
+ return result;
}
extern "C" void wl_proxy_destroy(wl_proxy* proxy) {
@@ -353,6 +383,92 @@ extern "C" void wl_log_set_handler_client(wl_log_func_t handler) {
// Ignore
}
+extern "C" void wl_list_init(wl_list* list) {
+ list->prev = list;
+ list->next = list;
+}
+
+extern "C" void wl_list_insert(wl_list* list, wl_list* elm) {
+ elm->prev = list;
+ elm->next = list->next;
+ list->next = elm;
+ elm->next->prev = elm;
+}
+
+extern "C" void wl_list_remove(wl_list* elm) {
+ elm->prev->next = elm->next;
+ elm->next->prev = elm->prev;
+ elm->next = nullptr;
+ elm->prev = nullptr;
+}
+
+extern "C" int wl_list_length(const wl_list* list) {
+ int count = 0;
+ for (auto e = list->next; e != list; e = e->next) {
+ ++count;
+ }
+ return count;
+}
+
+extern "C" int wl_list_empty(const wl_list* list) {
+ return list->next == list;
+}
+
+extern "C" void wl_list_insert_list(wl_list* list, wl_list* other) {
+ if (wl_list_empty(other)) {
+ return;
+ }
+ other->next->prev = list;
+ other->prev->next = list->next;
+ list->next->prev = other->prev;
+ list->next = other->next;
+}
+
+extern "C" void wl_array_init(wl_array* array) {
+ memset(array, 0, sizeof(*array));
+}
+
+extern "C" void wl_array_release(wl_array* array) {
+ free(array->data);
+ array->data = (void*)4;
+}
+
+extern "C" void* wl_array_add(wl_array* array, size_t size) {
+ if (size > SIZE_MAX - array->size) {
+ return nullptr;
+ }
+ size_t needed = array->size + size;
+ size_t alloc = array->alloc > 0 ? array->alloc : 16;
+ while (alloc < needed) {
+ alloc = alloc > SIZE_MAX / 2 ? needed : alloc * 2;
+ }
+ if (array->alloc < alloc) {
+ void* data = array->alloc > 0 ? realloc(array->data, alloc) : malloc(alloc);
+ if (!data) {
+ return nullptr;
+ }
+ array->data = data;
+ array->alloc = alloc;
+ }
+ void* p = (char*)array->data + array->size;
+ array->size += size;
+ return p;
+}
+
+extern "C" int wl_array_copy(wl_array* array, wl_array* source) {
+ if (array->size < source->size) {
+ if (!wl_array_add(array, source->size - array->size)) {
+ return -1;
+ }
+ } else {
+ array->size = source->size;
+ }
+ if (source->size > 0) {
+ memcpy(array->data, source->data, source->size);
+ }
+ return 0;
+}
+
void OnInit() {
fex_wl_exchange_interface_pointer(const_cast<wl_interface*>(&wl_output_interface), "wl_output_interface");
diff --git a/ThunkLibs/libwayland-client/Host.cpp b/ThunkLibs/libwayland-client/Host.cpp
index 68c2ded..25f964c 100644
--- a/ThunkLibs/libwayland-client/Host.cpp
+++ b/ThunkLibs/libwayland-client/Host.cpp
@@ -22,6 +22,7 @@ $end_info$
#include <map>
#include <span>
#include <string>
+#include <utility>
#include <ranges>
@@ -166,6 +167,7 @@ static wl_proxy* fexfn_impl_libwayland_client_wl_proxy_create(wl_proxy* proxy, g
}
#define WL_CLOSURE_MAX_ARGS 20
+#define WAYLAND_UNIFORM_MAX_ARGS 17
static auto fex_wl_remap_argument_list(guest_layout<wl_argument*> args, const wl_message& message) {
#ifndef IS_32BIT_THUNK
// Cast to host layout and return as std::span
@@ -309,6 +311,21 @@ static void WaylandFinalizeHostTrampolineForGuestListener(void (*callback)()) {
FinalizeHostTrampolineForGuestFunction((cb*)callback);
}
+
+template<std::size_t... I>
+static void WaylandFinalizeUniformHostTrampoline(void (*callback)(), std::index_sequence<I...>) {
+ using cb = void(void*, wl_proxy*, std::conditional_t<true, uint64_t, std::integral_constant<std::size_t, I>>...);
+ FinalizeHostTrampolineForGuestFunction((cb*)callback);
+}
+
+template<std::size_t... Counts>
+static void WaylandFinalizeUniformHostTrampoline(void (*callback)(), std::size_t count, std::index_sequence<Counts...>) {
+ using finalizer = void (*)(void (*)());
+ static constexpr finalizer finalizers[] = {
+ [](void (*cb)()) { WaylandFinalizeUniformHostTrampoline(cb, std::make_index_sequence<Counts> {}); }...};
+ finalizers[count](callback);
+}
+
extern "C" int
fexfn_impl_libwayland_client_wl_proxy_add_listener(struct wl_proxy* proxy, guest_layout<void (**)(void)> callback_table_raw, void* data) {
auto interface = get_proxy_interface(proxy);
@@ -446,6 +463,8 @@ fexfn_impl_libwayland_client_wl_proxy_add_listener(struct wl_proxy* proxy, guest
WaylandFinalizeHostTrampolineForGuestListener<'s', 'i', 'i'>(callback);
} else if (signature == "ss") {
WaylandFinalizeHostTrampolineForGuestListener<'s', 's'>(callback);
+ } else if (signature.size() <= WAYLAND_UNIFORM_MAX_ARGS) {
+ WaylandFinalizeUniformHostTrampoline(callback, signature.size(), std::make_index_sequence<WAYLAND_UNIFORM_MAX_ARGS + 1> {});
} else {
fprintf(stderr, "TODO: Unknown wayland event signature descriptor %s\n", signature.data());
std::abort();
@@ -514,8 +533,35 @@ void fexfn_impl_libwayland_client_fex_wl_get_interface_event_name(wl_proxy* prox
strcpy(out, get_proxy_interface(proxy)->events[i].name);
}
-void fexfn_impl_libwayland_client_fex_wl_get_interface_event_signature(wl_proxy* proxy, int i, char* out) {
- strcpy(out, get_proxy_interface(proxy)->events[i].signature);
+size_t fexfn_impl_libwayland_client_fex_wl_get_interface_event_signature(wl_proxy* proxy, int i, char* out, size_t size) {
+ const char* signature = get_proxy_interface(proxy)->events[i].signature;
+ size_t length = strlen(signature);
+ if (size > 0) {
+ size_t copied = std::min(length, size - 1);
+ memcpy(out, signature, copied);
+ out[copied] = '\0';
+ }
+ return length;
+}
+
+uint32_t fexfn_impl_libwayland_client_wl_display_get_protocol_error(wl_display* display, guest_layout<const wl_interface**> guest_interface,
+ uint32_t* id) {
+ const wl_interface* host_interface = nullptr;
+ auto code = fexldr_ptr_libwayland_client_wl_display_get_protocol_error(display, &host_interface, id);
+ if (!guest_interface.force_get_host_pointer()) {
+ return code;
+ }
+ uintptr_t result = 0;
+ for (auto& [guest, host] : guest_to_host_interface) {
+ if (host == host_interface) {
+ result = reinterpret_cast<uintptr_t>(guest);
+ }
+ }
+ if (!result) {
+ result = reinterpret_cast<uintptr_t>(host_interface);
+ }
+ guest_interface.get_pointer()->data = result;
+ return code;
}
EXPORTS(libwayland_client)
diff --git a/ThunkLibs/libwayland-client/libwayland-client_interface.cpp b/ThunkLibs/libwayland-client/libwayland-client_interface.cpp
index 575d2e1..9723a3c 100644
--- a/ThunkLibs/libwayland-client/libwayland-client_interface.cpp
+++ b/ThunkLibs/libwayland-client/libwayland-client_interface.cpp
@@ -83,6 +83,16 @@ struct fex_gen_config<wl_display_get_fd> {};
template<>
struct fex_gen_config<wl_event_queue_destroy> {};
+template<>
+struct fex_gen_config<wl_event_queue_get_name> {};
+template<>
+struct fex_gen_config<wl_display_create_queue_with_name> {};
+template<>
+struct fex_gen_config<wl_display_set_max_buffer_size> {};
+template<>
+struct fex_gen_config<wl_display_get_protocol_error> : fexgen::custom_host_impl {};
+template<>
+struct fex_gen_param<wl_display_get_protocol_error, 1, const wl_interface**> : fexgen::ptr_passthrough {};
template<>
struct fex_gen_config<wl_proxy_add_listener> : fexgen::custom_host_impl, fexgen::custom_guest_entrypoint {};
@@ -101,6 +111,10 @@ struct fex_gen_config<wl_proxy_create_wrapper> {};
template<>
struct fex_gen_config<wl_proxy_get_class> {};
template<>
+struct fex_gen_config<wl_proxy_get_display> {};
+template<>
+struct fex_gen_config<wl_proxy_get_queue> {};
+template<>
struct fex_gen_config<wl_proxy_get_id> {};
template<>
struct fex_gen_config<wl_proxy_get_listener> {};
@@ -164,6 +178,6 @@ struct fex_gen_config<fex_wl_get_interface_event_count> : fexgen::custom_host_im
void fex_wl_get_interface_event_name(wl_proxy*, int, char*);
template<>
struct fex_gen_config<fex_wl_get_interface_event_name> : fexgen::custom_host_impl {};
-void fex_wl_get_interface_event_signature(wl_proxy*, int, char*);
+size_t fex_wl_get_interface_event_signature(wl_proxy*, int, char*, size_t);
template<>
struct fex_gen_config<fex_wl_get_interface_event_signature> : fexgen::custom_host_impl {};
diff --git a/ThunkLibs/libwayland-egl/Guest.cpp b/ThunkLibs/libwayland-egl/Guest.cpp
new file mode 100644
index 0000000..300a8fc
--- /dev/null
+++ b/ThunkLibs/libwayland-egl/Guest.cpp
@@ -0,0 +1,7 @@
+#include <wayland-egl.h>
+
+#include "common/Guest.h"
+
+#include "thunkgen_guest_libwayland-egl.inl"
+
+LOAD_LIB(libwayland-egl)
diff --git a/ThunkLibs/libwayland-egl/Host.cpp b/ThunkLibs/libwayland-egl/Host.cpp
new file mode 100644
index 0000000..81ad83b
--- /dev/null
+++ b/ThunkLibs/libwayland-egl/Host.cpp
@@ -0,0 +1,8 @@
+#include <wayland-egl.h>
+
+#include "common/Host.h"
+#include <dlfcn.h>
+
+#include "thunkgen_host_libwayland-egl.inl"
+
+EXPORTS(libwayland_egl)
diff --git a/ThunkLibs/libwayland-egl/libwayland-egl_interface.cpp b/ThunkLibs/libwayland-egl/libwayland-egl_interface.cpp
new file mode 100644
index 0000000..bc5d743
--- /dev/null
+++ b/ThunkLibs/libwayland-egl/libwayland-egl_interface.cpp
@@ -0,0 +1,25 @@
+#include <common/GeneratorInterface.h>
+
+#include <wayland-egl.h>
+
+template<auto>
+struct fex_gen_config {
+ unsigned version = 1;
+};
+
+template<typename>
+struct fex_gen_type {};
+
+template<>
+struct fex_gen_type<wl_egl_window> : fexgen::opaque_type {};
+template<>
+struct fex_gen_type<wl_surface> : fexgen::opaque_type {};
+
+template<>
+struct fex_gen_config<wl_egl_window_create> {};
+template<>
+struct fex_gen_config<wl_egl_window_destroy> {};
+template<>
+struct fex_gen_config<wl_egl_window_resize> {};
+template<>
+struct fex_gen_config<wl_egl_window_get_attached_size> {};
+19
View File
@@ -425,3 +425,22 @@ at a pointer that never left the top-left corner. Steam picks Disabled for some
cursor followed the mouse while every click landed at (0,0). In Disabled the nested pointer now warps the X pointer as
in the other modes; real fingers are still ignored. `tools/tests/test_gamescope_disabled_touch_mouse.py` compiles the
branch from this patch.
## 0142 Steam is entered at the corner it is reset to
When Steam's window takes focus with `bResetToCorner`, gamescope parks the pointer in its bottom-right corner so
nothing in Big Picture is hovered and the controller owns the UI. Upstream fe7f21c (3.16.24) moved
`wlserver_mousefocus` ahead of that reset, so the window is first entered under the current pointer, then warped to
its centre (`wlserver_mousewarp`, synthetic), then moved to the corner. SteamOS's 3.16.23 still resets before focus,
so its motions reach no window and the X pointer stays at (0,0). On upstream 3.16.29 they reach Steam: on a Steam Deck
the pointer is at (1279,799) right after focus. The Deck shows no hover because Big Picture's page exists about 1 s
before the reset. On a Retroid Pocket Duo the page is created at the same moment, Chromium keeps the centre position
as its hover, and the second library tile stayed highlighted on every start (4 of 4).
Steam is now entered at the corner. The centre is still stored in `mouse_surface_cursorx/y`, so the gamepad cursor
starts there as before, but no motion is sent for it. The fake pointer position stays in the corner. Only the
`bResetToCorner` path changes. Other windows are entered under the pointer as upstream does.
With the patch, the Duo starts with only the bottom bar under the parked pointer hovered and controller focus on the
first tile (4 of 4 starts), and returns from a game the same way (3 of 3). Making 0100 ignore the X server's initial
pointer instead was tried and rejected: the centre motion still arrived, and the header or search bar ended up hovered.
@@ -0,0 +1,31 @@
diff --git a/src/steamcompmgr.cpp b/src/steamcompmgr.cpp
--- a/src/steamcompmgr.cpp
+++ b/src/steamcompmgr.cpp
@@ -5790,7 +5790,16 @@
if ( win_surface(pFocus->inputFocusWindow) != nullptr && pFocus->cursor )
{
- wlserver_mousefocus( pFocus->inputFocusWindow->main_surface(), pFocus->cursor->x(), pFocus->cursor->y() );
+ int nEnterX = pFocus->cursor->x();
+ int nEnterY = pFocus->cursor->y();
+ // A window reset to the corner below must not first be entered under the cursor:
+ // a page that loads during the reset keeps that position as its hover.
+ if ( pFocus->inputFocusWindow->GetFocus()->bResetToCorner )
+ {
+ nEnterX = pFocus->inputFocusWindow->GetGeometry().nWidth - 1;
+ nEnterY = pFocus->inputFocusWindow->GetGeometry().nHeight - 1;
+ }
+ wlserver_mousefocus( pFocus->inputFocusWindow->main_surface(), nEnterX, nEnterY );
focus_log.debugf( "Setting mouse focus to: %s (%x)", pFocus->inputFocusWindow->debug_name(), pFocus->inputFocusWindow->id() );
}
@@ -5813,7 +5822,8 @@
if ( pFocus->inputFocusWindow->GetFocus()->bResetToCorner )
{
wlserver_lock();
- wlserver_mousewarp( pFocus->inputFocusWindow->GetGeometry().nWidth / 2, pFocus->inputFocusWindow->GetGeometry().nHeight / 2, 0, true );
+ wlserver.mouse_surface_cursorx = pFocus->inputFocusWindow->GetGeometry().nWidth / 2;
+ wlserver.mouse_surface_cursory = pFocus->inputFocusWindow->GetGeometry().nHeight / 2;
wlserver_fake_mouse_pos( pFocus->inputFocusWindow->GetGeometry().nWidth - 1, pFocus->inputFocusWindow->GetGeometry().nHeight - 1 );
wlserver_unlock();
}
+6 -2
View File
@@ -38,8 +38,9 @@ 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
cat > "$dd_layout/org.kde.plasma.desktop-layout.js" <<'LAYOUT'
if 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";
@@ -111,10 +112,13 @@ 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 [ "$(cat "$dd_panel_stamp" 2>/dev/null)" != steamos-2 ]; then
if [ "$dd_layout_installed" -eq 1 ] && [ "$(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
+27
View File
@@ -0,0 +1,27 @@
#!/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
@@ -0,0 +1,25 @@
{
"$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"
]
}
@@ -115,7 +115,7 @@ def link_libraries():
common = os.path.join(library, "steamapps", "common")
link = os.path.join(HOME, label)
if os.path.isdir(common):
if os.path.islink(link) and os.readlink(link) == common:
if os.path.islink(link) and os.readlink(link) == common and os.path.isdir(os.path.join(link, ".")):
continue
if os.path.islink(link) or os.path.isfile(link):
os.unlink(link)
@@ -10,7 +10,7 @@ free_name() {
share() {
local android=$HOME/Storage/$1 link=$HOME/$2 f
[ -d "$android" ] && [ -w "$android" ] || return 0
[ "$(readlink "$link" 2>/dev/null)" = "$android" ] && return 0
[ "$(readlink "$link" 2>/dev/null)" = "$android" ] && [ -d "$link/." ] && return 0
if [ -L "$link" ]; then
rm -f "$link"
elif [ -d "$link" ]; then
@@ -71,6 +71,7 @@ RUNTIME_LIBRARIES = (("libc.so.6", b"GLIBC_"), ("libstdc++.so.6", b"GLIBCXX_"))
VERSION_NAME = re.compile(rb"GLIBC(?:XX)?_[0-9][0-9.]*[0-9]")
BUNDLE_DEPTH = 3
THUNKS = {"GL": 1, "Vulkan": 1}
WAYLAND_THUNKS = {"WaylandClient": "libwayland-client-guest.so", "EGL": "libEGL-guest.so", "WaylandEGL": "libwayland-egl-guest.so"}
X86 = {3: "i386", 62: "x86_64"}
ARM = {40: "arm", 183: "arm64"}
SCAN_DEPTH = 4
@@ -448,13 +449,20 @@ def install_preloads(root):
write_if_changed(os.path.join(root, "etc", "asound.conf"), ASOUND_CONF)
def enabled_thunks(fex):
thunks = dict(THUNKS)
if all(os.path.isfile(os.path.join(fex["guest_thunks"], name)) for name in WAYLAND_THUNKS.values()):
thunks.update(dict.fromkeys(WAYLAND_THUNKS, 1))
return thunks
def write_config(fex, root):
config = {"Config": {"RootFS": root}}
if fex["host_thunks"] and fex["guest_thunks"] and fex["thunks_db"]:
config["Config"]["ThunkHostLibs"] = fex["host_thunks"]
config["Config"]["ThunkGuestLibs"] = fex["guest_thunks"]
config["ThunksDB"] = dict(THUNKS)
write_if_changed(os.path.join(CONFIG_DIR, "ThunksConfig.json"), json.dumps({"ThunksDB": dict(THUNKS)}, indent=2) + "\n")
config["ThunksDB"] = enabled_thunks(fex)
write_if_changed(os.path.join(CONFIG_DIR, "ThunksConfig.json"), json.dumps({"ThunksDB": config["ThunksDB"]}, indent=2) + "\n")
write_if_changed(os.path.join(CONFIG_DIR, "Config.json"), json.dumps(config, indent=2) + "\n")
@@ -29,14 +29,19 @@ fex_install() {
return 1
fi
(cd "$tmp/root" && find . ! -type d) > "$tmp/files"
for d in usr/local/share/fex-emu/GuestThunks usr/local/share/fex-emu/GuestThunks_32 usr/local/lib/fex-emu/HostThunks usr/local/lib/fex-emu/HostThunks_32; do
[ -d "$tmp/root/$d" ] && [ -d "$dst$d" ] || continue
(cd "$dst" && find "$d" ! -type d) | while IFS= read -r f; do grep -qxF "./$f" "$tmp/files" || echo "$f"; done
done > "$tmp/stale"
mkdir "$tmp/old"
while IFS= read -r f; do
f=${f#./}
if [ -e "$dst$f" ] || [ -L "$dst$f" ]; then
cp -a --parents "$dst$f" "$tmp/old" || { echo "== FEX $tag: could not keep $dst$f aside" >&2; rm -rf "$tmp"; return 1; }
fi
done < "$tmp/files"
if tar -C "$tmp/root" -c . | tar -C "$dst" -x && fex_loads "$dst" &&
done < <(cat "$tmp/files" "$tmp/stale")
if tar -C "$tmp/root" -c . | tar -C "$dst" -x &&
( while IFS= read -r f; do rm -f "$dst$f" || exit 1; done < "$tmp/stale" ) && fex_loads "$dst" &&
mkdir -p "${dst}usr/local/share/fex-emu" && echo "$tag" > "${dst}usr/local/share/fex-emu/.droiddeck-tag"; then
rm -rf "$tmp"
return 0
@@ -1169,7 +1169,10 @@ case $mode in
"${DD_X64_HOME:-$HOME/.droiddeck-x64}/.local/share/Steam" &&
echo "$DD_SHADER_PRECACHE" > "$HOME/.dd-shader-precache-applied" || true
fi
if [ "$steam_x64" = 0 ] && [ ! -f "$steam_root/steamapps/appmanifest_4427310.acf" ]; then
if [ "$steam_x64" = 0 ] && [ ! -f "$steam_root/steamapps/appmanifest_4427310.acf" ] &&
! steam-compatibility "$steam_root" --valve-proton-needed; then
step "leaving Valve's ARM64 Proton until a title needs it"
elif [ "$steam_x64" = 0 ] && [ ! -f "$steam_root/steamapps/appmanifest_4427310.acf" ]; then
step "asking the client to fetch the ARM64 Proton"
set -- "$@" steam://install/4427310
(
@@ -966,6 +966,7 @@ class Helper:
self.fex_asked = set()
self.tools_asked = {}
self.tools_checked = None
self.valve_names = None
self.vr_launch = None
self.chooser = None
self.controls_state = None
@@ -1256,6 +1257,10 @@ class Helper:
page.compat("set(%d, %s)" % (int(app), json.dumps(tool if tool is not None else "")))
say("%s -> %s" % ("default" if app == "0" else "app %s" % app,
tool if tool is not None else "Steam native default"))
names = set(dict(current, **changes).values()) | {default}
if COMPAT["uses_valve_proton"](names) and not COMPAT["uses_valve_proton"](self.valve_names or ()):
self.tools_checked = None
self.valve_names = names
state.update(
auto={app: tool for app, tool in auto.items() if tool is not COMPAT["NATIVE_CHOICE"]},
native_choices=sorted(refused_native | {app for app, tool in auto.items() if tool is COMPAT["NATIVE_CHOICE"]}),
@@ -1276,7 +1281,8 @@ class Helper:
self.tools_checked = now
if COMPAT["game_running"]():
return
for app, action in COMPAT["tool_downloads"](self.steam_root):
needed = COMPAT["valve_proton_needed"](self.steam_root, self.valve_names)
for app, action in COMPAT["tool_downloads"](self.steam_root, needed):
if now - self.tools_asked.get(app, -TOOL_RETRY_SECONDS) < TOOL_RETRY_SECONDS:
continue
self.tools_asked[app] = now
@@ -26,6 +26,9 @@ SNIPER_APPID = "1628350"
SLR4_APPID = "4183110"
FEX_DEPENDENCIES = (FEX_APPID, SNIPER_APPID, SLR4_APPID)
REQUIRED_TOOLS = (PROTON_ARM64_APPID,) + FEX_DEPENDENCIES
# "0" = the app's "Valve Proton only when needed": Valve's ARM64 Proton is fetched only for a title or
# default set to a tool built from it, or while no own Proton build is installed.
VALVE_PROTON_ENV = "DD_VALVE_PROTON"
# Linux builds that bundle an arm64 binary their launcher starts; Steamworks offers no arm64
# launch-option architecture, so appinfo cannot say so (#1774).
FEX_DEFAULT_APPS = frozenset({"4385780"})
@@ -1008,11 +1011,33 @@ def manifest_flags(tokens):
return 0
def tool_downloads(steam_root):
def valve_proton_on_demand():
return os.environ.get(VALVE_PROTON_ENV) == "0"
def uses_valve_proton(names):
return any(name == TOOL or VALVE_DEPOTS.get(name) == SOURCES[0] for name in names if name)
def valve_proton_needed(steam_root, names=None):
if not valve_proton_on_demand():
return True
if not own_builds(tool_catalog(steam_root)):
return True
if names is None:
names = set((read_config_mapping(os.path.join(steam_root, "config", "config.vdf")) or {}).values())
names.add(read_json(state_path("state.json")).get("default"))
return uses_valve_proton(names)
def tool_downloads(steam_root, valve_needed=None):
wanted = []
for app in REQUIRED_TOOLS:
tokens = app_manifest(steam_root, app)
if tokens is None:
if app == PROTON_ARM64_APPID and not (
valve_proton_needed(steam_root) if valve_needed is None else valve_needed):
continue
wanted.append((app, "install"))
elif not manifest_flags(tokens) & FULLY_INSTALLED or manifest_flags(tokens) & UPDATE_REQUIRED:
wanted.append((app, "update"))
@@ -1755,6 +1780,8 @@ def x64_repoint(steam_root, tool, live=False):
def main():
steam_root = sys.argv[1]
if "--valve-proton-needed" in sys.argv[2:]:
sys.exit(0 if valve_proton_needed(steam_root) else 1)
if "--x64" in sys.argv[2:]:
x64_repoint(steam_root, os.environ.get("DD_COMPAT_TOOL"), "--live" in sys.argv[2:])
return
@@ -1773,6 +1800,7 @@ def main():
build_tool(os.path.join(tools, name), depot, sources, name)
print("steam-compatibility: registered %s (%s)" % (
name, "depot %s present" % os.path.basename(depot) if depot else
"no ARM64 Proton depot yet; fetched when a title needs it" if valve_proton_on_demand() else
"no ARM64 Proton depot yet; the session asks the client to fetch it"))
build_fex_tool(os.path.join(tools, FEX_TOOL))
print("steam-compatibility: registered %s" % FEX_TOOL)
+3
View File
@@ -445,12 +445,15 @@ static void load_app_ids(void) {
__atomic_store_n(&g_app_uid, uid, __ATOMIC_RELAXED);
}
#define ANDROID_MEDIA_RW_GID ((gid_t)1023)
static void present_owner_as_root(uid_t *uid, gid_t *gid) {
if (__atomic_load_n(&g_app_uid, __ATOMIC_RELAXED) == (uid_t)-1) load_app_ids();
uid_t app_uid = __atomic_load_n(&g_app_uid, __ATOMIC_RELAXED);
gid_t app_gid = __atomic_load_n(&g_app_gid, __ATOMIC_RELAXED);
if (app_uid == (uid_t)-1) return;
if (uid && *uid == app_uid) *uid = 0;
if (uid && gid && *gid == ANDROID_MEDIA_RW_GID) *uid = 0;
if (gid && *gid == app_gid) *gid = 0;
}
+284 -8
View File
@@ -44,6 +44,7 @@ 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
@@ -56,6 +57,7 @@ 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;
@@ -297,10 +299,243 @@ 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).
static const char *resolve_bind_links(const char *host, size_t src_len, char *buffer, size_t bufsize) {
#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) {
#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];
@@ -324,18 +559,22 @@ static const char *resolve_bind_links(const char *host, size_t src_len, char *bu
return buffer;
}
#else
(void)src_len; (void)bufsize;
(void)src_len; (void)bufsize; (void)check_plain;
#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_bind_links(host, (size_t)(devices - host) + 11, buffer, bufsize);
return resolve_links_after(host, (size_t)(devices - host) + 11, buffer, bufsize, 0);
}
// Maps an absolute Ubuntu path into the rootfs. Returns `path` (possibly advanced past
@@ -390,7 +629,14 @@ 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);
ddnatv_append(buffer, bufsize, n, path + b->dst_len, strlen(path + b->dst_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
return resolve_bind_links(buffer, b->src_len, buffer, bufsize);
}
}
@@ -455,17 +701,21 @@ 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(const char *path, char *out, size_t outsz) {
static const char *follow_guest_link_host(const char *path, char *out, size_t outsz, char *host_out, size_t host_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 = raw_readlinkat(AT_FDCWD, host, target, sizeof(target) - 1);
if (n <= 0) return cur;
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;
}
target[n] = '\0';
n = (long)link_root_guest_target(target, (size_t)n);
char joined[PATH_MAX];
@@ -504,11 +754,15 @@ static const char *follow_guest_link(const char *path, char *out, size_t outsz)
}
return cur;
#else
(void)out; (void)outsz;
(void)out; (void)outsz; (void)host_out; (void)host_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.
@@ -827,6 +1081,27 @@ static void ddnatv_build_at_dirs(void) {
}
#if defined(__aarch64__)
static int stays_in_plain_bind(const char *host, const char *rel) {
if (get_rootfs_subpath(host)) return 0;
struct ddnatv_bind *best = NULL;
for (int i = 0; i < g_nbinds; i++) {
struct ddnatv_bind *b = &g_binds[i];
if (b->identity || !is_path_prefix(host, b->src, b->src_len)) continue;
if (!best || b->src_len > best->src_len) best = b;
}
if (!best) return 0;
for (int i = 0; i < g_nbinds; i++) {
struct ddnatv_bind *cover = &g_binds[i];
if (cover->identity || !is_path_prefix(host, cover->src, cover->src_len)) continue;
for (int j = 0; j < g_nbinds; j++) {
struct ddnatv_bind *b = &g_binds[j];
if (j != i && b->dst_len >= cover->dst_len && is_path_prefix(b->dst, cover->dst, cover->dst_len))
return 0;
}
}
return !climbs_past_root(host + best->src_len, rel) && bind_holds_no_links(best);
}
static const char *map_parent_walk(int dirfd, const char *rel, char *buf, size_t size) {
char link[32], host[PATH_MAX], dir_buf[PATH_MAX], guest[PATH_MAX];
if (dirfd == AT_FDCWD) ddnatv_copy_cstr(link, sizeof(link), "/proc/self/cwd");
@@ -834,6 +1109,7 @@ static const char *map_parent_walk(int dirfd, const char *rel, char *buf, size_t
long n = raw_readlinkat(AT_FDCWD, link, host, sizeof(host) - 1);
if (n <= 0 || host[0] != '/') return NULL;
host[n] = '\0';
if (stays_in_plain_bind(host, rel)) return NULL;
const char *dir = guest_path_of_host_dir(host, dir_buf, sizeof(dir_buf));
if (!dir || strcmp(dir, host) == 0) return NULL;
if (get_rootfs_subpath(host) && !climbs_past_root(dir, rel)) return NULL;
+10 -2
View File
@@ -37,6 +37,9 @@ 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);
@@ -776,13 +779,16 @@ 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)) return host;
if (is_android_host_path(path) || known_plain(host)) return host;
char target[PATH_MAX];
long n = raw_readlinkat(AT_FDCWD, host, target, sizeof(target) - 1);
if (n <= 0 || target[0] != '/') return host;
@@ -805,7 +811,9 @@ static const char *rewrite_path_follow(const char *path, char *buffer, size_t bu
path = from_source;
}
char guest[PATH_MAX];
const char *followed = follow_guest_link(path, guest, sizeof(guest));
buffer[0] = '\0';
const char *followed = follow_guest_link_host(path, guest, sizeof(guest), buffer, bufsize);
if (followed == path && buffer[0]) return buffer;
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
+3 -1
View File
@@ -27,10 +27,12 @@ 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', 'kwin_wayland_wrapper']:
for name in ['droiddeck-desktop', 'droiddeck-gpu', 'droiddeck-desktop-gpu', 'droiddeck-device-info',
'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
@@ -0,0 +1,28 @@
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()
+59
View File
@@ -0,0 +1,59 @@
import os
import subprocess
import tempfile
import unittest
from pathlib import Path
SCRIPT = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-downloads"
class DesktopDownloadsTest(unittest.TestCase):
def run_script(self, home, shim=None):
env = dict(os.environ, HOME=str(home))
if shim:
env["PATH"] = f"{shim}:{env['PATH']}"
subprocess.run(["bash", str(SCRIPT)], env=env, check=True)
def make_home(self, temp):
home = Path(temp) / "home"
for name in ("Download", "Documents"):
(home / "Storage" / name).mkdir(parents=True)
return home
def test_links_to_the_android_folders_are_made(self):
with tempfile.TemporaryDirectory() as temp:
home = self.make_home(temp)
self.run_script(home)
self.assertEqual(str(home / "Storage/Download"), os.readlink(home / "Downloads"))
self.assertEqual(str(home / "Storage/Documents"), os.readlink(home / "Documents"))
def test_working_links_are_kept(self):
with tempfile.TemporaryDirectory() as temp:
home = self.make_home(temp)
self.run_script(home)
before = os.lstat(home / "Downloads").st_ino
self.run_script(home)
self.assertEqual(before, os.lstat(home / "Downloads").st_ino)
def test_links_that_name_the_folder_but_cannot_be_walked_are_made_again(self):
with tempfile.TemporaryDirectory() as temp:
home = self.make_home(temp)
for link in ("Downloads", "Documents"):
os.symlink(str(Path(temp) / "gone"), home / link)
shim = Path(temp) / "bin"
shim.mkdir()
(shim / "readlink").write_text(
'#!/bin/bash\ncase "${@: -1}" in\n'
f' "{home}/Downloads") echo "{home}/Storage/Download" ;;\n'
f' "{home}/Documents") echo "{home}/Storage/Documents" ;;\n'
' *) exec /usr/bin/readlink "$@" ;;\nesac\n')
(shim / "readlink").chmod(0o755)
self.run_script(home, shim)
for link, folder in (("Downloads", "Download"), ("Documents", "Documents")):
self.assertEqual(str(home / "Storage" / folder), os.readlink(home / link))
self.assertTrue((home / link / ".").is_dir())
self.assertEqual([], sorted(p.name for p in home.iterdir() if ".old." in p.name))
if __name__ == "__main__":
unittest.main()
+49 -2
View File
@@ -19,10 +19,11 @@ def block(first, last):
return DESKTOP[start:DESKTOP.index(last, start) + len(last)]
def run(script, home):
def run(script, home, layout_installed=True):
environment = {key: value for key, value in os.environ.items() if key != 'XDG_CONFIG_HOME'}
environment['HOME'] = str(home)
result = subprocess.run(['bash', '-c', script], env=environment, capture_output=True, text=True, timeout=5)
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)
if result.returncode != 0:
raise AssertionError(result.stderr)
@@ -101,6 +102,52 @@ 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'))
+53
View File
@@ -1188,6 +1188,22 @@ class LaunchTest(FexTestCase):
thunks = json.loads((self.home / ".local/share/droiddeck-fex/config/ThunksConfig.json").read_text())
self.assertEqual(thunks, {"ThunksDB": {"GL": 1, "Vulkan": 1}})
def test_wayland_and_egl_thunks_turn_on_only_when_the_build_ships_all_of_them(self):
guest = self.tmp / "guest-thunks"
guest.mkdir()
fex = {"host_thunks": "/h", "guest_thunks": str(guest), "thunks_db": "/db"}
thunks_file = self.home / ".local/share/droiddeck-fex/config/ThunksConfig.json"
for name in ("libwayland-client-guest.so", "libEGL-guest.so"):
(guest / name).write_bytes(b"")
FEX["write_config"](fex, "/root")
self.assertEqual({"GL": 1, "Vulkan": 1}, json.loads(thunks_file.read_text())["ThunksDB"])
(guest / "libwayland-egl-guest.so").write_bytes(b"")
FEX["write_config"](fex, "/root")
expected = {"GL": 1, "Vulkan": 1, "WaylandClient": 1, "EGL": 1, "WaylandEGL": 1}
self.assertEqual(expected, json.loads(thunks_file.read_text())["ThunksDB"])
config = json.loads((self.home / ".local/share/droiddeck-fex/config/Config.json").read_text())
self.assertEqual(expected, config["ThunksDB"])
def test_host_libc_tunables_stay_on_the_host(self):
guest = FEX["guest_environment"]({"portable": True}, {"GLIBC_TUNABLES": "glibc.pthread.rseq=0"})
self.assertNotIn("GLIBC_TUNABLES", guest)
@@ -1430,6 +1446,43 @@ class AppInfoTest(unittest.TestCase):
self.manifest(steam, app)
self.assertEqual(downloads(str(steam)), [])
def test_valve_proton_on_demand_waits_for_a_title_that_uses_it(self):
with tempfile.TemporaryDirectory() as tmp:
steam = Path(tmp)
for app in ("3127680", "1628350", "4183110"):
self.manifest(steam, app)
downloads, needed, tool = self.COMPAT["tool_downloads"], self.COMPAT["valve_proton_needed"], self.COMPAT["TOOL"]
own = steam / "compatibilitytools.d/DroidDeck-Proton 11-14.1"
with mock.patch.dict(os.environ, {"DD_VALVE_PROTON": "0"}):
self.assertEqual(downloads(str(steam)), [("4427310", "install")])
ge = steam / "compatibilitytools.d/GE-Proton10-25"
ge.mkdir(parents=True)
(ge / "droiddeck-proton-wrap").write_text("")
(ge / "compatibilitytool.vdf").write_text(
'"compatibilitytools" { "compat_tools" { "GE-Proton10-25" { "install_path" "." } } }')
self.assertEqual(downloads(str(steam)), [("4427310", "install")])
own.mkdir(parents=True)
(own / "droiddeck-proton-wrap").write_text("")
(own / "compatibilitytool.vdf").write_text(
'"compatibilitytools" { "compat_tools" { "DroidDeck-Proton-11-14.1" { "install_path" "." } } }')
self.assertEqual(downloads(str(steam)), [])
self.assertFalse(needed(str(steam), {"DroidDeck-Proton-11-14.1", None}))
self.assertTrue(needed(str(steam), {"DroidDeck-Proton-11-14.1", tool}))
self.assertTrue(needed(str(steam), {"proton-experimental-arm64"}))
self.assertEqual(downloads(str(steam), True), [("4427310", "install")])
config = steam / "config/config.vdf"
config.parent.mkdir()
config.write_text('"InstallConfigStore" { "Software" { "Valve" { "Steam" { "CompatToolMapping" { '
'"0" { "name" "DroidDeck-Proton-11-14.1" "config" "" "priority" "75" } '
'"10" { "name" "%s" "config" "" "priority" "250" } } } } } }' % tool)
self.assertEqual(downloads(str(steam)), [("4427310", "install")])
config.unlink()
self.manifest(steam, "4427310", flags="6")
self.assertEqual(downloads(str(steam), False), [("4427310", "update")])
with mock.patch.dict(os.environ, {"DD_VALVE_PROTON": "1"}):
(steam / "steamapps/appmanifest_4427310.acf").unlink()
self.assertEqual(downloads(str(steam)), [("4427310", "install")])
def test_titles_with_a_valve_pick_are_found_installed_or_not(self):
def deck(oslist, runtime, kind="game"):
common = {"type": kind, "oslist": oslist, "steam_deck_compatibility": {"configuration": {"recommended_runtime": runtime}}}
+39 -1
View File
@@ -11,6 +11,7 @@ SOURCE = SCRIPT.read_text()
START = SOURCE.index("fex_install() {")
END = SOURCE.index("\n}\n", START) + 3
FEX_INSTALL = SOURCE[START:END]
THUNK_DIRS = (("share/fex-emu/GuestThunks_32", "libGL-guest.so"), ("lib/fex-emu/HostThunks_32", "libGL-host.so"))
HARNESS = textwrap.dedent("""\
set -eu
@@ -37,9 +38,25 @@ class FexInstallTest(unittest.TestCase):
(new / "lib").mkdir()
(new / "lib/libxxhash.so.0").write_text("lib\n")
self.pkg = base / "fex.tzst"
subprocess.run(f"tar -C '{base / 'pkg'}' -c . | zstd -q -o '{self.pkg}'", shell=True, check=True)
self.pack()
def pack(self):
base = Path(self.temp.name)
subprocess.run(f"tar -C '{base / 'pkg'}' -c . | zstd -q -f -o '{self.pkg}'", shell=True, check=True)
self.sha = hashlib.sha256(self.pkg.read_bytes()).hexdigest()
def add_old_thunks(self):
old, new = self.root / "usr/local", Path(self.temp.name) / "pkg/usr/local"
for side, name in THUNK_DIRS:
(new / side).mkdir(parents=True)
(new / side / name).write_text("new thunk\n")
(old / side).mkdir(parents=True)
(old / side / name).write_text("old thunk\n")
(old / side / "libwayland-client-thunk.so").write_text("stale\n")
(old / "share/fex-emu/GuestThunks").mkdir()
(old / "share/fex-emu/GuestThunks/libkept-guest.so").write_text("kept\n")
self.pack()
def install(self, installed_loads, sha=None):
body = FEX_INSTALL.replace("local tag=$1 sha=$2 urls=$3 dst=/ ", "local tag=$1 sha=$2 urls=$3 dst=$ROOT/ ")
self.assertNotEqual(body, FEX_INSTALL)
@@ -79,6 +96,27 @@ class FexInstallTest(unittest.TestCase):
self.assertEqual("old FEX\n", (self.root / "usr/local/bin/FEX").read_text())
self.assertFalse((self.root / "usr/local/lib/libxxhash.so.0").exists())
def test_thunks_the_new_build_no_longer_ships_are_removed(self):
self.add_old_thunks()
self.assertEqual("OK", self.install(installed_loads=True)[0])
for side, name in THUNK_DIRS:
with self.subTest(side=side):
self.assertEqual("new thunk\n", (self.root / "usr/local" / side / name).read_text())
self.assertFalse((self.root / "usr/local" / side / "libwayland-client-thunk.so").exists())
def test_a_thunk_folder_the_new_build_does_not_ship_is_left_alone(self):
self.add_old_thunks()
self.assertEqual("OK", self.install(installed_loads=True)[0])
self.assertEqual("kept\n", (self.root / "usr/local/share/fex-emu/GuestThunks/libkept-guest.so").read_text())
def test_a_failed_install_puts_removed_thunks_back(self):
self.add_old_thunks()
self.assertEqual("FAILED", self.install(installed_loads=False)[0])
for side, name in THUNK_DIRS:
with self.subTest(side=side):
self.assertEqual("old thunk\n", (self.root / "usr/local" / side / name).read_text())
self.assertEqual("stale\n", (self.root / "usr/local" / side / "libwayland-client-thunk.so").read_text())
def test_an_archive_that_does_not_match_installs_nothing(self):
result, err = self.install(installed_loads=True, sha="0" * 64)
self.assertEqual("FAILED", result)
+151
View File
@@ -0,0 +1,151 @@
import re
import runpy
import unittest
from pathlib import Path
REPO = Path(__file__).resolve().parents[2]
PATCH = REPO / "tools/fex/patches/0019-wayland-and-egl-thunks-for-64-bit-guests.patch"
LAUNCHER = REPO / "tools/linuxfs/overlay/usr/local/bin/droiddeck-fex"
THUNKS = {"WaylandClient": "wayland-client", "EGL": "EGL", "WaylandEGL": "wayland-egl"}
def blocks():
return {re.match(r"a/(\S+) ", block).group(1): block
for block in re.split(r"^diff --git ", PATCH.read_text(), flags=re.M)[1:]}
def files():
return {name: [line[1:] for line in block.splitlines() if line.startswith("+") and not line.startswith("+++")]
for name, block in blocks().items()}
def built_libs(block):
out, base, stack = set(), False, []
for line in block.splitlines():
if line.startswith("@@"):
base, stack = "BITNESS EQUAL 64" in line, []
continue
if line[:1] == "-":
continue
text = line[1:].strip()
if text.startswith("if ("):
stack.append("gate" if "BITNESS EQUAL 64" in text else "other")
elif text.startswith("else"):
if stack:
stack[-1] = {"gate": "inverted", "inverted": "gate"}.get(stack[-1], stack[-1])
else:
base = False
elif text == "endif()":
if stack:
stack.pop()
else:
base = False
found = re.match(r"add_(?:guest|host)_lib\(([\w-]+)", text)
if found and line[:1] == "+":
out.add((found.group(1), "inverted" not in stack and (base or "gate" in stack)))
return out
def database():
entries, name = {}, None
for line in blocks()["Data/ThunksDB.json"].splitlines():
if line[:1] == "-":
continue
found = re.match(r'[ +]\s*"(\w+)": \{', line)
if found:
name = found.group(1)
found = re.search(r'"Library" : "([^"]+)"', line)
if found and name:
entries[name] = found.group(1)
return entries
class FexWaylandEglThunksTest(unittest.TestCase):
def test_only_thunk_sources_and_the_thunk_database_change(self):
for name in files():
with self.subTest(name=name):
self.assertTrue(name == "Data/ThunksDB.json" or name.startswith("ThunkLibs/"))
def test_each_enabled_thunk_maps_to_the_guest_library_the_build_ships(self):
launcher = runpy.run_path(str(LAUNCHER), run_name="droiddeck_fex")["WAYLAND_THUNKS"]
self.assertEqual(set(THUNKS), set(launcher))
built = {name for name, _ in built_libs(blocks()["ThunkLibs/GuestLibs/CMakeLists.txt"])}
entries = database()
for name, lib in THUNKS.items():
with self.subTest(name=name):
self.assertIn(lib, built)
self.assertEqual(f"lib{lib}-guest.so", launcher[name])
if name in entries:
self.assertEqual(launcher[name], entries[name])
self.assertEqual({"EGL", "WaylandEGL"}, set(entries) & set(THUNKS))
def test_the_upstream_wayland_client_entry_is_left_unchanged(self):
changed = [line for line in blocks()["Data/ThunksDB.json"].splitlines()
if line[:1] in "+-" and not line.startswith(("+++", "---"))]
self.assertFalse([line for line in changed if "WaylandClient" in line or "wayland-client" in line])
def test_an_extension_is_advertised_only_with_every_entrypoint(self):
guest = "\n".join(files()["ThunkLibs/libEGL/libEGL_Guest.cpp"])
table = dict(re.findall(r'\{"(EGL_\w+)", "([\w ]+)"\}', guest))
self.assertEqual("eglQueryNativeDisplayNV eglQueryNativeWindowNV eglQueryNativePixmapNV",
table["EGL_NV_native_query"])
self.assertIn("eglSignalSyncKHR", table["EGL_KHR_reusable_sync"].split())
self.assertIn("eglCreateSyncKHR", table["EGL_KHR_reusable_sync"].split())
body = re.search(r"static bool GuestHasEntrypoints\(.*?\n\}", guest, re.S).group(0)
self.assertRegex(body, r"while \(!rest\.empty\(\)\)")
self.assertRegex(body, r"dlsym\(Self\(\), .*rest\.substr\(0, end\)")
def test_a_legacy_display_follows_the_platform_mesa_would_pick(self):
host = "\n".join(files()["ThunkLibs/libEGL/libEGL_Host.cpp"])
env = re.search(r"static std::string_view EnvPlatform\(\) \{.*?\n\}", host, re.S).group(0)
self.assertLess(env.index('getenv("EGL_PLATFORM")'), env.index('getenv("EGL_DISPLAY")'))
legacy = re.search(r"case 0:\n(.*?)\n default:", host, re.S).group(1)
self.assertLess(legacy.index("EnvPlatform()"), legacy.index("IsWaylandDisplay(native)"))
self.assertIn('env == "xcb"', legacy)
self.assertIn('env != "x11"', legacy)
self.assertNotIn("IsHostDevice", host)
def test_gles_is_overlaid_only_by_the_64_bit_egl_thunk(self):
overlays, name = {}, None
for line in blocks()["Data/ThunksDB.json"].splitlines():
found = re.match(r'[ +]\s*"(\w+)": \{', line)
if found:
name = found.group(1)
if "libGLESv2" in line:
overlays.setdefault(line[:1], set()).add(name)
self.assertEqual({"EGL"}, overlays.get("+"))
self.assertNotIn("-", overlays)
def test_guest_and_host_libraries_are_built_for_64_bit_guests_only(self):
changed = blocks()
for side in ("GuestLibs", "HostLibs"):
built = built_libs(changed[f"ThunkLibs/{side}/CMakeLists.txt"])
for lib in THUNKS.values():
with self.subTest(side=side, lib=lib):
self.assertEqual({(lib, True)}, {entry for entry in built if entry[0] == lib})
def test_listener_trampolines_stay_inside_the_packed_argument_limit(self):
guest = "\n".join(files()["ThunkLibs/libwayland-client/Guest.cpp"])
limit = int(re.search(r"#define WAYLAND_UNIFORM_MAX_ARGS (\d+)", guest).group(1))
self.assertLessEqual(limit + 2, 19)
def test_the_guest_provides_the_inline_list_and_array_helpers(self):
guest = "\n".join(files()["ThunkLibs/libwayland-client/Guest.cpp"])
for name in ("wl_list_init", "wl_list_insert", "wl_list_remove", "wl_list_length", "wl_list_empty",
"wl_list_insert_list", "wl_array_init", "wl_array_release", "wl_array_add", "wl_array_copy"):
with self.subTest(name=name):
self.assertRegex(guest, rf"\b{name}\(")
def test_the_inverse_branch_of_the_bitness_gate_is_not_64_bit_only(self):
block = "@@ -1 +1 @@\n+if (GUEST_BITNESS EQUAL 64)\n+else()\n+ add_host_lib(EGL ${GUEST_BITNESS})\n+endif()\n"
self.assertEqual({("EGL", False)}, built_libs(block))
def test_no_comments_are_added(self):
for name, lines in files().items():
for line in lines:
with self.subTest(name=name, line=line):
self.assertNotRegex(line, r"(^|\s)(//|/\*)|\$info\$")
if __name__ == "__main__":
unittest.main()
+238 -5
View File
@@ -1,5 +1,7 @@
import os
from pathlib import Path
import re
import shutil
import subprocess
import tempfile
import unittest
@@ -65,6 +67,11 @@ 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);
@@ -149,6 +156,18 @@ 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"
@@ -159,20 +178,44 @@ class NativeHookMountTest(unittest.TestCase):
def tearDownClass(cls):
cls.tmp.cleanup()
def run_probe(self, *args, binds=None):
def run_probe(self, *args, binds=None, mounts=None, syscalls=False):
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) + [arg for key, value in hook_env.items() for arg in ("-E", f"{key}={value}")]
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}")]
else:
cmd = []
env.update(hook_env)
if syscalls and not shutil.which("strace"):
self.skipTest("no strace")
if syscalls:
cmd = ["strace", "-f", "-qq", "-e", "trace=readlinkat,newfstatat,fstatat64,statx"]
cmd += [arg for key, value in hook_env.items() for arg in ("-E", f"{key}={value}")]
else:
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)
return {line.split("\t")[0]: line.split("\t")[1:] for line in out.stdout.splitlines()}
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)
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")
@@ -310,6 +353,196 @@ 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)
def test_relative_parent_walks_inside_mounts_without_links_stay_relative(self):
real, _, _ = self.links_volume()
binds = f"{self.links}:/mnt/links"
paths = {"sub/deeper/../file.txt": ["1", "deep"], "sub/deeper/more/../more/leaf.txt": ["1", "leaf"],
"../real/sub/file.txt": ["1", "deep"], "../../../etc/hostname": ["1", "rootfs"],
"sub/../../../../etc/hostname": ["1", "rootfs"]}
for kind, relative in (("exfat", True), ("ext4", False)):
table = [("/", "ext4", "/dev/root"), (real, kind, "/dev/sdb1")]
result, log = self.run_probe("cd:/mnt/links/real", *paths, binds=binds, mounts=table, syscalls=True)
for path, want in paths.items():
self.assertEqual(result[path], want, (path, kind))
stats = [m.group(1) for m in re.finditer(r'(?:fstatat|statx)\([^,"]*,\s*"([^"]*)"', log)]
for path in ("sub/deeper/../file.txt", "sub/deeper/more/../more/leaf.txt", "../real/sub/file.txt"):
self.assertEqual(path in stats, relative, (path, kind, stats))
for path in ("../../../etc/hostname", "sub/../../../../etc/hostname"):
self.assertNotIn(path, stats, (path, kind))
nested = f"{binds}|{self.library}:/mnt/links/real/sub"
table = [("/", "ext4", "/dev/root"), (real, "exfat", "/dev/sdb1")]
result, log = self.run_probe("cd:/mnt/links/real", "sub/deeper/../game.txt", binds=nested, mounts=table,
syscalls=True)
stats = [m.group(1) for m in re.finditer(r'(?:fstatat|statx)\([^,"]*,\s*"([^"]*)"', log)]
self.assertNotIn("sub/deeper/../game.txt", stats)
walk = "sub/Some Game/../Some Game/game.txt"
for order in ((f"{self.links}:/mnt/links", f"{self.links}:/mnt/longer/alias"),
(f"{self.links}:/mnt/longer/alias", f"{self.links}:/mnt/links")):
shared = "|".join(order) + f"|{self.library}:/mnt/links/real/sub"
results = [self.run_probe("cd:/mnt/links/real", walk, binds=shared,
mounts=[("/", "ext4", "/dev/root"), (real, kind, "/dev/sdb1")])[walk]
for kind in ("ext4", "exfat")]
self.assertEqual(results[0], results[1], order)
def test_relative_parent_walks_honour_identity_binds_shared_guest_paths_and_the_rootfs(self):
real, _, _ = self.links_volume()
tmp = os.path.realpath(self.tmp.name)
card = f"{tmp}/identity-card"
os.makedirs(f"{card}/real/sub/deeper", exist_ok=True)
Path(f"{card}/real/sub/file.txt").write_text("identity")
binds = f"{self.links}:{card}|{card}/real/sub:{card}/real/sub"
walk = "sub/deeper/../file.txt"
results = [self.run_probe(f"cd:{card}/real", walk, binds=binds,
mounts=[("/", "ext4", "/dev/root"), (real, kind, "/dev/sdb1")])[walk]
for kind in ("ext4", "exfat")]
self.assertEqual(results[0], results[1])
twins = (f"{tmp}/twin-a", f"{tmp}/twin-b")
for twin in twins:
os.makedirs(f"{twin}/only/sub/deeper", exist_ok=True)
Path(f"{twin}/only/sub/file.txt").write_text(os.path.basename(twin))
for order in (twins, twins[::-1]):
shared = "|".join(f"{src}:/mnt/twin" for src in order)
result, log = self.run_probe("cd:/mnt/twin/only", walk, binds=shared, syscalls=True,
mounts=[("/", "ext4", "/dev/root")] +
[(twin, "exfat", f"/dev/sd{i}1") for i, twin in zip("bc", twins)])
stats = [m.group(1) for m in re.finditer(r'(?:fstatat|statx)\([^,"]*,\s*"([^"]*)"', log)]
self.assertEqual(result[walk], ["1", os.path.basename(order[0])], order)
self.assertNotIn(walk, stats, order)
climb = "../../etc/hostname"
for kind in ("ext4", "exfat"):
result = self.run_probe("cd:/etc", climb, binds=f"{tmp}:/mnt/card",
mounts=[("/", "ext4", "/dev/root"), (tmp, kind, "/dev/sdb1")])
self.assertEqual(result[climb], ["1", "rootfs"], kind)
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,131 @@
import os
from pathlib import Path
import subprocess
import tempfile
import unittest
from tools.tests.test_usr2_preload import runner
HOOK_BUILD = Path(__file__).resolve().parents[1] / "nativeguest/build.sh"
OWNERS = r"""
#define _GNU_SOURCE
#include <dlfcn.h>
#include <fcntl.h>
#include <string.h>
#include <sys/stat.h>
static void owner(const char *path, unsigned *uid, unsigned *gid) {
if (!path) return;
if (strstr(path, "shared")) { *uid = 4242; *gid = 1023; }
else if (strstr(path, "other")) { *uid = 4242; *gid = 4242; }
}
int stat(const char *path, struct stat *st) {
int (*next)(const char *, struct stat *) = dlsym(RTLD_NEXT, "stat");
int ret = next(path, st);
if (ret == 0) owner(path, &st->st_uid, &st->st_gid);
return ret;
}
int lstat(const char *path, struct stat *st) {
int (*next)(const char *, struct stat *) = dlsym(RTLD_NEXT, "lstat");
int ret = next(path, st);
if (ret == 0) owner(path, &st->st_uid, &st->st_gid);
return ret;
}
int fstatat(int dirfd, const char *path, struct stat *st, int flags) {
int (*next)(int, const char *, struct stat *, int) = dlsym(RTLD_NEXT, "fstatat");
int ret = next(dirfd, path, st, flags);
if (ret == 0) owner(path, &st->st_uid, &st->st_gid);
return ret;
}
int statx(int dirfd, const char *path, int flags, unsigned mask, struct statx *sx) {
int (*next)(int, const char *, int, unsigned, struct statx *) = dlsym(RTLD_NEXT, "statx");
int ret = next(dirfd, path, flags, mask, sx);
if (ret == 0) owner(path, &sx->stx_uid, &sx->stx_gid);
return ret;
}
"""
PROBE = r"""
#define _GNU_SOURCE
#include <fcntl.h>
#include <stdio.h>
#include <sys/stat.h>
int main(int argc, char **argv) {
struct stat st;
struct statx sx;
for (int i = 1; i < argc; i++) {
if (stat(argv[i], &st) != 0) return 2;
printf("%s\tstat\t%u\t%u\n", argv[i], st.st_uid, st.st_gid);
if (lstat(argv[i], &st) != 0) return 3;
printf("%s\tlstat\t%u\t%u\n", argv[i], st.st_uid, st.st_gid);
if (fstatat(AT_FDCWD, argv[i], &st, 0) != 0) return 4;
printf("%s\tfstatat\t%u\t%u\n", argv[i], st.st_uid, st.st_gid);
if (statx(AT_FDCWD, argv[i], 0, STATX_BASIC_STATS, &sx) != 0) return 5;
printf("%s\tstatx\t%u\t%u\n", argv[i], sx.stx_uid, sx.stx_gid);
}
return 0;
}
"""
class NativeHookStorageOwnerTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.cc, cls.prefix = runner()
if cls.cc is None:
raise unittest.SkipTest("no aarch64 compiler and runner")
cls.tmp = tempfile.TemporaryDirectory(dir="/tmp")
tmp = Path(cls.tmp.name)
cls.hook = tmp / "hook.so"
subprocess.run(["bash", str(HOOK_BUILD), str(cls.hook), cls.cc], check=True, capture_output=True)
(tmp / "owners.c").write_text(OWNERS)
cls.owners = tmp / "owners.so"
subprocess.run([cls.cc, "-shared", "-fPIC", "-O1", "-o", str(cls.owners), str(tmp / "owners.c"), "-ldl"], check=True)
(tmp / "probe.c").write_text(PROBE)
cls.probe = tmp / "probe"
subprocess.run([cls.cc, "-O1", "-o", str(cls.probe), str(tmp / "probe.c")], check=True)
cls.root = tmp / "root"
cls.root.mkdir()
for name in ("shared", "other", "own"):
(cls.root / name).write_text("")
@classmethod
def tearDownClass(cls):
cls.tmp.cleanup()
def owners_of(self, *paths):
hook_env = {"DDNATV_ROOT": str(self.root), "LD_PRELOAD": f"{self.hook} {self.owners}"}
env = {k: v for k, v in os.environ.items() if k not in ("LD_PRELOAD", "DDNATV_ROOT")}
if self.prefix:
cmd = list(self.prefix) + [arg for key, value in hook_env.items() for arg in ("-E", f"{key}={value}")]
else:
cmd = []
env.update(hook_env)
out = subprocess.run(cmd + [str(self.probe), *paths], env=env, capture_output=True, text=True, timeout=120)
self.assertEqual(0, out.returncode, out.stdout + out.stderr)
result = {}
for line in out.stdout.splitlines():
path, call, uid, gid = line.split("\t")
result.setdefault(path, {})[call] = (int(uid), int(gid))
return result
def test_shared_storage_files_are_owned_by_root_and_keep_their_group(self):
for call, ids in self.owners_of("/shared")["/shared"].items():
self.assertEqual((0, 1023), ids, call)
def test_other_owners_and_the_apps_own_files_are_unchanged(self):
result = self.owners_of("/other", "/own")
for call, ids in result["/other"].items():
self.assertEqual((4242, 4242), ids, call)
for call, ids in result["/own"].items():
self.assertEqual((0, 0), ids, call)
if __name__ == "__main__":
unittest.main()
+22
View File
@@ -150,6 +150,28 @@ class CompatLibrariesTest(unittest.TestCase):
class DesktopGamesTest(unittest.TestCase):
def test_library_links_that_cannot_be_walked_are_made_again(self):
with tempfile.TemporaryDirectory() as temp:
root = Path(temp)
steam, home = root / "Steam", root / "home"
(steam / "steamapps/common/Game").mkdir(parents=True)
home.mkdir()
common = str(steam / "steamapps/common")
stale, kept = home / "Steam Games", home / "SD Games"
os.symlink(str(root / "elsewhere"), stale)
card = root / "card/steamapps/common"
card.mkdir(parents=True)
os.symlink(str(card), kept)
before = os.lstat(kept).st_ino
real = os.readlink
with patch.object(desktop, "HOME", str(home)), \
patch.object(desktop, "LIBRARIES", ((str(steam), "Steam Games"), (str(root / "card"), "SD Games"))), \
patch.object(desktop.os, "readlink", lambda p: common if p == str(stale) else real(p)):
desktop.link_libraries()
self.assertEqual(common, os.readlink(stale))
self.assertTrue((stale / "Game").is_dir())
self.assertEqual(before, os.lstat(kept).st_ino)
def test_games_in_registered_libraries_get_entries(self):
with tempfile.TemporaryDirectory() as temp:
root = Path(temp)
@@ -1,18 +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", "host", "kernel", "uptime", "packages", "shell",
"display", "de", "wm", "wmtheme", "theme", "icons", "font", "cursor",
"terminal", "cpu", "gpu", "memory", "swap", "disk", "battery", "locale",
"break", "colors"
]
}
+154 -33
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,1406 @@
@@ -0,0 +1,1527 @@
+//! 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; the download is kept for a retry");
+ return fail("extract-failed", "Could not unpack the package; retrying may require downloading the bundle again because containers are removed to save disk space");
+ }
+ // 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,15 +813,24 @@ 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();
+ 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());
+ 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(),
+ }
+ }
+ names
@@ -994,8 +1003,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().to_ascii_lowercase();
+ if text.contains("processorarchitecture=\"x64\"") {
+ let text = std::fs::read_to_string(&manifest).unwrap_or_default();
+ if identity_is_x64(&text) {
+ return Some(folder);
+ }
+ }
@@ -1011,6 +1020,24 @@ 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> {
@@ -1057,8 +1084,18 @@ 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();
+ 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}"))?;
+ 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}"));
+ }
+ Ok(())
+}
+
@@ -1079,7 +1116,16 @@ index 0000000..d43c5fc
+ if target.exists() {
+ continue;
+ }
+ std::fs::copy(&path, &target).map_err(|error| format!("framework copy failed: {error}"))?;
+ 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}"));
+ }
+ copied.push(file_name.to_string_lossy().into_owned());
+ }
+ Ok(())
@@ -1119,10 +1165,19 @@ index 0000000..d43c5fc
+ ));
+ }
+ let inner = candidates.remove(0);
+ for entry in std::fs::read_dir(&inner)
+ let entries: Vec<_> = 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);
@@ -1142,16 +1197,41 @@ index 0000000..d43c5fc
+ if !existing.is_empty() && !updating && !metadata {
+ return Err(format!("Extraction would overwrite {}", target.display()));
+ }
+ 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}"))?;
+ 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}"))?;
+ }
+ 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(())
@@ -1165,7 +1245,9 @@ index 0000000..d43c5fc
+ if applications.len() > 1 {
+ let x64: Vec<PathBuf> = applications
+ .iter()
+ .filter(|folder| manifest_text(folder).contains("processorarchitecture=\"x64\""))
+ .filter(|folder| {
+ identity_is_x64(&manifest_text_original(folder))
+ })
+ .cloned()
+ .collect();
+ if x64.len() == 1 {
@@ -1176,22 +1258,41 @@ 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("
+")
+ .to_ascii_lowercase()
+ .join("\n")
+}
+
+fn declares_application(folder: &Path) -> bool {
+ let text = manifest_text(folder);
+ opens_element(&text, "<application") || opens_element(&text, "<executable")
+ 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
+}
+
+/// Whether [text] opens [tag] as its own element, so `<Application Id=` and an attribute on the next
+/// line count and `<Applications>` does not.
+/// line count and `<Applications>` does not. Used by the focused parser test only.
+#[cfg(test)]
+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 == '/')
@@ -1441,6 +1542,23 @@ 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"] {
@@ -1465,6 +1583,9 @@ 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();
+ }
+