mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-20 05:16:01 +00:00
ESync, FSync, NTSync + OpenNow + FEX for Desktop Apps (#197)
* Make the Compatible Proton ARM64 the default and label compatible builds
The CompatToolMapping "0" default always points at DroidDeck's Proton
ARM64 tool, and per-game picks of adopted GE/CachyOS builds are kept,
including when the shortcuts writer remaps.
The tool is named after the Proton build it runs, Proton Experimental
ARM64 (Compatible), or Proton 11.0 ARM64 (Compatible) once that newer build
is installed. Adopted builds carry the same Compatible mark, read from a
string resource the app stages into the runtime, and the Proton page
explains which builds have the prefix fixes.
The registrar is renamed steam-compatibility and the tool
droiddeck-proton-arm64. Existing installs migrate on the next session: the
old tool directory is removed, every mapping that named it moves to the new
tool, and the retired bannerlator-steam-compat script is removed from the
runtime. CI and local packaging include the renamed script.
* Drop the duplicate R import left by merging main
* Add userspace ntsync for Proton on Android
Android kernels have no /dev/ntsync and its app policy refuses futex_waitv,
so every Proton 11 build here fell back to wineserver for every wait.
libblsession now serves /dev/ntsync itself: wineserver opens a memfd region,
each sync object is a timerfd that carries its slot, and the kernel ntsync
ioctls are answered in shared memory with futexes, following the kernel
driver's wake order. Valve's Proton Experimental ARM64, GE-Proton and
proton-cachyos use it unchanged.
Locks record their owner so a killed process cannot wedge the others,
signals are held off inside each critical section, dead processes and
exiting threads are swept, and object lifetimes follow close, dup2, dup3,
close_range and received descriptors.
Fast sync is on by default under Performance > Session fixes, and
PROTON_NO_NTSYNC=1 turns it off per game.
* Add droiddeck-esync as the default sync for Proton on Android
Without a kernel ntsync driver, Proton 11 builds here fell back to
wineserver for every wait. droiddeck-esync brings eventfd and shared-memory
sync to the exact Proton build a game runs on: a pack holds that build's
ntdll.so and wineserver with the patch series in tools/droiddeck-esync
applied, and the guest runs Proton from a shadow tree that links the stock
tool and swaps in those two files. A wineserver from a pack still prefers
/dev/ntsync when a kernel driver or droiddeck-ntsync is there.
Packs are built in Valve's SDK image from each release's own wine source
(Proton Experimental ARM64 tags, GE-Proton and proton-cachyos releases); the
control build must reproduce the release binaries byte for byte, and a
signed index lists the packs. The APK bundles the packs pinned in
release.env, the app fetches newer ones, and Steam's compatibility tool
picks the pack for each Proton build, so new Proton releases get packs
without an app update.
The ntdll side reads, writes and polls its eventfds with raw system calls,
so the guest's LD_PRELOAD wrappers stay out of the sync path. The server
abandons a mutex once a thread killed by TerminateThread has really exited
and when its process dies, and a mutex's owner and recursion count change
in one atomic step, so a killed owner cannot touch the next owner's count.
droiddeck-esync is on by default and PROTON_NO_ESYNC=1 turns it off per
game; droiddeck-ntsync, the userspace ntsync, is now an opt-in toggle.
* Watch Valve's Proton releases and build droiddeck-esync packs for them
A scheduled workflow reads the Proton ARM64 builds Steam ships (anonymous
steamcmd app info) and the upstream source tags, compares them with the
previous watch state and starts the pack build for any build that has no
pack yet. The pack build applies the patch series with --fuzz=0 and runs a
smoke test of each new pack against the esstress suite before it is
published.
* Add droiddeck-fsync, keep Steam and the app on one Proton, fix DirectAudio
droiddeck-fsync: libblsession answers futex_waitv(2), which the app
sandbox refuses, in userspace, so Proton's own fsync runs on the stock
Proton files with no pack. Waiters register the words they wait on in a
table beside the fsync shared memory and sleep on a futex of their own;
FUTEX_WAKE on the fsync memory wakes the registered waiters. Slots carry
one owner word that the sweeper and the owner claim with a CAS, and the
mapping table is rebuilt under a lock held across the real munmap, so a
reused address or a recycled slot cannot lose a waiter. It stands in for
a Proton build without a pack (droiddeck-ntsync where fsync is off), takes
over for games with esync off, and the "droiddeck-fsync first" toggle
(BL_FSYNC_FIRST, also per game) puts it ahead of the packs. The games
Proton keeps off fsync and esync never get it. A launch into a prefix
whose wineserver is still running keeps that server's sync choice.
One Proton for Steam and the app: the Components page's Proton is the
default Steam uses, applied live through the client while Steam runs
(droiddeck-steam-compat) and at the next start otherwise; a choice made in
Steam's menu comes back to the app. Requests are ordered by a sequence that
never goes backwards, and the page no longer jumps back to the default
after a swap or restore.
DirectAudio: the wrapper wrote the driver key with its backslashes
stripped, so no game ever used DirectAudio. Wine 11 also loads a builtin
only from the prefix, so the driver is now linked into system32 and
syswow64 before "directaudio,pulse" is selected; mmdevapi falls back to
winepulse whenever DirectAudio cannot start.
* Pick esync, ntsync or fsync from the Steam settings' Games group
A three-way tab row above the FEX preset sets the sync Proton games use. It
writes the existing switches together (droiddeck-ntsync, droiddeck-fsync
first, droiddeck-esync), so the Performance toggles and the tabs always agree,
starts on esync and keeps the choice until it is changed again.
* Make droiddeck-fsync the default sync for Proton games
A fresh install, or one that never picked a sync, starts on fsync; a choice made
in the Steam settings' Games group still sticks. Games Proton keeps off fsync
still fall back to droiddeck-esync.
* Add wineserver to the Wine sync tabs and order them ntsync, fsync, esync, wineserver
wineserver turns every in-process sync off so games wait through wineserver;
picking any other tab turns sync back on. The tabs shrink to fit a narrow pane.
* Shorten the Wine sync description
* Answer openat2 and execveat for FEX in the session preload
FEX opens every file of its x86 rootfs with openat2(RESOLVE_IN_ROOT) and
only falls back to the host path on EXDEV. Under proot on Android openat2
answers ENOSYS, so each lookup of an x86 library silently went to the host
and missed. The exported syscall() now turns openat2 into openat once the
real call reports ENOSYS: RESOLVE_IN_ROOT paths are taken relative to the
root fd (FEX has already resolved the links inside the rootfs), and an
absolute path under RESOLVE_BENEATH fails with EXDEV as the kernel would.
execveat with an absolute path, or relative to AT_FDCWD, and without
AT_EMPTY_PATH or AT_SYMLINK_NOFOLLOW, is plain execve; it is sent as such
because proot refuses execveat with a directory fd, which FEX uses when it
re-executes itself for a child x86 program.
* Run x86 Linux games and programs through FEX
Steam: Linux-only titles that have no ARM64 build (from the client's
appinfo cache: type game, demo, application or beta) are mapped to a new
compatibility tool, droiddeck-fex ("Linux x86 (FEX)", linux to linux,
no required runtime). Valve's own "fex" tool needs pressure-vessel, which
cannot run under proot, so a mapping to it or to a Steam Linux Runtime is
replaced; any other pick the user made stays. Titles that also ship for
Windows stay on Proton. When such a title is installed and FEX or the
sniper runtime is missing, the client is asked to install them.
droiddeck-fex runs the program under the FEX that Steam installs (app
3127680), with Steam Linux Runtime 3.0 (sniper, app 1628350) as the x86
rootfs:
- the sniper platform is linked in place from its usr-mtree (relative
links only, files/usr -> .), once per runtime version;
- the x86_64 and i386 builds of libblsession and libfakeinput go into the
runtime's lib/<triplet>/droiddeck and its etc/ld.so.preload, mirroring
the session's own list, so x86 programs get the pads and the session
fixes (FEX passes their system calls straight to the kernel, so the
ARM64 preloads cannot reach them);
- Config.json sets RootFS and the GL and Vulkan thunks, so x86 games draw
with the device's Turnip and Mesa;
- the FEX preset and the game's own environment from the Steam settings
apply, and ARM64 entries are dropped from LD_PRELOAD/LD_LIBRARY_PATH.
It also links ~/.steam/sdk64 and sdk32 to the client's x86 steamclient
when the client has one and nothing is there yet.
Desktop: x86_64 and i386 AppImages can be imported now; they unpack
through FEX (or unsquashfs) and record their architecture. Scripts,
AppImages and programs started in a run session use FEX automatically
when they are x86, and each added app has a "Use FEX" Auto/On/Off choice
in its edit dialog. The launchers' "still running" checks also look at
FEX processes, whose exe is FEX rather than the program. A GitHub release
without an ARM64 AppImage falls back to its x86_64 one. Decky's x86
loader starts through droiddeck-fex instead of the fex-mesa rootfs path,
which no runtime ships.
The x86 preloads are built against glibc 2.31 (Debian 11) so they load
in sniper: tools/linuxfs/build-x86-preloads.sh, run in CI and by
build_local.sh. fakeinput's stat hooks fall back to __xstat on a glibc
without a stat export, and mmap64 takes off64_t for the i386 build.
* Keep a FEX unixlib from outliving its DLL
A FEX package or original bundle without the aarch64-unix helpers left
the previous version's libarm64ecfex.so / libwow64fex.so in the Proton,
so the new DLLs loaded a unixlib built for another FEX. A swap now removes
the helpers the package does not carry; FEX then runs DLL-only, which it
already falls back to when Wine cannot load the unixlib.
* Fix the Wine sync choices an audit found
- wineserver tab: it passed Proton's environment through, so a build with
esync built in (GE, cachyos) still ran esync and a kernel ntsync would
still be used. It now sets PROTON_NO_ESYNC, PROTON_NO_FSYNC and
PROTON_NO_NTSYNC (unless the game's own environment sets them).
- ntsync tab: a Proton whose wineserver has no /dev/ntsync client got
wineserver-only sync although fsync would work. The hash cache records
whether the wineserver has one; without it the launch goes to
droiddeck-fsync, and no stand-in or pack turns droiddeck-ntsync on.
- A build with esync built in returned before the per-game fallbacks, so
a game that turns esync off ran with no in-process sync. It now gets
droiddeck-fsync, or droiddeck-ntsync where fsync is off too.
- When a pack's proton cannot start and the stock one is used, or the
selection fails, the prefix's record now says stock, so a second
launch into the same running prefix no longer picks the pack's ntdll.
- droiddeck-fsync: its mutex is held across fork and re-made in the
child, a closed or replaced shm fd is forgotten (close, dup2, dup3,
close_range, closefrom), and a waiter woken while it was leaving on a
timeout or signal reports the wake instead of losing it.
- BL_SYNC_MIN_NOFILE applies per game to every verb, debug logs carry
prefixes.json, the device report names the chosen sync instead of the
three raw switches, and PATCHES.md and the proot notes describe the
selector, the fsync default and droiddeck-fsync's futex_waitv.
* Name the runtime's scripts and files droiddeck, migrating old installs
The guest scripts are droiddeck-* now (droiddeck-session and the other 19),
as are the files the app and scripts generate (etc/droiddeck, the network
state files, the components dir, the Steam install stamp, the redist marker,
the extra-Proton wrapper and backups) and the compositor's own names
(libdroiddeckwayland, droiddeck_* sources, DROIDDECK_* switches, the
wl_output and seat names).
Installed runtimes carry on: LegacyNames moves etc/bannerlator and
share/bannerlator over and leaves relative links at the old paths before
every proot command, turns any old script into a link to its new name,
moves the generated files and points menu entries at the new scripts.
The session scripts and steam-compatibility move their markers on first
use, the components dir's desired.tsv is rewritten with it, and the
runtime counts as installed under either session script.
Kept: the banner_ahb_v1/banner_desktop_v1 wire names and BANNER_AUDIO_DIRECT
(read by prebuilt Turnip and Wine builds), Banners-Turnip and other
third-party names, BL_* switches, libblsession, and credits to Bannerlator.
* Unpack x86 AppImages without FEX, then ask Steam for FEX
Importing an x86 AppImage failed when FEX was not installed yet ("needs FEX
to unpack and no unsquashfs is installed"). AppImages now unpack with
uruntime (VHSgunzo, MIT, v0.8.1 aarch64, pinned by sha256 and shipped
unmodified with its licence), which reads SquashFS and DwarFS images of any
architecture natively. FEX's own --appimage-extract and unsquashfs stay as
fallbacks, and an ARM64 image whose own runtime cannot unpack it goes the
same way.
An x86 import with FEX missing records that FEX is wanted, so the next
Steam session requests FEX and the Steam Linux Runtime, and the program's
page says FEX is not set up yet and how to get it.
* Run Vulkan Qt Quick AppImages on Wayland
OpenNOW (Qt 6.8, Qt Quick on Vulkan) closed within two seconds in a run
mode. The session sends toolkits to gamescope's Xwayland, and Qt's xcb
backend only presents with Vulkan when Mesa's X11 WSI does, which needs
DRI3; Xwayland on KGSL has none, so Qt found no queue that can present and
aborted ("Failed to create RHI").
An AppImage that bundles Qt Quick, the Vulkan loader and Qt's Wayland
plugin now runs on gamescope's Wayland socket (the desktop's, outside
gamescope), where Turnip presents as it does for games, with Qt's xcb
backend as the fallback. SDL_VIDEODRIVER and XDG_SESSION_TYPE follow, so
helpers that pick their window system from them (OpenNOW's streamer) agree
with Qt. Everything else stays on X11; a qt file in the app's directory
(wayland or xcb) overrides the choice.
* Keep gamescope's WSI layer away from Qt apps on its Wayland socket
OpenNOW still closed at once: its FFmpeg (the Raspberry Pi fork, libavutil
61) creates its Vulkan queues internally synchronized whenever the driver
offers VK_KHR_internally_synchronized_queues, which DD-Turnip does. The
gamescope WSI layer registers every queue of a new device through
vkGetDeviceQueue, which only returns queues created without flags, so it
got VK_NULL_HANDLE and vkroots aborted on assert(obj) before Qt opened a
window.
Programs that draw on gamescope's Wayland socket do not need the layer,
which only carries X11 windows past Xwayland, so it is turned off for
them. OpenNOW bundles no Vulkan loader (it reaches Vulkan through Qt and
dlopen), so a binary that uses QVulkanInstance counts as a Vulkan app too,
and a Qt Quick app left on X11 says why in the session log.
* Keep the end of the session log, and say when FEX is missing
The session sends its output through head -c into session.log. head
writes through stdio, so it held up to 4 KB that proot's --kill-on-exit
threw away when the guest ended: every log stopped mid-line at a 4096-byte
boundary, losing exactly the lines that say why a program quit (an x86
AppImage's "x86 Linux programs need FEX" among them). dd writes each read
as it comes and keeps the same cap.
A run mode always ends with status 0 (gamescope does not pass its child's
on), so a program that could not start just closed. When the log says FEX
is missing, the ended screen now says so and how to get it.
The app reads FEX's readiness from status.json, which only a launch or an
import wrote, so it still said "not set up" after Steam installed FEX.
droiddeck-fex status rewrites it, and a Steam session ends with it while
FEX is wanted. FEX is also looked for at the tool's root and under files/,
and a tool folder without it lists what it holds.
* Let FEX and its runtime install runnable on an SD card library
A Steam library on shared storage loses the executable bits, so native
tools are staged in private directories bound over it; only Proton and
SteamLinuxRuntime folders were. FEX (3127680) installed there could never
run, droiddeck-fex saw no FEX and kept asking Steam for it. FEX and the
sniper runtime (1628350) now get private directories from their first
download, whatever their install folder is called.
* Keep fsync off in the pack smoke test
A runner whose kernel allows futex_waitv started stock Proton with fsync,
so the server-side baseline never said what the test waits for and every
pack was waved through as untestable; the esync run would have measured
fsync too.
* Judge a pack against stock's own esstress failures
Stock Proton fails esstress's dup wait all under server-side sync as well
(a Wine bug, seen on the phone too), and any stock failure made the test
call the runner unusable. A pack now fails only when it crashes, hangs or
fails a check stock passes.
* Ask Steam for FEX and its runtime one at a time
Both steam://install requests were started together, and the running client
took only the first: FEX installed, the sniper runtime FEX needs never did.
Each request now waits for the client to take it before the next.
* Bundle the first published droiddeck-esync packs in the apk
* Log how an x86 program under FEX ends
FEX keeps its own errors quiet unless asked, so a program it could not run
left nothing in the session log. Its log now goes to stderr, and the AppImage
launcher records the program's exit status or the signal that ended it.
* Show the log a failed AppImage program wrote
Programs like Eden stop themselves on a failed check and say why only in
their own log under the home folder. When the program ends badly, the end of
any log it wrote during the run is copied into the session log.
* Report where an x86 program under FEX hit an illegal instruction
A tiny x86_64 preload, built without libc, catches SIGILL and writes the
address, the instruction bytes and the mapping they belong to before the
program dies as it would have. droiddeck-fex preloads it into x86_64 programs.
* Load the fault reporter from the x86 runtime
Programs under FEX look libraries up in the x86 runtime, so the reporter is
copied there with the other preloads and named by its path inside it.
* Hand FEX its x86 runtime and thunks through the environment
Valve's FEX runs portable and reads its config beside itself, so the
Config.json droiddeck-fex writes was not seen: programs ran without the
runtime. The runtime, thunk libraries and thunk list now also go in FEX's
own environment variables, and each launch says what it was given.
* Use the sync pack built for the installed Proton release
Some Proton releases ship byte-identical ntdll.so and wineserver (Valve
11.0-2b/2c, CachyOS 0702/0703), so a pack built for a newer release
matched an older install exactly and the older install never fetched its
own pack. A pack from a newer release no longer counts as an exact match;
among matches the one built for the installed version wins, then rev.
The app ranks the pack a tool already uses the same way and only fetches
a pack that ranks higher, reads the release epoch from tools.tsv and
refetches when tools.tsv changes. A prefix whose server is still running
re-checks its recorded pack on waitforexitandrun and starts fresh when a
better one now applies.
* Keep published sync packs and revocations consistent
The publish step never replaces a pack that has an entry beside it; a
pack left without its entry by an interrupted run is replaced so the
build stops repeating. Discovery counts revocations the signed index does
not show yet, including superseded packs only the flavor releases list,
so the index is signed again. The release watch always builds every
flavor.
* Fetch the droiddeck-esync packs from DroidDeck-Components
The packs, the signed index and the apk bundle now live in the releases
of Droid-Deck/DroidDeck-Components, together with the pipeline that
builds them, so this repository keeps only the app and the guest code
that consumes them. The app's index and asset URLs point there,
release.env names the repository its bundle comes from, and the apk
builds drop bundled packs that the published index revokes.
* Stop the apk build when the published sync index cannot be read
* Ask Steam for one FEX dependency at a time
The client shows a confirmation dialog for each steam://install, and a
second request replaces the first dialog, so FEX was never installed
when the runtime was requested right after it. The next dependency is
now requested once the previous one has an app manifest.
* Use generic names in the AppImage test fixtures
* Give x86-64 apps under FEX the Vulkan thunk
Apps that bring their own glibc and Vulkan loader skipped FEX's thunk
overlay and loaded their bundled desktop Mesa drivers, which crash on the
phone's GPU during Vulkan setup. droiddeck-fex now adds an x86-64 audit
module when a program's bundled glibc and libstdc++ meet the thunk's
version needs. The module sends libvulkan.so.1 lookups to a nodelete stub
that needs FEX's thunk path. That keeps the thunk mapped when an app
unloads Vulkan and loads it again, since FEX keeps its first trampoline
links and the old addresses get reused.
The fault reporter now restores the default action before re-raising,
because FEX ignores SA_RESETHAND and the handler looped.
This commit is contained in:
1 parent
4cc9f2a3f3
commit
49a5f4aa94
165 files changed
+11709
-9667
No files matched your search
@@ -3,7 +3,7 @@
|
||||
# session: "plasma", "plasma-wayland-persistent", ...) and waits for Game Mode to end; with nothing
|
||||
# here it sat on "Switching to Desktop..." for ever. Here the desktop is DroidDeck's own: the app is
|
||||
# asked for a desktop session with Steam's desktop client open in it (the request file
|
||||
# bannerlator-steam-launch uses; the app ends this session and starts that one). Anything else -
|
||||
# droiddeck-steam-launch uses; the app ends this session and starts that one). Anything else -
|
||||
# "gamescope", the session Game Mode already is - has nothing to do.
|
||||
echo "steamos-session-select: $*" >&2
|
||||
case "${1:-}" in
|
||||
|
||||
@@ -1,69 +0,0 @@
|
||||
#!/bin/bash
|
||||
# An AppImage imported from the front end (AppImageManager), extracted once at import into
|
||||
# /opt/appimages/user/<id>/app
|
||||
# and started from there: proot has no FUSE to mount the image, and extracting it at every
|
||||
# start (APPIMAGE_EXTRACT_AND_RUN) would cost the whole image in /tmp each time.
|
||||
# bannerlator-appimage-run /opt/appimages/user/<id> [args...]
|
||||
set -u
|
||||
dir=${1:?usage: bannerlator-appimage-run <imported AppImage directory> [args...]}
|
||||
shift
|
||||
export APPDIR=$dir/app
|
||||
# APPIMAGE is left unset on purpose: with it an app believes it runs from an image file and offers
|
||||
# to add itself to the menu (DuckStation) or update the file in place - DroidDeck already does the
|
||||
# one, and there is no image file for the other.
|
||||
unset APPIMAGE
|
||||
export ARGV0=$(cat "$dir/name" 2>/dev/null || basename "$dir")
|
||||
if [ ! -x "$APPDIR/AppRun" ]; then
|
||||
echo "bannerlator-appimage-run: $APPDIR/AppRun is missing; import the AppImage again" >&2
|
||||
exit 127
|
||||
fi
|
||||
# Browsers sandbox their own children with namespaces and a setuid helper, neither of which proot
|
||||
# can give them (the Flatpak sandboxes get the same; see BwrapSpawner): Firefox and its forks (Zen,
|
||||
# LibreWolf) by these switches, Electron and Chromium builds by --no-sandbox. Chromium on Wayland
|
||||
# also asks the render node for a DRM version KGSL cannot give, so with an X server up it stays on
|
||||
# X11, which it picks from the session type.
|
||||
export MOZ_DISABLE_CONTENT_SANDBOX=1 MOZ_DISABLE_GMP_SANDBOX=1 MOZ_DISABLE_RDD_SANDBOX=1
|
||||
export MOZ_DISABLE_SOCKET_PROCESS_SANDBOX=1 MOZ_DISABLE_UTILITY_SANDBOX=1
|
||||
# sharun images start the app through their own ld.so, patched not to read /etc/ld.so.preload, and
|
||||
# drop LD_PRELOAD unless allowed: without this the app never gets the session's pads.
|
||||
if [ -s /etc/ld.so.preload ]; then
|
||||
preload=$(tr -s '\n' ':' < /etc/ld.so.preload)
|
||||
export LD_PRELOAD="${preload%:}${LD_PRELOAD:+:$LD_PRELOAD}" SHARUN_ALLOW_LD_PRELOAD=1
|
||||
fi
|
||||
flags=()
|
||||
if [ -e "$APPDIR/chrome-sandbox" ] || compgen -G "$APPDIR/*/chrome-sandbox" >/dev/null; then
|
||||
flags+=(--no-sandbox)
|
||||
if [ -n "${DISPLAY:-}" ]; then
|
||||
export XDG_SESSION_TYPE=x11
|
||||
unset WAYLAND_DISPLAY
|
||||
flags+=(--ozone-platform=x11)
|
||||
fi
|
||||
fi
|
||||
echo "== appimage $ARGV0 ($APPDIR) ${flags[*]}"
|
||||
cd "$APPDIR" || exit 1
|
||||
# Apps expect a session bus; Electron's main process traps (SIGTRAP) on an address it cannot
|
||||
# parse. A run mode has none, so one is started for the app, as for Flatpak apps.
|
||||
case ${DBUS_SESSION_BUS_ADDRESS:-} in
|
||||
unix:*) "$APPDIR/AppRun" "${flags[@]}" "$@" ;;
|
||||
*) unset DBUS_SESSION_BUS_ADDRESS
|
||||
if command -v dbus-run-session >/dev/null 2>&1; then
|
||||
dbus-run-session -- "$APPDIR/AppRun" "${flags[@]}" "$@"
|
||||
else
|
||||
"$APPDIR/AppRun" "${flags[@]}" "$@"
|
||||
fi ;;
|
||||
esac
|
||||
rc=$?
|
||||
# The program a session was started for may hand over to another process and exit: Electron apps
|
||||
# relaunch themselves (Obsidian on its first start), launchers fork their real program. The
|
||||
# session ends with this script, and takes the rest with it - so it waits while anything running
|
||||
# from the image is still up.
|
||||
image_running() {
|
||||
local p exe
|
||||
for p in /proc/[0-9]*; do
|
||||
exe=$(readlink "$p/exe" 2>/dev/null) || continue
|
||||
case $exe in "$APPDIR"/*) return 0 ;; esac
|
||||
done
|
||||
return 1
|
||||
}
|
||||
while image_running; do sleep 2; done
|
||||
exit $rc
|
||||
@@ -1,37 +0,0 @@
|
||||
#!/bin/bash
|
||||
# A script added on the Desktop page (UserApps), run from its own folder:
|
||||
# bannerlator-script-run /opt/droiddeck-apps/<id> [args...]
|
||||
set -u
|
||||
dir=${1:?usage: bannerlator-script-run <added app directory> [args...]}
|
||||
shift
|
||||
entry=$(cat "$dir/entry" 2>/dev/null) || { echo "bannerlator-script-run: $dir has no entry" >&2; exit 127; }
|
||||
cd -P "$dir/files" 2>/dev/null || { echo "bannerlator-script-run: $dir/files is missing; add the script again" >&2; exit 127; }
|
||||
folder=$PWD
|
||||
# Shared storage is noexec, so the script is handed to its interpreter rather than executed.
|
||||
first=
|
||||
IFS= read -r first < "$entry"
|
||||
first=${first%$'\r'}
|
||||
interp=(/bin/bash)
|
||||
case $first in '#!'*) read -r -a interp <<< "${first#'#!'}" ;; esac
|
||||
echo "== script $entry in $folder (${interp[*]})"
|
||||
case ${DBUS_SESSION_BUS_ADDRESS:-} in
|
||||
unix:*) "${interp[@]}" "./$entry" "$@" ;;
|
||||
*) unset DBUS_SESSION_BUS_ADDRESS
|
||||
if command -v dbus-run-session >/dev/null 2>&1; then
|
||||
dbus-run-session -- "${interp[@]}" "./$entry" "$@"
|
||||
else
|
||||
"${interp[@]}" "./$entry" "$@"
|
||||
fi ;;
|
||||
esac
|
||||
rc=$?
|
||||
# A launcher script often starts the game and returns; the session lasts while it runs.
|
||||
running() {
|
||||
local p exe
|
||||
for p in /proc/[0-9]*; do
|
||||
exe=$(readlink "$p/exe" 2>/dev/null) || continue
|
||||
case $exe in "$folder"/*) return 0 ;; esac
|
||||
done
|
||||
return 1
|
||||
}
|
||||
while running; do sleep 2; done
|
||||
exit $rc
|
||||
@@ -1,641 +0,0 @@
|
||||
#!/usr/bin/python3
|
||||
# Makes the ARM64 Proton the client already downloaded usable here, and sets it as the default tool
|
||||
# for Windows titles (CompatToolMapping "0" in config.vdf) when the user has not chosen one. Run
|
||||
# before the client starts; it rewrites config.vdf on exit.
|
||||
#
|
||||
# bannerlator-steam-compat <steam root>
|
||||
#
|
||||
# Valve ships a native aarch64 Proton (arm64ec Wine with FEX as the x86 layer) as an ordinary depot,
|
||||
# which is exactly what this runtime wants. Its toolmanifest declares require_tool_appid 4185400 -
|
||||
# Steam Linux Runtime 4 for arm64 - so Steam stacks pressure-vessel underneath it, and
|
||||
# pressure-vessel needs unprivileged user namespaces, which an Android app does not get. Steam then
|
||||
# drops the launch on the floor: no window, no log, straight back to the library.
|
||||
#
|
||||
# So the depot is re-registered here as a compatibility tool of our own: every entry symlinked so
|
||||
# nothing is copied and Steam still updates the real depot, but with a toolmanifest that leaves out
|
||||
# require_tool_appid. Proton takes its base directory from dirname(sys.argv[0]) without resolving
|
||||
# it, so it reads files/ through those symlinks and runs directly on this rootfs.
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import sys
|
||||
|
||||
TOOL = "bannerlator-proton-arm64"
|
||||
# Valve's own ARM64 Proton, by the name the client registers it under. Used only to bootstrap a
|
||||
# fresh install: naming it is what makes the client offer it and fetch the depot.
|
||||
SEED_TOOL = "proton-experimental-arm64"
|
||||
# The ARM64 Proton depot the client downloads for itself, as a compatibility-tool appid.
|
||||
# The session asks the client to install it on the command line the first time (steam://install),
|
||||
# so a new client has it before a Windows title is first launched. It is deliberately NOT named as
|
||||
# this tool's dependency: a dependency is composed with its own dependencies, and this depot
|
||||
# requires 4185400, the arm64 Steam Linux Runtime, whose container needs user namespaces Android
|
||||
# does not give - the launch would be wrapped in it and die before this tool ever ran.
|
||||
PROTON_ARM64_APPID = "4427310"
|
||||
LAUNCHER = "bannerlator-proton"
|
||||
# The extra Steam library the app mounts the installed games into (see bannerlator-steam-library).
|
||||
# installed_apps() scans it too; it lives only in the sibling script, so define it here as well.
|
||||
LIBRARY = "/mnt/bannerlator" # the card library is LIBRARY + "-sd"; internal storage is steam_root itself
|
||||
# The client lists its own "Proton Experimental (ARM64)" and "Proton 11.0 (ARM64)" in the same
|
||||
# Compatibility dropdown, and those are the two that cannot start a game here. Ours has to be
|
||||
# unmistakable at a glance, or a user picks a neighbour and gets a launch that fails silently.
|
||||
# Newest first: whichever the client has downloaded is used.
|
||||
SOURCES = ("Proton Experimental (ARM64)", "Proton 11.0 (ARM64)")
|
||||
# Written by us; everything else in the depot is symlinked through.
|
||||
OWN_FILES = ("toolmanifest.vdf", "compatibilitytool.vdf", "bannerlator-proton")
|
||||
# The client assigns a Proton to a Windows title by itself, as a per-app CompatToolMapping entry at
|
||||
# priority 250 - which outranks the "0" default, so setting that default alone changes nothing. Every
|
||||
# Proton it can pick is one this runtime cannot start: the ARM64 ones want pressure-vessel (see
|
||||
# above) and the x86_64 ones want pressure-vessel and FEX on top. Ours is the only one that runs
|
||||
# here, so every Proton mapping is repointed at it. Tools that are not Proton are left alone.
|
||||
COMPAT_TOOL_VDF = """"compatibilitytools"
|
||||
{
|
||||
"compat_tools"
|
||||
{
|
||||
"%s"
|
||||
{
|
||||
"install_path" "."
|
||||
"display_name" "Bannerlator Proton (ARM64)"
|
||||
"from_oslist" "windows"
|
||||
"to_oslist" "linux"
|
||||
}
|
||||
}
|
||||
}
|
||||
"""
|
||||
TOOL_MANIFEST_VDF = """"manifest"
|
||||
{
|
||||
"version" "2"
|
||||
"commandline" "/%s %%verb%%"
|
||||
"use_sessions" "1"
|
||||
"compatmanager_layer_name" "proton"
|
||||
}
|
||||
""" % LAUNCHER
|
||||
|
||||
|
||||
# Steam runs its own graphics probe through EVERY registered tool at once, ~40 s after logging in,
|
||||
# all with STEAM_COMPAT_DATA_PATH=.../compatdata/0, and those concurrent Protons can write their
|
||||
# builtin DLLs through each other's prefix links into each other's trees (seen: GE's FEX DLLs became
|
||||
# Proton Experimental's). Moving those runs to a prefix per tool was tried and crashed the Steam
|
||||
# client right after the probe started (segfault, rc 139, first ever in 25 sessions), so the client
|
||||
# relies on compatdata/0 itself. The launch-time check below is the protection instead.
|
||||
|
||||
# The Components page's choices, enforced in the one place every game launch passes: the app keeps
|
||||
# desired.tsv (tool dir, Proton build, component, file, sha256, source copy) and an unpacked copy of
|
||||
# each package in use. A file that no longer matches - whatever changed it - is put back before
|
||||
# Proton starts. Only for the Proton build the choice was made for: after a Steam update the build
|
||||
# differs and the Proton's own new files are left alone until the user chooses again.
|
||||
BL_COMPONENTS_SETUP = """
|
||||
bl_components() {
|
||||
base=$1
|
||||
cm_dir="${HOME:-/root}/.local/share/bannerlator-components"
|
||||
cm_list="$cm_dir/desired.tsv"
|
||||
# A real game launch only: the verb the client starts a game with and the game's own prefix. Every
|
||||
# other run - above all the client's own probes right after login, which all share compatdata/0 -
|
||||
# is left exactly as it was: with this check running through them, the client segfaulted (rc 139)
|
||||
# within seconds of starting its probes, four sessions out of four. The prefix decides rather than
|
||||
# the app id because a non-Steam shortcut launches with app id 0 but still gets a prefix of its own.
|
||||
[ "${verb:-}" = waitforexitandrun ] || return 0
|
||||
case "${STEAM_COMPAT_DATA_PATH:-}" in ''|*/compatdata/0|*/compatdata/0/|*/compatdata/0-*) return 0 ;; esac
|
||||
[ -f "$cm_list" ] || return 0
|
||||
cm_app=${STEAM_COMPAT_DATA_PATH%/}
|
||||
cm_app=${cm_app##*/}
|
||||
cm_tool=${base##*/}
|
||||
cm_build=$(awk 'NR == 1 { print $2 }' "$base/version" 2>/dev/null)
|
||||
cm_fixed=0
|
||||
cm_checked=0
|
||||
while IFS=$'\\t' read -r t want comp rel sum src; do
|
||||
[ "$t" = "$cm_tool" ] && [ "$want" = "$cm_build" ] || continue
|
||||
cm_checked=$((cm_checked + 1))
|
||||
f="$base/$rel"
|
||||
if [ -f "$f" ] && [ "$(sha256sum "$f" | cut -d' ' -f1)" = "$sum" ]; then continue; fi
|
||||
if [ ! -f "$src" ]; then
|
||||
echo "bannerlator-proton: components: $comp source missing ($src), left as it is" >&2
|
||||
continue
|
||||
fi
|
||||
mkdir -p "$(dirname "$f")"
|
||||
cp -f "$src" "$f.bl-new" && mv -f "$f.bl-new" "$f" || continue
|
||||
case "$rel" in *.so) chmod 755 "$f" ;; *) chmod 644 "$f" ;; esac
|
||||
cm_fixed=$((cm_fixed + 1))
|
||||
done < "$cm_list"
|
||||
[ "$cm_checked" -gt 0 ] && echo "bannerlator-proton: components: checked $cm_checked file(s) in $cm_tool for app $cm_app" >&2
|
||||
if [ "$cm_fixed" -gt 0 ]; then
|
||||
echo "bannerlator-proton: components: re-applied $cm_fixed of $cm_checked file(s) in $cm_tool before this launch" >&2
|
||||
printf '%s\\t%s\\t%s\\n' "$(date +%s)" "$cm_tool" "$cm_fixed" >> "$cm_dir/reapplied.log"
|
||||
fi
|
||||
}
|
||||
"""
|
||||
|
||||
# Resolves the depot at launch time, so the tool can be registered before the depot exists and
|
||||
# survives the client updating or replacing it. Proton takes its base directory from
|
||||
# dirname(sys.argv[0]) without resolving it, so it is run from the depot itself.
|
||||
# Cores for a game the client launches, kept separate from the client's own. One mask suits the
|
||||
# client's menus and another suits a game, and they are wanted at the same time - so the game's is
|
||||
# applied here, in the launch path every game goes through, rather than to the session as a whole.
|
||||
BL_GAME_CPUS_SETUP = """
|
||||
bl_game_cpus() {
|
||||
[ -n "${BL_GAME_CPUS:-}" ] || return 0
|
||||
command -v taskset >/dev/null 2>&1 || return 0
|
||||
# exec'd through taskset rather than set afterwards: a mask applied to a pid races the process
|
||||
# into spawning its own threads, and this way every thread inherits it from the first instruction.
|
||||
BL_TASKSET="taskset -c $BL_GAME_CPUS"
|
||||
echo "bannerlator-proton: game cores $BL_GAME_CPUS" >&2
|
||||
}
|
||||
"""
|
||||
|
||||
# Quake III engine games (id Tech 3) set their own resolution and switch the display to it. Under
|
||||
# gamescope with the ARM64 Proton that switch is refused ("calling CDS: failed, bad mode") and the
|
||||
# game never gets OpenGL; left at its own size in a window, it draws small in a corner. So these
|
||||
# titles are told to stay windowed at the session's own size - unless the user's launch options
|
||||
# already say something about the video mode, which are left as they are.
|
||||
# The session puts the client's own libraries (steamrtarm64, its panorama/) ahead of everything for
|
||||
# the client, and a game inherits that: Wine then resolved gnutls, SDL, FFmpeg and the rest against
|
||||
# the client's private copies instead of the rootfs it was built for. Inside Steam's runtime
|
||||
# container that path never reaches Proton either. (WinNative's winnative-proton-launch.)
|
||||
BL_LIBPATH_SETUP = """
|
||||
bl_libpath() {
|
||||
# A Proton built to prefer PipeWire (CachyOS's among the adopted ones) hung its audio thread
|
||||
# here, where only PulseAudio answers. (WinNative, winnative-proton-launch.)
|
||||
export PROTON_USE_PIPEWIRE=${PROTON_USE_PIPEWIRE:-0}
|
||||
[ -n "${LD_LIBRARY_PATH:-}" ] || return 0
|
||||
local kept= dir old_ifs=$IFS
|
||||
IFS=:
|
||||
for dir in $LD_LIBRARY_PATH; do
|
||||
case $dir in
|
||||
"" | */steamrtarm64 | */steamrtarm64/*) ;;
|
||||
*) kept=${kept:+$kept:}$dir ;;
|
||||
esac
|
||||
done
|
||||
IFS=$old_ifs
|
||||
if [ -n "$kept" ]; then export LD_LIBRARY_PATH="$kept"; else unset LD_LIBRARY_PATH; fi
|
||||
}
|
||||
"""
|
||||
|
||||
BL_IDTECH3_SETUP = """
|
||||
bl_idtech3() {
|
||||
BL_EXTRA_ARGS=()
|
||||
case "${SteamAppId:-${STEAM_COMPAT_APP_ID:-}}" in
|
||||
# Quake III Arena, Quake III: Team Arena, Return to Castle Wolfenstein, Jedi Academy.
|
||||
2200|2350|9010|6020) ;;
|
||||
*) return 0 ;;
|
||||
esac
|
||||
case " $* " in
|
||||
*r_fullscreen*|*r_mode*|*r_customwidth*|*r_customheight*)
|
||||
echo "bannerlator-proton: Quake-engine title; its launch options set the video mode, left as they are" >&2
|
||||
return 0 ;;
|
||||
esac
|
||||
w=${BL_WIDTH:-1280}
|
||||
h=${BL_HEIGHT:-720}
|
||||
BL_EXTRA_ARGS=(+set r_fullscreen 0 +set r_mode -1 +set r_customwidth "$w" +set r_customheight "$h")
|
||||
echo "bannerlator-proton: Quake-engine title: windowed at ${w}x${h}" >&2
|
||||
}
|
||||
"""
|
||||
|
||||
BL_DIRECTAUDIO_SETUP = """
|
||||
bl_directaudio() {
|
||||
base=$1
|
||||
[ -n "${BL_DIRECTAUDIO:-}" ] || return 0
|
||||
[ -d "$BL_DIRECTAUDIO/lib/wine" ] || return 0
|
||||
version=$("$base/files/bin-arm64/wine" --version 2>/dev/null)
|
||||
major=${version#wine-}
|
||||
major=${major%%.*}
|
||||
if [ "$major" != "11" ]; then
|
||||
echo "bannerlator-proton: DirectAudio left off - it is built for Wine 11 and this Proton is '${version:-unknown}'. Pairing them would be silent rather than broken, so it is not worth guessing." >&2
|
||||
return 0
|
||||
fi
|
||||
# Wine appends the per-architecture subdirectory to each entry, so the directory holding
|
||||
# aarch64-unix/ and aarch64-windows/ is what goes here.
|
||||
WINEDLLPATH="$BL_DIRECTAUDIO/lib/wine${WINEDLLPATH:+:$WINEDLLPATH}"
|
||||
export WINEDLLPATH
|
||||
# mmdevapi only tries the drivers named in the registry; its built-in list is pulse, alsa, oss and
|
||||
# coreaudio and knows nothing about this one. The key is appended to the prefix's user.reg rather
|
||||
# than written with `wine reg`, which would start a wineserver here just to set one value.
|
||||
reg="${STEAM_COMPAT_DATA_PATH:-}/pfx/user.reg"
|
||||
if [ -f "$reg" ]; then
|
||||
if ! grep -q '"Audio"="directaudio"' "$reg" 2>/dev/null; then
|
||||
printf '\n[Software\\\\Wine\\\\Drivers] %s\n"Audio"="directaudio"\n' "$(date +%s)" >> "$reg"
|
||||
echo "bannerlator-proton: DirectAudio selected in the prefix" >&2
|
||||
fi
|
||||
else
|
||||
# A prefix that does not exist yet is created by Proton moments from now, after this runs, so
|
||||
# the key lands on the NEXT launch of that game. Said out loud because silent audio on a first
|
||||
# launch would otherwise look like a fault.
|
||||
echo "bannerlator-proton: no prefix yet - DirectAudio takes effect the next time this game starts" >&2
|
||||
fi
|
||||
echo "bannerlator-proton: DirectAudio ready (Wine $major)" >&2
|
||||
}
|
||||
"""
|
||||
|
||||
# Resolves the depot at launch time, so the tool can be registered before the depot exists and
|
||||
# survives the client updating or replacing it. Proton takes its base directory from
|
||||
# dirname(sys.argv[0]) without resolving it, so it is run from the depot itself.
|
||||
LAUNCHER_SH = """#!/bin/bash
|
||||
# Bannerlator Proton (ARM64): runs the ARM64 Proton the Steam client downloaded, without the
|
||||
# Steam Linux Runtime container its own manifest asks for (no user namespaces on Android).
|
||||
verb=$1; shift
|
||||
steam_root=${STEAM_COMPAT_CLIENT_INSTALL_PATH:-${XDG_DATA_HOME:-$HOME/.local/share}/Steam}
|
||||
# Steam's overlay is preloaded into every game Valve launches, and used to be dropped here: it was
|
||||
# landing in front of open() and read() on /dev/input, letting Wine open the session's pad and
|
||||
# answering every read of it with nothing - a controller that never reports, and Wine's HID thread
|
||||
# spinning a core on it.
|
||||
#
|
||||
# Removing it was the wrong cure for an ordering problem. glibc processes LD_PRELOAD BEFORE
|
||||
# /etc/ld.so.preload, and the interposer lives in the latter, so the overlay was simply ahead of it.
|
||||
# Naming the interposer first in LD_PRELOAD puts it back in front and the overlay loads as Valve
|
||||
# intends. That matters beyond the overlay itself: every deviation from the launch Valve ships is a
|
||||
# difference this runtime would otherwise have to justify.
|
||||
fake=/usr/local/lib/libfakeinput.so
|
||||
if [ -f "$fake" ]; then
|
||||
case ":${LD_PRELOAD:-}:" in
|
||||
*":$fake:"*) ;;
|
||||
*) LD_PRELOAD="$fake${LD_PRELOAD:+:$LD_PRELOAD}"; export LD_PRELOAD ;;
|
||||
esac
|
||||
fi
|
||||
# The newest of the ARM64 depots the client has, by the build number that opens each one's version
|
||||
# file: taking the first one found ran a stale Experimental over a newer 11.0. (WinNative.)
|
||||
depot=
|
||||
best=0
|
||||
for name in %s; do
|
||||
for library in "$steam_root" /mnt/droiddeck-sd; do
|
||||
candidate="$library/steamapps/common/$name"
|
||||
[ -d "$candidate/files/bin-arm64" ] && [ -x "$candidate/proton" ] || continue
|
||||
build=0
|
||||
read -r build _ 2>/dev/null < "$candidate/version"
|
||||
case $build in "" | *[!0-9]*) build=0 ;; esac
|
||||
if [ -z "$depot" ] || [ "$build" -gt "$best" ]; then
|
||||
depot=$candidate
|
||||
best=$build
|
||||
fi
|
||||
done
|
||||
done
|
||||
if [ -n "$depot" ]; then
|
||||
bl_components "$depot"
|
||||
bl_directaudio "$depot"
|
||||
bl_game_cpus
|
||||
bl_idtech3 "$@"
|
||||
bl_libpath
|
||||
exec ${BL_TASKSET:-} /usr/local/bin/bannerlator-game-env "$depot/proton" "$verb" "$@" "${BL_EXTRA_ARGS[@]}"
|
||||
fi
|
||||
echo "bannerlator-proton: no ARM64 Proton depot yet - the client downloads one as this tool's dependency; retry the launch once it has" >&2
|
||||
exit 1
|
||||
""" % " ".join('"%s"' % n for n in SOURCES)
|
||||
# Spliced in after the formatting above, never through it: the function body contains ${major%%.*}
|
||||
# and a % format would eat that into a single %, leaving a shell expansion that silently does
|
||||
# something else.
|
||||
LAUNCHER_SH = LAUNCHER_SH.replace(
|
||||
"verb=$1; shift", "verb=$1; shift\n" + BL_DIRECTAUDIO_SETUP + BL_GAME_CPUS_SETUP + BL_IDTECH3_SETUP
|
||||
+ BL_COMPONENTS_SETUP + BL_LIBPATH_SETUP, 1)
|
||||
|
||||
# A third-party Proton dropped into compatibilitytools.d - GE-Proton, proton-cachyos, anything of
|
||||
# that shape - is adopted rather than used as shipped, for the same two reasons Valve's ARM64 depot
|
||||
# is: its manifest declares require_tool_appid, and the client's overlay library has to come out of
|
||||
# LD_PRELOAD. Its own entry point is left untouched and called through this wrapper.
|
||||
EXTRA_WRAPPER = "bannerlator-proton-wrap"
|
||||
EXTRA_MANIFEST_VDF = """"manifest"
|
||||
{
|
||||
"version" "2"
|
||||
"commandline" "/%s %%verb%%"
|
||||
"use_sessions" "1"
|
||||
"compatmanager_layer_name" "proton"
|
||||
}
|
||||
""" % EXTRA_WRAPPER
|
||||
# %s is the tool's own entry point, read out of the manifest it shipped with.
|
||||
EXTRA_WRAPPER_SH = """#!/bin/bash
|
||||
# Bannerlator: runs a Proton installed into compatibilitytools.d without the Steam Linux Runtime
|
||||
# container its own manifest asks for - pressure-vessel needs unprivileged user namespaces, which
|
||||
# an Android app does not get, and the launch dies before Proton is reached.
|
||||
verb=$1; shift
|
||||
here=$(dirname "$0")
|
||||
# See bannerlator-proton: the interposer goes first in LD_PRELOAD rather than the overlay being
|
||||
# removed, because glibc reads LD_PRELOAD before /etc/ld.so.preload and the overlay was simply
|
||||
# ahead of it on /dev/input.
|
||||
fake=/usr/local/lib/libfakeinput.so
|
||||
if [ -f "$fake" ]; then
|
||||
case ":${LD_PRELOAD:-}:" in
|
||||
*":$fake:"*) ;;
|
||||
*) LD_PRELOAD="$fake${LD_PRELOAD:+:$LD_PRELOAD}"; export LD_PRELOAD ;;
|
||||
esac
|
||||
fi
|
||||
bl_components "$here"
|
||||
bl_directaudio "$here"
|
||||
bl_game_cpus
|
||||
bl_idtech3 "$@"
|
||||
bl_libpath
|
||||
# Proton takes its base directory from dirname(sys.argv[0]) without resolving it, so it has to be
|
||||
# started from its own tree.
|
||||
exec ${BL_TASKSET:-} /usr/local/bin/bannerlator-game-env "$here/%s" "$verb" "$@" "${BL_EXTRA_ARGS[@]}"
|
||||
"""
|
||||
EXTRA_COMPAT_TOOL_VDF = """"compatibilitytools"
|
||||
{
|
||||
"compat_tools"
|
||||
{
|
||||
"%s"
|
||||
{
|
||||
"install_path" "."
|
||||
"display_name" "%s (Bannerlator)"
|
||||
"from_oslist" "windows"
|
||||
"to_oslist" "linux"
|
||||
}
|
||||
}
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
TOKEN = re.compile(r'\s*(?:"((?:[^"\\]|\\.)*)"|([{}])|//[^\n]*)')
|
||||
|
||||
|
||||
def tokenize(text):
|
||||
tokens = []
|
||||
pos = 0
|
||||
while pos < len(text):
|
||||
m = TOKEN.match(text, pos)
|
||||
if not m or m.end() == pos:
|
||||
break
|
||||
pos = m.end()
|
||||
if m.group(2):
|
||||
tokens.append(m.group(2))
|
||||
elif m.group(1) is not None:
|
||||
tokens.append('"' + m.group(1) + '"')
|
||||
return tokens
|
||||
|
||||
|
||||
def find_block(tokens, path):
|
||||
"""Index of the '{' opening the block at path, or None."""
|
||||
depth, want, i = 0, 0, 0
|
||||
while i < len(tokens):
|
||||
t = tokens[i]
|
||||
if t == "{":
|
||||
depth += 1
|
||||
elif t == "}":
|
||||
depth -= 1
|
||||
if depth < want:
|
||||
return None
|
||||
elif depth == want and i + 1 < len(tokens) and tokens[i + 1] == "{":
|
||||
if t.lower() == '"%s"' % path[want].lower():
|
||||
if want == len(path) - 1:
|
||||
return i + 1
|
||||
want += 1
|
||||
i += 1
|
||||
return None
|
||||
|
||||
|
||||
def block_end(tokens, start):
|
||||
depth = 0
|
||||
for i in range(start, len(tokens)):
|
||||
if tokens[i] == "{":
|
||||
depth += 1
|
||||
elif tokens[i] == "}":
|
||||
depth -= 1
|
||||
if depth == 0:
|
||||
return i
|
||||
return len(tokens)
|
||||
|
||||
|
||||
def serialize(tokens):
|
||||
out, depth, i = [], 0, 0
|
||||
while i < len(tokens):
|
||||
t = tokens[i]
|
||||
if t == "}":
|
||||
depth -= 1
|
||||
out.append("\t" * depth + "}")
|
||||
i += 1
|
||||
elif i + 1 < len(tokens) and tokens[i + 1] == "{":
|
||||
out.append("\t" * depth + t)
|
||||
out.append("\t" * depth + "{")
|
||||
depth += 1
|
||||
i += 2
|
||||
else:
|
||||
out.append("\t" * depth + t + "\t\t" + tokens[i + 1])
|
||||
i += 2
|
||||
return "\n".join(out) + "\n"
|
||||
|
||||
|
||||
def write_changed(path, text, mode=None):
|
||||
"""Writes `text` to `path` only when it differs, through a rename so a reader never sees half a
|
||||
file. The session runs this script every 15 s for as long as the client does; rewriting files
|
||||
that have not changed cost a python start's worth of writes each time, and config.vdf is the
|
||||
client's own, which it may be writing at that moment. Returns whether anything was written."""
|
||||
try:
|
||||
with open(path, encoding="utf-8", errors="replace") as f:
|
||||
same = f.read() == text
|
||||
except OSError:
|
||||
same = False
|
||||
if not same:
|
||||
tmp = path + ".bannerlator"
|
||||
with open(tmp, "w", encoding="utf-8") as f:
|
||||
f.write(text)
|
||||
if mode is not None:
|
||||
os.chmod(tmp, mode)
|
||||
os.replace(tmp, path)
|
||||
elif mode is not None and (os.stat(path).st_mode & 0o7777) != mode:
|
||||
os.chmod(path, mode)
|
||||
return not same
|
||||
|
||||
|
||||
def first_key(path, section):
|
||||
"""The single key naming a block inside `section`, or None. Used to keep a third-party tool's
|
||||
own internal name, so a mapping the user already made against it keeps working."""
|
||||
try:
|
||||
with open(path, encoding="utf-8", errors="replace") as f:
|
||||
tokens = tokenize(f.read())
|
||||
except OSError:
|
||||
return None
|
||||
block = find_block(tokens, section)
|
||||
if block is None:
|
||||
return None
|
||||
for i in range(block + 1, block_end(tokens, block)):
|
||||
if tokens[i] == "}":
|
||||
break
|
||||
if i + 1 < len(tokens) and tokens[i + 1] == "{":
|
||||
return tokens[i].strip('"')
|
||||
return None
|
||||
|
||||
|
||||
def manifest_entry_point(path):
|
||||
"""The script a toolmanifest's commandline runs, relative to the tool directory."""
|
||||
try:
|
||||
with open(path, encoding="utf-8", errors="replace") as f:
|
||||
tokens = tokenize(f.read())
|
||||
except OSError:
|
||||
return None
|
||||
for i in range(len(tokens) - 1):
|
||||
if tokens[i].lower() == '"commandline"':
|
||||
command = tokens[i + 1].strip('"').split()
|
||||
if command:
|
||||
return command[0].lstrip("/")
|
||||
return None
|
||||
|
||||
|
||||
def adopt_extras(tools):
|
||||
"""Makes every other Proton in compatibilitytools.d launchable here, and returns the tool names
|
||||
to leave alone in CompatToolMapping - the whole point of installing one is to pick it per game,
|
||||
so register_default must not repoint it back at ours."""
|
||||
adopted = {}
|
||||
try:
|
||||
entries = sorted(os.listdir(tools))
|
||||
except OSError:
|
||||
return adopted
|
||||
for entry in entries:
|
||||
if entry == TOOL or entry.startswith("."):
|
||||
continue
|
||||
tool_dir = os.path.join(tools, entry)
|
||||
manifest = os.path.join(tool_dir, "toolmanifest.vdf")
|
||||
if not os.path.isdir(tool_dir) or not os.path.isfile(manifest):
|
||||
continue
|
||||
# The shipped manifest is kept, once, and stays the source of the entry point: re-running
|
||||
# must not read back our own rewritten commandline and wrap the wrapper.
|
||||
original = manifest + ".bannerlator-orig"
|
||||
if not os.path.isfile(original):
|
||||
try:
|
||||
shutil.copy2(manifest, original)
|
||||
except OSError:
|
||||
continue
|
||||
entry_point = manifest_entry_point(original)
|
||||
if not entry_point or entry_point == EXTRA_WRAPPER:
|
||||
entry_point = "proton"
|
||||
if not os.path.exists(os.path.join(tool_dir, entry_point)):
|
||||
print("bannerlator-steam-compat: %s has no %s; left alone" % (entry, entry_point))
|
||||
continue
|
||||
compat_vdf = os.path.join(tool_dir, "compatibilitytool.vdf")
|
||||
name = first_key(compat_vdf, ["compatibilitytools", "compat_tools"]) or entry
|
||||
wrapper = os.path.join(tool_dir, EXTRA_WRAPPER)
|
||||
try:
|
||||
# Formatted first, spliced second: the function carries a printf %s and a
|
||||
# ${major%%.*} of its own, and putting it through the format would eat both.
|
||||
body = (EXTRA_WRAPPER_SH % entry_point).replace(
|
||||
'here=$(dirname "$0")',
|
||||
'here=$(dirname "$0")\n' + BL_DIRECTAUDIO_SETUP + BL_GAME_CPUS_SETUP + BL_IDTECH3_SETUP
|
||||
+ BL_COMPONENTS_SETUP + BL_LIBPATH_SETUP, 1)
|
||||
write_changed(wrapper, body, 0o755)
|
||||
write_changed(manifest, EXTRA_MANIFEST_VDF)
|
||||
write_changed(compat_vdf, EXTRA_COMPAT_TOOL_VDF % (name, entry))
|
||||
except OSError as e:
|
||||
print("bannerlator-steam-compat: could not adopt %s (%s)" % (entry, e))
|
||||
continue
|
||||
adopted[name] = entry
|
||||
return adopted
|
||||
|
||||
|
||||
# Steam's own tools and runtimes live in steamapps beside the games; they are not titles and must
|
||||
# not be mapped to a compatibility tool.
|
||||
NOT_GAMES = frozenset((
|
||||
"228980", # Steamworks Common Redistributables
|
||||
"1070560", # Steam Linux Runtime 1.0 (scout)
|
||||
"1391110", # Steam Linux Runtime 2.0 (soldier)
|
||||
"1493710", # Proton Experimental
|
||||
"3127680", # FEX
|
||||
"4183110", # Steam Linux Runtime 4.0
|
||||
"4185400", # Steam Linux Runtime 4.0 - Arm64
|
||||
"4427310", # Proton Experimental (ARM64)
|
||||
"4628740", # Proton 11.0 (ARM64)
|
||||
))
|
||||
|
||||
|
||||
def installed_apps(steam_root):
|
||||
"""App ids of the titles the client has installed, tools and runtimes excluded."""
|
||||
apps = set()
|
||||
for library in (steam_root, LIBRARY + "-sd"):
|
||||
steamapps = os.path.join(library, "steamapps")
|
||||
try:
|
||||
names = os.listdir(steamapps)
|
||||
except OSError:
|
||||
continue
|
||||
for name in names:
|
||||
m = re.fullmatch(r"appmanifest_(\d+)\.acf", name)
|
||||
if m and m.group(1) not in NOT_GAMES:
|
||||
apps.add(m.group(1))
|
||||
return sorted(apps, key=int)
|
||||
|
||||
|
||||
def register_default(config_path, apps=(), name=None, protect=()):
|
||||
"""Writes the mapping. `name` defaults to our own tool; the first-run seed passes Valve's."""
|
||||
tool = name or TOOL
|
||||
# Tool names the user may deliberately have chosen (see adopt_extras); never repointed.
|
||||
keep = {n.lower() for n in protect}
|
||||
with open(config_path, encoding="utf-8", errors="replace") as f:
|
||||
original = f.read()
|
||||
tokens = tokenize(original)
|
||||
steam = find_block(tokens, ["InstallConfigStore", "Software", "Valve", "Steam"])
|
||||
if steam is None:
|
||||
return
|
||||
mapping = find_block(tokens[steam + 1:], ["CompatToolMapping"])
|
||||
entry = ['"0"', "{", '"name"', '"%s"' % tool, '"config"', '""', '"priority"', '"75"', "}"]
|
||||
if mapping is None:
|
||||
end = block_end(tokens, steam)
|
||||
tokens[end:end] = ['"CompatToolMapping"', "{"] + entry + ["}"]
|
||||
else:
|
||||
mapping += steam + 1
|
||||
# Repoint every per-app entry the client aimed at a Proton it cannot actually start.
|
||||
for i in range(mapping, block_end(tokens, mapping)):
|
||||
named = tokens[i + 1].strip('"').lower()
|
||||
if (tokens[i] == '"name"' and named.startswith("proton")
|
||||
and named != tool.lower() and named not in keep):
|
||||
tokens[i + 1] = '"%s"' % tool
|
||||
if find_block(tokens[mapping + 1:], ["0"]) is None:
|
||||
tokens[mapping + 1:mapping + 1] = entry
|
||||
# The "0" default only decides how a title is installed, so it settles new downloads and
|
||||
# leaves anything already installed as a Linux build running as one. An entry per installed
|
||||
# app is what the client's own Compatibility checkbox writes, and is what makes it switch.
|
||||
for app in apps:
|
||||
if find_block(tokens[mapping + 1:], [app]) is not None:
|
||||
continue
|
||||
tokens[mapping + 1:mapping + 1] = [
|
||||
'"%s"' % app, "{", '"name"', '"%s"' % tool, '"config"', '""', '"priority"', '"250"', "}"]
|
||||
# Nothing to change is the usual case on the session's beat: the client's own file is left alone.
|
||||
text = serialize(tokens)
|
||||
if text != serialize(tokenize(original)):
|
||||
write_changed(config_path, text)
|
||||
|
||||
|
||||
def depot_build(depot):
|
||||
"""The build number a depot's version file starts with; 0 when there is none."""
|
||||
try:
|
||||
with open(os.path.join(depot, "version"), encoding="utf-8", errors="replace") as f:
|
||||
first = f.read().split(None, 1)
|
||||
except OSError:
|
||||
return 0
|
||||
return int(first[0]) if first and first[0].isdigit() else 0
|
||||
|
||||
|
||||
def find_source(steam_root):
|
||||
"""The newest ARM64 Proton depot the client has downloaded (the one the launcher runs), or None."""
|
||||
# bin-arm64 is what makes it the native build rather than the x86_64 one.
|
||||
found = [os.path.join(root, "steamapps", "common", name)
|
||||
for root in (steam_root, "/mnt/droiddeck-sd") for name in SOURCES
|
||||
if os.path.isdir(os.path.join(root, "steamapps", "common", name, "files", "bin-arm64"))]
|
||||
return max(found, key=depot_build) if found else None
|
||||
|
||||
|
||||
def build_tool(tool_dir):
|
||||
"""Our own manifests and the launcher. The depot is found at launch time, not here."""
|
||||
if os.path.islink(tool_dir):
|
||||
os.unlink(tool_dir)
|
||||
elif os.path.isdir(tool_dir) and set(os.listdir(tool_dir)) - set(OWN_FILES):
|
||||
# Earlier versions mirrored the depot in here as symlinks; start clean. A directory holding
|
||||
# only our own files is kept, and each file rewritten only when it changed.
|
||||
shutil.rmtree(tool_dir)
|
||||
os.makedirs(tool_dir, exist_ok=True)
|
||||
write_changed(os.path.join(tool_dir, "toolmanifest.vdf"), TOOL_MANIFEST_VDF)
|
||||
write_changed(os.path.join(tool_dir, "compatibilitytool.vdf"), COMPAT_TOOL_VDF % TOOL)
|
||||
write_changed(os.path.join(tool_dir, LAUNCHER), LAUNCHER_SH, 0o755)
|
||||
|
||||
|
||||
def main():
|
||||
steam_root = sys.argv[1]
|
||||
tools = os.path.join(steam_root, "compatibilitytools.d")
|
||||
os.makedirs(tools, exist_ok=True)
|
||||
build_tool(os.path.join(tools, TOOL))
|
||||
extras = adopt_extras(tools)
|
||||
for name, directory in sorted(extras.items()):
|
||||
print("bannerlator-steam-compat: adopted %s as %s" % (directory, name))
|
||||
depot = find_source(steam_root)
|
||||
print("bannerlator-steam-compat: registered %s (%s)" % (
|
||||
TOOL, "depot %s present" % os.path.basename(depot) if depot else
|
||||
"no ARM64 Proton depot yet; the session asks the client to fetch it"))
|
||||
config = os.path.join(steam_root, "config", "config.vdf")
|
||||
if os.path.isfile(config):
|
||||
apps = installed_apps(steam_root)
|
||||
register_default(config, apps, protect=extras)
|
||||
print("bannerlator-steam-compat: default and %d installed title(s) set to %s" % (len(apps), TOOL))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+122
@@ -0,0 +1,122 @@
|
||||
#!/bin/bash
|
||||
# An AppImage imported from the front end (AppImageManager), extracted once at import into
|
||||
# /opt/appimages/user/<id>/app
|
||||
# and started from there: proot has no FUSE to mount the image, and extracting it at every
|
||||
# start (APPIMAGE_EXTRACT_AND_RUN) would cost the whole image in /tmp each time.
|
||||
# droiddeck-appimage-run /opt/appimages/user/<id> [args...]
|
||||
set -u
|
||||
dir=${1:?usage: droiddeck-appimage-run <imported AppImage directory> [args...]}
|
||||
shift
|
||||
export APPDIR=$dir/app
|
||||
# APPIMAGE is left unset on purpose: with it an app believes it runs from an image file and offers
|
||||
# to add itself to the menu (DuckStation) or update the file in place - DroidDeck already does the
|
||||
# one, and there is no image file for the other.
|
||||
unset APPIMAGE
|
||||
export ARGV0=$(cat "$dir/name" 2>/dev/null || basename "$dir")
|
||||
if [ ! -x "$APPDIR/AppRun" ]; then
|
||||
echo "droiddeck-appimage-run: $APPDIR/AppRun is missing; import the AppImage again" >&2
|
||||
exit 127
|
||||
fi
|
||||
# Browsers sandbox their own children with namespaces and a setuid helper, neither of which proot
|
||||
# can give them (the Flatpak sandboxes get the same; see BwrapSpawner): Firefox and its forks (Zen,
|
||||
# LibreWolf) by these switches, Electron and Chromium builds by --no-sandbox. Chromium on Wayland
|
||||
# also asks the render node for a DRM version KGSL cannot give, so with an X server up it stays on
|
||||
# X11, which it picks from the session type.
|
||||
export MOZ_DISABLE_CONTENT_SANDBOX=1 MOZ_DISABLE_GMP_SANDBOX=1 MOZ_DISABLE_RDD_SANDBOX=1
|
||||
export MOZ_DISABLE_SOCKET_PROCESS_SANDBOX=1 MOZ_DISABLE_UTILITY_SANDBOX=1
|
||||
# sharun images start the app through their own ld.so, patched not to read /etc/ld.so.preload, and
|
||||
# drop LD_PRELOAD unless allowed: without this the app never gets the session's pads.
|
||||
if [ -s /etc/ld.so.preload ]; then
|
||||
preload=$(tr -s '\n' ':' < /etc/ld.so.preload)
|
||||
export LD_PRELOAD="${preload%:}${LD_PRELOAD:+:$LD_PRELOAD}" SHARUN_ALLOW_LD_PRELOAD=1
|
||||
fi
|
||||
flags=()
|
||||
if [ -e "$APPDIR/chrome-sandbox" ] || compgen -G "$APPDIR/*/chrome-sandbox" >/dev/null; then
|
||||
flags+=(--no-sandbox)
|
||||
if [ -n "${DISPLAY:-}" ]; then
|
||||
export XDG_SESSION_TYPE=x11
|
||||
unset WAYLAND_DISPLAY
|
||||
flags+=(--ozone-platform=x11)
|
||||
fi
|
||||
fi
|
||||
qt=$(cat "$dir/qt" 2>/dev/null)
|
||||
case $qt in wayland|xcb) ;; *) qt=auto ;; esac
|
||||
wayland=${GAMESCOPE_WAYLAND_DISPLAY:-${WAYLAND_DISPLAY:-}}
|
||||
if [ "$qt" = auto ] && [ -n "$wayland" ]; then
|
||||
bundled=$(find "$APPDIR" -maxdepth 6 \( -name 'libQt6Quick.so.6*' -o -name libvulkan.so.1 -o -name 'libqwayland*.so' \) -printf '%f\n' 2>/dev/null)
|
||||
if grep -q '^libQt6Quick\.so\.6' <<<"$bundled"; then
|
||||
if grep -q '^libqwayland' <<<"$bundled" \
|
||||
&& { grep -qx libvulkan.so.1 <<<"$bundled" || grep -qs QVulkanInstance "$APPDIR"/usr/bin/* "$APPDIR"/bin/*; }; then
|
||||
qt=wayland
|
||||
else
|
||||
echo "== appimage: Qt Quick without Vulkan or Qt's Wayland plugin stays on X11 ($(tr '\n' ' ' <<<"$bundled"))"
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
if [ "$qt" = wayland ] && [ -n "$wayland" ]; then
|
||||
export QT_QPA_PLATFORM='wayland;xcb' WAYLAND_DISPLAY=$wayland SDL_VIDEODRIVER=wayland XDG_SESSION_TYPE=wayland
|
||||
[ "$wayland" = "${GAMESCOPE_WAYLAND_DISPLAY:-}" ] && export QT_WAYLAND_DISABLE_WINDOWDECORATION=1 DISABLE_GAMESCOPE_WSI=1
|
||||
elif [ "$qt" = xcb ] && [ -n "${DISPLAY:-}" ]; then
|
||||
export QT_QPA_PLATFORM=xcb
|
||||
fi
|
||||
fex=$(cat "$dir/fex" 2>/dev/null)
|
||||
case $fex in on|off) ;; *) fex=auto ;; esac
|
||||
run=("$APPDIR/AppRun")
|
||||
if [ -x /usr/local/bin/droiddeck-fex ]; then
|
||||
case $fex:$(cat "$dir/arch" 2>/dev/null) in
|
||||
auto:x86_64|auto:i386) run=(/usr/local/bin/droiddeck-fex run --mode on -- "$APPDIR/AppRun") ;;
|
||||
auto:arm64) ;;
|
||||
*) run=(/usr/local/bin/droiddeck-fex run --mode "$fex" --for "$APPDIR" -- "$APPDIR/AppRun") ;;
|
||||
esac
|
||||
fi
|
||||
echo "== appimage $ARGV0 ($APPDIR) ${flags[*]} FEX $fex Qt $qt${QT_QPA_PLATFORM:+ ($QT_QPA_PLATFORM)}"
|
||||
cd "$APPDIR" || exit 1
|
||||
started=$(mktemp "${TMPDIR:-/tmp}/droiddeck-appimage.XXXXXX")
|
||||
# Apps expect a session bus; Electron's main process traps (SIGTRAP) on an address it cannot
|
||||
# parse. A run mode has none, so one is started for the app, as for Flatpak apps.
|
||||
case ${DBUS_SESSION_BUS_ADDRESS:-} in
|
||||
unix:*) "${run[@]}" "${flags[@]}" "$@" ;;
|
||||
*) unset DBUS_SESSION_BUS_ADDRESS
|
||||
if command -v dbus-run-session >/dev/null 2>&1; then
|
||||
dbus-run-session -- "${run[@]}" "${flags[@]}" "$@"
|
||||
else
|
||||
"${run[@]}" "${flags[@]}" "$@"
|
||||
fi ;;
|
||||
esac
|
||||
rc=$?
|
||||
if [ "$rc" -gt 128 ]; then
|
||||
echo "== appimage $ARGV0: ended by signal $((rc - 128)) ($(kill -l $((rc - 128)) 2>/dev/null))"
|
||||
else
|
||||
echo "== appimage $ARGV0: exited with status $rc"
|
||||
fi
|
||||
if [ "$rc" -ne 0 ] && [ -n "$started" ]; then
|
||||
find "${HOME:-/root}/.local/share" "${HOME:-/root}/.config" "${HOME:-/root}/.cache" -maxdepth 4 -type f \
|
||||
\( -iname '*.log' -o -iname '*log*.txt' \) -newer "$started" -size -64M 2>/dev/null | head -n 3 |
|
||||
while IFS= read -r log; do
|
||||
echo "== appimage $ARGV0: end of $log"
|
||||
tail -n 40 "$log" | LC_ALL=C tr -cd '\11\12\40-\176' | cut -c1-400
|
||||
done
|
||||
fi
|
||||
rm -f "$started"
|
||||
# The program a session was started for may hand over to another process and exit: Electron apps
|
||||
# relaunch themselves (Obsidian on its first start), launchers fork their real program. The
|
||||
# session ends with this script, and takes the rest with it - so it waits while anything running
|
||||
# from the image is still up.
|
||||
image_running() {
|
||||
local p exe arg cwd
|
||||
for p in /proc/[0-9]*; do
|
||||
exe=$(readlink "$p/exe" 2>/dev/null) || continue
|
||||
case $exe in "$APPDIR"/*) return 0 ;; esac
|
||||
case $exe in
|
||||
*/FEX|*/FEXInterpreter)
|
||||
arg=$(tr '\0' '\n' < "$p/cmdline" 2>/dev/null | sed -n 2p)
|
||||
cwd=$(readlink "$p/cwd" 2>/dev/null)
|
||||
case $arg in "$APPDIR"/*) return 0 ;; esac
|
||||
case $cwd in "$APPDIR"|"$APPDIR"/*) return 0 ;; esac
|
||||
;;
|
||||
esac
|
||||
done
|
||||
return 1
|
||||
}
|
||||
while image_running; do sleep 2; done
|
||||
exit $rc
|
||||
File renamed without changes.
File renamed without changes.
+3
-3
@@ -4,7 +4,7 @@
|
||||
# the app - so an entry of ours exists only for a game the client wrote none for. Plus two links in
|
||||
# the home folder to the game files. Run at every desktop start; stale entries go.
|
||||
#
|
||||
# bannerlator-desktop-games [steam root]
|
||||
# droiddeck-desktop-games [steam root]
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
@@ -90,7 +90,7 @@ def write_entries():
|
||||
safe = name.replace("\n", " ").strip() or str(appid)
|
||||
body = (
|
||||
"[Desktop Entry]\nType=Application\nName=%s\nComment=Steam game %d - opens in Steam under gamescope\n"
|
||||
"Exec=/usr/local/bin/bannerlator-steam-launch desktop %d\nIcon=%s\nTerminal=false\n"
|
||||
"Exec=/usr/local/bin/droiddeck-steam-launch desktop %d\nIcon=%s\nTerminal=false\n"
|
||||
"Categories=Game;\nX-DroidDeck-AppId=%d\n" % (safe, appid, appid, icon_for(appid), appid)
|
||||
)
|
||||
path = os.path.join(APPS_DIR, "%s%d.desktop" % (PREFIX, appid))
|
||||
@@ -123,7 +123,7 @@ def link_libraries():
|
||||
def main():
|
||||
wanted = write_entries()
|
||||
link_libraries()
|
||||
print("bannerlator-desktop-games: %d entr%s of ours, %d the client's" % (
|
||||
print("droiddeck-desktop-games: %d entr%s of ours, %d the client's" % (
|
||||
len(wanted), "y" if len(wanted) == 1 else "ies", len(client_entries())))
|
||||
|
||||
|
||||
@@ -364,11 +364,21 @@ def load_packs(root):
|
||||
return packs
|
||||
|
||||
|
||||
def line_epoch(line):
|
||||
fields = (line or "").split()
|
||||
try:
|
||||
return int(fields[0]) if fields else 0
|
||||
except ValueError:
|
||||
return 0
|
||||
|
||||
|
||||
def match_kind(pack, measured):
|
||||
if pack.get("revoked") or pack.get("ignored") or measured["builtin"]:
|
||||
return None
|
||||
stock = pack["stock"]
|
||||
if stock[NTDLL] == measured["ntdll"] and stock[WINESERVER] == measured["wineserver"]:
|
||||
if pack.get("version") != measured["token"] and line_epoch(pack.get("version_line")) > line_epoch(measured["version_line"]) > 0:
|
||||
return None
|
||||
return "exact"
|
||||
if (pack.get("source_match") is True and measured["token"] and pack.get("version") == measured["token"]
|
||||
and pack.get("exports") == measured["exports"]):
|
||||
@@ -383,7 +393,7 @@ def find_pack(packs, measured):
|
||||
kind = match_kind(pack, measured)
|
||||
if kind is None:
|
||||
continue
|
||||
key = (kind == "exact", pack["rev"], pack["id"])
|
||||
key = (kind == "exact", bool(measured["token"]) and pack.get("version") == measured["token"], pack["rev"], pack["id"])
|
||||
if best_key is None or key > best_key:
|
||||
best, best_key = pack, key
|
||||
return best
|
||||
@@ -789,6 +799,18 @@ def keep_live(root, command, env, tool):
|
||||
return None
|
||||
if not os.path.isfile(kept_command) or not server_running(prefix):
|
||||
return None
|
||||
kept_pack = row["env"].get("BL_SYNC_PACK")
|
||||
if isinstance(kept_pack, str) and kept_pack and command[1:2] == ["waitforexitandrun"]:
|
||||
try:
|
||||
cache = HashCache(root)
|
||||
try:
|
||||
pack = find_pack(load_packs(root), measure(tool, cache))
|
||||
finally:
|
||||
cache.save()
|
||||
except (OSError, ValueError):
|
||||
pack = {"id": kept_pack}
|
||||
if pack is None or pack["id"] != kept_pack:
|
||||
return None
|
||||
command, env = list(command), dict(env)
|
||||
command[0] = kept_command
|
||||
for name in LIVE_KEYS:
|
||||
|
||||
+659
@@ -0,0 +1,659 @@
|
||||
#!/usr/bin/python3
|
||||
import contextlib
|
||||
import fcntl
|
||||
import filecmp
|
||||
import gzip
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import runpy
|
||||
import shutil
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
HOME = os.environ.get("HOME") or "/root"
|
||||
STEAM_ROOT = os.path.join(HOME, ".local", "share", "Steam")
|
||||
LIBRARIES = ("/mnt/droiddeck", "/mnt/droiddeck-sd")
|
||||
STATE = os.path.join(HOME, ".local", "share", "droiddeck-fex")
|
||||
CONFIG_DIR = os.path.join(STATE, "config")
|
||||
DATA_DIR = os.path.join(STATE, "data")
|
||||
CACHE_DIR = os.path.join(HOME, ".cache", "droiddeck-fex")
|
||||
STATUS_FILE = os.path.join(STATE, "status.json")
|
||||
WANTED = os.path.join(HOME, ".config", "droiddeck", "fex-wanted")
|
||||
GAME_ENVIRONMENT = os.path.join(HOME, ".config", "droiddeck", "game-environment.json")
|
||||
BIN_DIR = os.path.dirname(os.path.abspath(__file__))
|
||||
PRELOADS = "/usr/local/lib/droiddeck-fex"
|
||||
URUNTIME = "/usr/local/lib/droiddeck/uruntime"
|
||||
HOST_PRELOAD = "/etc/ld.so.preload"
|
||||
FEX_APPID = "3127680"
|
||||
SNIPER_APPID = "1628350"
|
||||
INSTALL_DIRS = {FEX_APPID: "FEX-Emu", SNIPER_APPID: "SteamLinuxRuntime_sniper"}
|
||||
MARKER = ".droiddeck-fex"
|
||||
LAYOUT = 1
|
||||
GUEST_LIBDIRS = (("x86_64", "lib/x86_64-linux-gnu"), ("i386", "lib/i386-linux-gnu"))
|
||||
PRELOAD_NAMES = ("libblsession.so", "libfakeinput.so")
|
||||
FAULT_REPORT = "libfaultreport.so"
|
||||
FAULT_REPORT_GUEST = "/usr/lib/x86_64-linux-gnu/droiddeck/" + FAULT_REPORT
|
||||
THUNK_AUDIT = "libthunkaudit.so"
|
||||
THUNK_AUDIT_GUEST = "/usr/lib/x86_64-linux-gnu/droiddeck/" + THUNK_AUDIT
|
||||
VULKAN_PIN = "libvulkan-thunk.so"
|
||||
VULKAN_THUNK = "libvulkan-guest.so"
|
||||
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}
|
||||
X86 = {3: "i386", 62: "x86_64"}
|
||||
ARM = {40: "arm", 183: "arm64"}
|
||||
SCAN_DEPTH = 4
|
||||
SCAN_LIMIT = 4000
|
||||
MODES = ("auto", "on", "off")
|
||||
STEAM_VERBS = ("run", "waitforexitandrun")
|
||||
ESCAPE = re.compile(rb"\\([0-7]{3})")
|
||||
|
||||
|
||||
def say(message):
|
||||
print("droiddeck-fex: %s" % message, file=sys.stderr, flush=True)
|
||||
|
||||
|
||||
def read_text(path):
|
||||
try:
|
||||
with open(path, encoding="utf-8", errors="replace") as f:
|
||||
return f.read()
|
||||
except OSError:
|
||||
return None
|
||||
|
||||
|
||||
def write_if_changed(path, data, mode=0o644):
|
||||
if isinstance(data, str):
|
||||
data = data.encode("utf-8")
|
||||
try:
|
||||
with open(path, "rb") as f:
|
||||
if f.read() == data:
|
||||
return False
|
||||
except OSError:
|
||||
pass
|
||||
os.makedirs(os.path.dirname(path), exist_ok=True)
|
||||
tmp = "%s.%d.tmp" % (path, os.getpid())
|
||||
with open(tmp, "wb") as f:
|
||||
f.write(data)
|
||||
os.chmod(tmp, mode)
|
||||
os.replace(tmp, path)
|
||||
return True
|
||||
|
||||
|
||||
def copy_if_changed(source, target):
|
||||
if os.path.isfile(target) and filecmp.cmp(source, target, shallow=False):
|
||||
return False
|
||||
os.makedirs(os.path.dirname(target), exist_ok=True)
|
||||
tmp = "%s.%d.tmp" % (target, os.getpid())
|
||||
shutil.copyfile(source, tmp)
|
||||
os.chmod(tmp, 0o755)
|
||||
os.replace(tmp, target)
|
||||
return True
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def locked():
|
||||
os.makedirs(STATE, exist_ok=True)
|
||||
with open(os.path.join(STATE, "lock"), "w") as handle:
|
||||
fcntl.flock(handle, fcntl.LOCK_EX)
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
fcntl.flock(handle, fcntl.LOCK_UN)
|
||||
|
||||
|
||||
def libraries():
|
||||
roots = [STEAM_ROOT]
|
||||
text = read_text(os.path.join(STEAM_ROOT, "steamapps", "libraryfolders.vdf")) or ""
|
||||
roots += [path.replace("\\\\", "\\") for path in re.findall(r'"path"\s+"((?:[^"\\]|\\.)*)"', text)]
|
||||
roots += LIBRARIES
|
||||
seen, found = set(), []
|
||||
for root in roots:
|
||||
real = os.path.realpath(root)
|
||||
if real not in seen and os.path.isdir(os.path.join(root, "steamapps")):
|
||||
seen.add(real)
|
||||
found.append(root)
|
||||
return found
|
||||
|
||||
|
||||
def app_dir(appid):
|
||||
for library in libraries():
|
||||
steamapps = os.path.join(library, "steamapps")
|
||||
match = re.search(r'"installdir"\s+"([^"]+)"', read_text(os.path.join(steamapps, "appmanifest_%s.acf" % appid)) or "")
|
||||
for name in filter(None, (match.group(1) if match else None, INSTALL_DIRS.get(appid))):
|
||||
path = os.path.join(steamapps, "common", name)
|
||||
if os.path.isdir(path):
|
||||
return path
|
||||
return None
|
||||
|
||||
|
||||
def first_dir(prefix, candidates):
|
||||
for candidate in candidates:
|
||||
path = os.path.join(prefix, candidate)
|
||||
if os.path.isdir(path):
|
||||
return path
|
||||
return None
|
||||
|
||||
|
||||
def fex_install():
|
||||
prefixes = []
|
||||
tool = app_dir(FEX_APPID)
|
||||
if tool:
|
||||
prefixes += [(os.path.join(tool, sub), True) for sub in ("usr", "", "files/usr", "files")]
|
||||
prefixes.append(("/usr", False))
|
||||
for prefix, portable in prefixes:
|
||||
binary = next((os.path.join(prefix, "bin", name) for name in ("FEX", "FEXInterpreter")
|
||||
if os.access(os.path.join(prefix, "bin", name), os.X_OK)), None)
|
||||
if not binary:
|
||||
continue
|
||||
server = os.path.join(prefix, "bin", "FEXServer")
|
||||
thunks_db = os.path.join(prefix, "share", "fex-emu", "ThunksDB.json")
|
||||
return {
|
||||
"bin": binary,
|
||||
"server": server if os.access(server, os.X_OK) else shutil.which("FEXServer"),
|
||||
"portable": portable,
|
||||
"host_thunks": first_dir(prefix, ("lib/aarch64-linux-gnu/fex-emu/HostThunks", "lib/fex-emu/HostThunks", "lib64/fex-emu/HostThunks")),
|
||||
"guest_thunks": first_dir(prefix, ("share/fex-emu/GuestThunks",)),
|
||||
"thunks_db": thunks_db if os.path.isfile(thunks_db) else None,
|
||||
}
|
||||
return None
|
||||
|
||||
|
||||
def platform_version(path):
|
||||
return tuple(int(part) for part in re.findall(r"\d+", os.path.basename(path)))
|
||||
|
||||
|
||||
def runtime_platform():
|
||||
runtime = app_dir(SNIPER_APPID)
|
||||
if not runtime:
|
||||
return None
|
||||
try:
|
||||
entries = os.listdir(runtime)
|
||||
except OSError:
|
||||
return None
|
||||
platforms = [os.path.join(runtime, entry) for entry in entries if entry.startswith("sniper_platform_")]
|
||||
platforms = [path for path in platforms if os.path.isdir(os.path.join(path, "files"))
|
||||
and os.path.isfile(os.path.join(path, "usr-mtree.txt.gz"))]
|
||||
return max(platforms, key=platform_version, default=None)
|
||||
|
||||
|
||||
def unescape(raw):
|
||||
return ESCAPE.sub(lambda match: bytes([int(match.group(1), 8)]), raw)
|
||||
|
||||
|
||||
def in_root(root, link, target):
|
||||
if not target.startswith(b"/"):
|
||||
return target
|
||||
relative = target.lstrip(b"/")
|
||||
if relative == b"usr" or relative.startswith(b"usr/"):
|
||||
relative = relative[4:]
|
||||
return os.path.relpath(os.path.join(root, relative), os.path.dirname(link))
|
||||
|
||||
|
||||
def materialize(platform):
|
||||
mtree = os.path.join(platform, "usr-mtree.txt.gz")
|
||||
info = os.stat(mtree)
|
||||
stamp = "%d %d %d\n" % (LAYOUT, info.st_size, info.st_mtime_ns)
|
||||
root = os.fsencode(os.path.join(platform, "files"))
|
||||
marker = os.path.join(os.fsdecode(root), MARKER)
|
||||
if read_text(marker) == stamp:
|
||||
return False
|
||||
links = []
|
||||
with gzip.open(mtree, "rb") as source:
|
||||
for line in source:
|
||||
parts = line.split()
|
||||
if not parts or parts[0].startswith(b"#"):
|
||||
continue
|
||||
fields = dict(part.split(b"=", 1) for part in parts[1:] if b"=" in part)
|
||||
relative = os.path.normpath(unescape(parts[0]))
|
||||
if os.path.isabs(relative) or relative == b".." or relative.startswith(b"../"):
|
||||
continue
|
||||
dest = os.path.join(root, relative)
|
||||
kind = fields.get(b"type")
|
||||
if kind == b"dir":
|
||||
os.makedirs(dest, exist_ok=True)
|
||||
elif kind == b"file" and b"contents" in fields:
|
||||
blob = os.path.join(root, os.path.normpath(unescape(fields[b"contents"])))
|
||||
links.append((dest, os.path.relpath(blob, os.path.dirname(dest))))
|
||||
elif kind == b"link" and b"link" in fields:
|
||||
links.append((dest, in_root(root, dest, unescape(fields[b"link"]))))
|
||||
for dest, target in links:
|
||||
if os.path.islink(dest):
|
||||
if os.readlink(dest) == target:
|
||||
continue
|
||||
os.unlink(dest)
|
||||
elif os.path.lexists(dest):
|
||||
continue
|
||||
os.makedirs(os.path.dirname(dest), exist_ok=True)
|
||||
os.symlink(target, dest)
|
||||
usr = os.path.join(root, b"usr")
|
||||
if not os.path.lexists(usr):
|
||||
os.symlink(b".", usr)
|
||||
write_if_changed(marker, stamp)
|
||||
return True
|
||||
|
||||
|
||||
def host_preloads():
|
||||
listed = read_text(HOST_PRELOAD) or ""
|
||||
return [name for name in PRELOAD_NAMES if name in listed]
|
||||
|
||||
|
||||
def install_preloads(root):
|
||||
shipped = set()
|
||||
for arch, libdir in GUEST_LIBDIRS:
|
||||
for name in PRELOAD_NAMES:
|
||||
source = os.path.join(PRELOADS, arch, name)
|
||||
if os.path.isfile(source):
|
||||
copy_if_changed(source, os.path.join(root, libdir, "droiddeck", name))
|
||||
shipped.add(name)
|
||||
for name in (FAULT_REPORT, THUNK_AUDIT, VULKAN_PIN):
|
||||
source = os.path.join(PRELOADS, "x86_64", name)
|
||||
if os.path.isfile(source):
|
||||
copy_if_changed(source, os.path.join(root, "lib/x86_64-linux-gnu/droiddeck", name))
|
||||
wanted = [name for name in host_preloads() if name in shipped]
|
||||
write_if_changed(os.path.join(root, "etc", "ld.so.preload"), "".join("/usr/$LIB/droiddeck/%s\n" % name for name in wanted))
|
||||
|
||||
|
||||
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")
|
||||
write_if_changed(os.path.join(CONFIG_DIR, "Config.json"), json.dumps(config, indent=2) + "\n")
|
||||
|
||||
|
||||
def link_steam_sdk():
|
||||
for sdk, candidates in (("sdk64", ("linux64", "ubuntu12_64")), ("sdk32", ("linux32", "ubuntu12_32"))):
|
||||
link = os.path.join(HOME, ".steam", sdk)
|
||||
if os.path.lexists(link):
|
||||
continue
|
||||
want = "x86_64" if sdk == "sdk64" else "i386"
|
||||
for candidate in candidates:
|
||||
directory = os.path.join(STEAM_ROOT, candidate)
|
||||
if elf_arch(os.path.join(directory, "steamclient.so")) == want:
|
||||
os.makedirs(os.path.dirname(link), exist_ok=True)
|
||||
os.symlink(directory, link)
|
||||
break
|
||||
|
||||
|
||||
def steam_running():
|
||||
for pid in os.listdir("/proc"):
|
||||
if not pid.isdigit():
|
||||
continue
|
||||
try:
|
||||
with open("/proc/%s/cmdline" % pid, "rb") as f:
|
||||
first = f.read().split(b"\0", 1)[0]
|
||||
except OSError:
|
||||
continue
|
||||
if first.endswith(b"steamrtarm64/steam"):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def request_install():
|
||||
os.makedirs(os.path.dirname(WANTED), exist_ok=True)
|
||||
write_if_changed(WANTED, "1\n")
|
||||
if not steam_running():
|
||||
return []
|
||||
try:
|
||||
compat = runpy.run_path(os.path.join(BIN_DIR, "steam-compatibility"))
|
||||
return compat["request_fex"](STEAM_ROOT, set())
|
||||
except Exception as error:
|
||||
say("could not ask the client to install FEX (%s)" % error)
|
||||
return []
|
||||
|
||||
|
||||
def describe(fex, platform):
|
||||
return {
|
||||
"fex": fex["bin"] if fex else None,
|
||||
"server": fex["server"] if fex else None,
|
||||
"thunks": bool(fex and fex["host_thunks"] and fex["guest_thunks"] and fex["thunks_db"]),
|
||||
"runtime": platform,
|
||||
"steamclient64": os.path.realpath(os.path.join(HOME, ".steam", "sdk64", "steamclient.so"))
|
||||
if elf_arch(os.path.join(HOME, ".steam", "sdk64", "steamclient.so")) == "x86_64" else None,
|
||||
"ready": bool(fex and fex["server"] and platform),
|
||||
}
|
||||
|
||||
|
||||
def prepare():
|
||||
with locked():
|
||||
fex = fex_install()
|
||||
platform = runtime_platform()
|
||||
status = describe(fex, platform)
|
||||
if not status["ready"]:
|
||||
missing = []
|
||||
tool = app_dir(FEX_APPID)
|
||||
if not fex and tool:
|
||||
say("FEX is installed at %s but holds no FEX or FEXInterpreter in usr/bin, bin or files; it has: %s"
|
||||
% (tool, ", ".join(sorted(os.listdir(tool))[:20])))
|
||||
if not fex:
|
||||
missing.append("FEX (Steam app %s)" % FEX_APPID)
|
||||
elif not fex["server"]:
|
||||
missing.append("FEXServer beside %s" % fex["bin"])
|
||||
if not platform:
|
||||
missing.append("Steam Linux Runtime 3.0 (sniper, Steam app %s)" % SNIPER_APPID)
|
||||
requested = request_install()
|
||||
say("x86 Linux programs need %s; %s" % (" and ".join(missing),
|
||||
"the Steam client was asked to install it" if requested else "open Steam once and it is installed for you"))
|
||||
write_if_changed(STATUS_FILE, json.dumps(status, indent=2) + "\n")
|
||||
return None
|
||||
root = os.path.join(platform, "files")
|
||||
if materialize(platform):
|
||||
say("prepared %s as the x86 runtime" % os.path.basename(platform))
|
||||
install_preloads(root)
|
||||
write_config(fex, root)
|
||||
fex["rootfs"] = root
|
||||
try:
|
||||
link_steam_sdk()
|
||||
except OSError:
|
||||
pass
|
||||
status = describe(fex, platform)
|
||||
write_if_changed(STATUS_FILE, json.dumps(status, indent=2) + "\n")
|
||||
with contextlib.suppress(OSError):
|
||||
os.unlink(WANTED)
|
||||
return fex
|
||||
|
||||
|
||||
def elf_arch(path):
|
||||
try:
|
||||
with open(path, "rb") as f:
|
||||
head = f.read(20)
|
||||
except OSError:
|
||||
return None
|
||||
if len(head) < 20 or head[:4] != b"\x7fELF":
|
||||
return None
|
||||
machine = struct.unpack_from("<H" if head[5] == 1 else ">H", head, 18)[0]
|
||||
return X86.get(machine) or ARM.get(machine) or "other"
|
||||
|
||||
|
||||
def scan(folder):
|
||||
counts = {"x86": 0, "arm": 0}
|
||||
seen = 0
|
||||
base = folder.rstrip("/").count("/")
|
||||
for directory, dirs, files in os.walk(folder):
|
||||
if directory.count("/") - base >= SCAN_DEPTH:
|
||||
dirs[:] = []
|
||||
for name in files:
|
||||
seen += 1
|
||||
if seen > SCAN_LIMIT:
|
||||
return counts
|
||||
arch = elf_arch(os.path.join(directory, name))
|
||||
if arch in X86.values():
|
||||
counts["x86"] += 1
|
||||
elif arch in ARM.values():
|
||||
counts["arm"] += 1
|
||||
return counts
|
||||
|
||||
|
||||
def needs_fex(path):
|
||||
arch = elf_arch(path)
|
||||
if arch is not None:
|
||||
return arch in X86.values()
|
||||
folder = path if os.path.isdir(path) else os.path.dirname(os.path.abspath(path))
|
||||
counts = scan(folder)
|
||||
return counts["x86"] > 0 and counts["arm"] == 0
|
||||
|
||||
|
||||
def is_arm(path):
|
||||
return elf_arch(path) in ARM.values()
|
||||
|
||||
|
||||
def split_paths(value):
|
||||
return [part for part in re.split(r"[:\s]+", value or "") if part]
|
||||
|
||||
|
||||
def guest_environment(fex, env):
|
||||
result = dict(env)
|
||||
for directory in (CONFIG_DIR, DATA_DIR, CACHE_DIR):
|
||||
os.makedirs(directory, exist_ok=True)
|
||||
result["FEX_APP_CONFIG_LOCATION"] = CONFIG_DIR + "/"
|
||||
result["FEX_APP_DATA_LOCATION"] = DATA_DIR + "/"
|
||||
result["FEX_APP_CACHE_LOCATION"] = CACHE_DIR + "/"
|
||||
result.setdefault("FEX_SILENTLOG", "0")
|
||||
result.setdefault("FEX_OUTPUTLOG", "stderr")
|
||||
if fex["portable"]:
|
||||
result["FEX_PORTABLE"] = "1"
|
||||
else:
|
||||
result.pop("FEX_PORTABLE", None)
|
||||
for name in ("FEX_ROOTFS", "FEX_THUNKHOSTLIBS", "FEX_THUNKGUESTLIBS"):
|
||||
if name in result and not os.path.exists(result[name]):
|
||||
result.pop(name)
|
||||
if fex.get("rootfs"):
|
||||
result["FEX_ROOTFS"] = fex["rootfs"]
|
||||
if fex.get("rootfs") and fex.get("host_thunks") and fex.get("guest_thunks") and fex.get("thunks_db"):
|
||||
result["FEX_THUNKHOSTLIBS"] = fex["host_thunks"]
|
||||
result["FEX_THUNKGUESTLIBS"] = fex["guest_thunks"]
|
||||
result["FEX_THUNKCONFIG"] = os.path.join(CONFIG_DIR, "ThunksConfig.json")
|
||||
preload = [part for part in split_paths(result.get("LD_PRELOAD")) if os.path.exists(part) and not is_arm(part)]
|
||||
library_path = [part for part in (result.get("LD_LIBRARY_PATH") or "").split(":")
|
||||
if part and "steamrtarm64" not in part and "aarch64" not in part]
|
||||
for name, parts in (("LD_PRELOAD", preload), ("LD_LIBRARY_PATH", library_path)):
|
||||
if parts:
|
||||
result[name] = ":".join(parts)
|
||||
else:
|
||||
result.pop(name, None)
|
||||
return result
|
||||
|
||||
|
||||
def version_names(path):
|
||||
try:
|
||||
with open(path, "rb") as f:
|
||||
return set(VERSION_NAME.findall(f.read()))
|
||||
except OSError:
|
||||
return set()
|
||||
|
||||
|
||||
def bundled_libraries(folder):
|
||||
wanted = [name for name, _ in RUNTIME_LIBRARIES]
|
||||
found = {}
|
||||
seen = 0
|
||||
base = folder.rstrip("/").count("/")
|
||||
for directory, dirs, files in os.walk(folder):
|
||||
seen += len(files)
|
||||
if seen > SCAN_LIMIT:
|
||||
break
|
||||
if directory.count("/") - base >= BUNDLE_DEPTH:
|
||||
dirs[:] = []
|
||||
for name in wanted:
|
||||
if name in files and name not in found:
|
||||
found[name] = os.path.join(directory, name)
|
||||
return found
|
||||
|
||||
|
||||
def vulkan_thunk_loads(fex, folder):
|
||||
needed = version_names(os.path.join(fex["guest_thunks"], VULKAN_THUNK))
|
||||
if not needed:
|
||||
return False
|
||||
found = bundled_libraries(folder)
|
||||
for name, prefix in RUNTIME_LIBRARIES:
|
||||
library = found.get(name) or os.path.join(fex["rootfs"], "lib/x86_64-linux-gnu", name)
|
||||
if not {version for version in needed if version.startswith(prefix)} <= version_names(library):
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def resolve(program, env):
|
||||
if "/" in program:
|
||||
return os.path.abspath(program)
|
||||
return shutil.which(program, path=env.get("PATH")) or program
|
||||
|
||||
|
||||
def launch(command, env, mode, decide=None):
|
||||
program = resolve(command[0], env)
|
||||
use = mode == "on" or (mode == "auto" and needs_fex(decide or program))
|
||||
if not use:
|
||||
return os.execvpe(command[0], command, env)
|
||||
fex = prepare()
|
||||
if fex is None:
|
||||
return 126
|
||||
guest = guest_environment(fex, env)
|
||||
x86_64 = elf_arch(program) != "i386"
|
||||
if os.path.isfile(os.path.join(PRELOADS, "x86_64", FAULT_REPORT)) and x86_64:
|
||||
guest["LD_PRELOAD"] = ":".join([FAULT_REPORT_GUEST] + split_paths(guest.get("LD_PRELOAD")))
|
||||
thunks = "on" if "FEX_THUNKCONFIG" in guest else "off"
|
||||
folder = decide if decide and os.path.isdir(decide) else os.path.dirname(program)
|
||||
if thunks == "on" and x86_64 and all(os.path.isfile(os.path.join(PRELOADS, "x86_64", name)) for name in (THUNK_AUDIT, VULKAN_PIN)) \
|
||||
and vulkan_thunk_loads(fex, folder):
|
||||
guest["LD_AUDIT"] = ":".join([THUNK_AUDIT_GUEST] + split_paths(guest.get("LD_AUDIT")))
|
||||
thunks = "on, its own Vulkan loader too"
|
||||
say("running %s with %s (runtime %s, thunks %s)" % (program, fex["bin"], guest.get("FEX_ROOTFS", "none"), thunks))
|
||||
return os.execve(fex["bin"], [fex["bin"], program] + command[1:], guest)
|
||||
|
||||
|
||||
def game_environment(env):
|
||||
try:
|
||||
game_env = runpy.run_path(os.path.join(BIN_DIR, "droiddeck-game-env"))
|
||||
app = game_env["game_id"](env) or env.get("SteamAppId") or env.get("SteamGameId")
|
||||
if not app:
|
||||
return env
|
||||
with open(GAME_ENVIRONMENT, encoding="utf-8") as source:
|
||||
return game_env["apply_config"](env, json.load(source), str(app))
|
||||
except FileNotFoundError:
|
||||
return env
|
||||
except Exception as error:
|
||||
say("game settings were not applied (%s)" % error)
|
||||
return env
|
||||
|
||||
|
||||
def appimage_offset(path):
|
||||
with open(path, "rb") as f:
|
||||
head = f.read(64)
|
||||
if head[:4] != b"\x7fELF":
|
||||
raise ValueError("not an ELF file")
|
||||
order = "<" if head[5] == 1 else ">"
|
||||
if head[4] == 2:
|
||||
shoff, = struct.unpack_from(order + "Q", head, 0x28)
|
||||
shentsize, shnum = struct.unpack_from(order + "HH", head, 0x3A)
|
||||
else:
|
||||
shoff, = struct.unpack_from(order + "I", head, 0x20)
|
||||
shentsize, shnum = struct.unpack_from(order + "HH", head, 0x2E)
|
||||
return shoff + shentsize * shnum
|
||||
|
||||
|
||||
def clear_extracted():
|
||||
for stale in ("squashfs-root", "AppDir"):
|
||||
if os.path.islink(stale):
|
||||
os.unlink(stale)
|
||||
else:
|
||||
shutil.rmtree(stale, ignore_errors=True)
|
||||
|
||||
|
||||
def extracted():
|
||||
if os.path.isdir("AppDir") and not os.path.lexists("squashfs-root"):
|
||||
os.symlink("AppDir", "squashfs-root")
|
||||
return os.path.isdir("squashfs-root")
|
||||
|
||||
|
||||
def want_fex():
|
||||
with locked():
|
||||
status = describe(fex_install(), runtime_platform())
|
||||
if not status["ready"]:
|
||||
request_install()
|
||||
write_if_changed(STATUS_FILE, json.dumps(status, indent=2) + "\n")
|
||||
|
||||
|
||||
def extract(image):
|
||||
image = os.path.abspath(image)
|
||||
clear_extracted()
|
||||
x86 = elf_arch(image) in X86.values()
|
||||
if os.access(URUNTIME, os.X_OK):
|
||||
status = subprocess.call([URUNTIME, "--appimage-extract"], stdout=subprocess.DEVNULL,
|
||||
env=dict(os.environ, TARGET_APPIMAGE=image))
|
||||
if status == 0 and extracted():
|
||||
if x86:
|
||||
want_fex()
|
||||
return 0
|
||||
say("uruntime could not extract it (status %d)" % status)
|
||||
clear_extracted()
|
||||
fex = prepare() if x86 else None
|
||||
if fex is not None:
|
||||
status = subprocess.call([fex["bin"], image, "--appimage-extract"], stdout=subprocess.DEVNULL,
|
||||
env=guest_environment(fex, dict(os.environ)))
|
||||
if status == 0 and extracted():
|
||||
return 0
|
||||
say("the image's own runtime could not extract it under FEX (status %d)" % status)
|
||||
unsquashfs = shutil.which("unsquashfs")
|
||||
if unsquashfs:
|
||||
clear_extracted()
|
||||
status = subprocess.call([unsquashfs, "-q", "-n", "-o", str(appimage_offset(image)), "-d", "squashfs-root", image],
|
||||
stdout=subprocess.DEVNULL)
|
||||
if status == 0:
|
||||
if x86:
|
||||
want_fex()
|
||||
return 0
|
||||
say("unsquashfs could not extract it (status %d)" % status)
|
||||
elif fex is None:
|
||||
say("this AppImage could not be unpacked here: no AppImage runtime for ARM64, no FEX yet and no unsquashfs")
|
||||
return 1
|
||||
|
||||
|
||||
def parse_run(args):
|
||||
mode, decide = os.environ.get("DROIDDECK_FEX", "auto"), None
|
||||
while args and args[0].startswith("--"):
|
||||
option = args.pop(0)
|
||||
if option == "--":
|
||||
break
|
||||
if option in ("--mode", "--for") and args:
|
||||
value = args.pop(0)
|
||||
if option == "--mode":
|
||||
mode = value
|
||||
else:
|
||||
decide = value
|
||||
else:
|
||||
raise ValueError("unknown option %s" % option)
|
||||
if mode not in MODES:
|
||||
raise ValueError("--mode takes %s" % ", ".join(MODES))
|
||||
return mode, decide, args
|
||||
|
||||
|
||||
def main(argv):
|
||||
if not argv:
|
||||
say("usage: droiddeck-fex steam VERB CMD... | run [--mode auto|on|off] [--for PATH] [--] CMD... | needs PATH | extract IMAGE | prepare | status")
|
||||
return 2
|
||||
action, args = argv[0], list(argv[1:])
|
||||
if action == "steam":
|
||||
if not args:
|
||||
return 2
|
||||
verb, command = args[0], args[1:]
|
||||
if verb not in STEAM_VERBS:
|
||||
return 0
|
||||
if not command:
|
||||
return 2
|
||||
return launch(command, game_environment(dict(os.environ)), os.environ.get("DROIDDECK_FEX", "auto"))
|
||||
if action == "run":
|
||||
try:
|
||||
mode, decide, command = parse_run(args)
|
||||
except ValueError as error:
|
||||
say(str(error))
|
||||
return 2
|
||||
if not command:
|
||||
return 2
|
||||
return launch(command, dict(os.environ), mode, decide)
|
||||
if action == "needs":
|
||||
if len(args) != 1:
|
||||
return 2
|
||||
needed = needs_fex(args[0])
|
||||
print("fex" if needed else "native")
|
||||
return 0 if needed else 1
|
||||
if action == "extract":
|
||||
if len(args) != 1:
|
||||
return 2
|
||||
return extract(args[0])
|
||||
if action == "prepare":
|
||||
return 0 if prepare() else 1
|
||||
if action == "status":
|
||||
with locked():
|
||||
status = describe(fex_install(), runtime_platform())
|
||||
write_if_changed(STATUS_FILE, json.dumps(status, indent=2) + "\n")
|
||||
print(json.dumps(status, indent=2))
|
||||
return 0 if status["ready"] else 1
|
||||
say("unknown action %s" % action)
|
||||
return 2
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main(sys.argv[1:]))
|
||||
+7
-7
@@ -3,10 +3,10 @@
|
||||
# reaches the front end as numbers rather than a terminal's redrawn bar. Per-user installation,
|
||||
# Flathub as the remote, this device's architecture.
|
||||
#
|
||||
# bannerlator-flatpak install <app-id> the app and whatever runtimes it needs
|
||||
# bannerlator-flatpak uninstall <app-id> the app, then runtimes nothing uses any more
|
||||
# bannerlator-flatpak update [<app-id>] one app, or everything with an update
|
||||
# bannerlator-flatpak updates what has one (a "updates" line)
|
||||
# droiddeck-flatpak install <app-id> the app and whatever runtimes it needs
|
||||
# droiddeck-flatpak uninstall <app-id> the app, then runtimes nothing uses any more
|
||||
# droiddeck-flatpak update [<app-id>] one app, or everything with an update
|
||||
# droiddeck-flatpak updates what has one (a "updates" line)
|
||||
#
|
||||
# Lines: {"e":"op","i":1,"n":3,"kind":"install","ref":"..."} as each step starts,
|
||||
# {"e":"progress","i":1,"n":3,"percent":45,"status":"..."} while it runs,
|
||||
@@ -15,7 +15,7 @@ import json
|
||||
import os
|
||||
import sys
|
||||
|
||||
os.environ.setdefault("FLATPAK_BWRAP", "/usr/local/bin/bannerlator-bwrap")
|
||||
os.environ.setdefault("FLATPAK_BWRAP", "/usr/local/bin/droiddeck-bwrap")
|
||||
|
||||
import gi # noqa: E402
|
||||
|
||||
@@ -216,7 +216,7 @@ def updates():
|
||||
|
||||
def main():
|
||||
if len(sys.argv) < 2:
|
||||
sys.stderr.write(__doc__ or "usage: bannerlator-flatpak install|uninstall|update|updates [app-id]\n")
|
||||
sys.stderr.write(__doc__ or "usage: droiddeck-flatpak install|uninstall|update|updates [app-id]\n")
|
||||
return 2
|
||||
cmd, args = sys.argv[1], sys.argv[2:]
|
||||
if cmd in ("install", "update"):
|
||||
@@ -229,7 +229,7 @@ def main():
|
||||
return update(args[0] if args else None)
|
||||
if cmd == "updates":
|
||||
return updates()
|
||||
sys.stderr.write("usage: bannerlator-flatpak install|uninstall|update|updates [app-id]\n")
|
||||
sys.stderr.write("usage: droiddeck-flatpak install|uninstall|update|updates [app-id]\n")
|
||||
return 2
|
||||
|
||||
|
||||
+2
-2
@@ -1,8 +1,8 @@
|
||||
#!/bin/bash
|
||||
# A Flatpak app from the front end, full screen under gamescope like an emulator:
|
||||
# bannerlator-flatpak-run <app-id> [args...]
|
||||
# droiddeck-flatpak-run <app-id> [args...]
|
||||
set -u
|
||||
export FLATPAK_BWRAP=/usr/local/bin/bannerlator-bwrap
|
||||
export FLATPAK_BWRAP=/usr/local/bin/droiddeck-bwrap
|
||||
case ":${XDG_DATA_DIRS:-}:" in
|
||||
*"/flatpak/exports/share:"*) ;;
|
||||
*) export XDG_DATA_DIRS=$HOME/.local/share/flatpak/exports/share:${XDG_DATA_DIRS:-/usr/local/share:/usr/share} ;;
|
||||
+3
-3
@@ -9,7 +9,7 @@
|
||||
# few packages Flatpak needs on top of this image, verifying each against the Arch Linux ARM
|
||||
# keyring, and they are unpacked here without hooks or scripts, like the desktop package itself.
|
||||
#
|
||||
# bannerlator-flatpak-setup install or repair; prints "== STEP ..." milestones
|
||||
# droiddeck-flatpak-setup install or repair; prints "== STEP ..." milestones
|
||||
set -u
|
||||
export LANG=C.UTF-8
|
||||
step() { echo "== STEP $*"; }
|
||||
@@ -17,7 +17,7 @@ fail() { echo "== FAIL $*"; exit 1; }
|
||||
|
||||
# Flatpak, the libraries it and appstream add to this image, and the D-Bus proxy flatpak run puts
|
||||
# between an app and the session bus. bubblewrap is not among them: Android gives an app no user
|
||||
# namespaces, and bannerlator-bwrap stands in for it (FLATPAK_BWRAP).
|
||||
# namespaces, and droiddeck-bwrap stands in for it (FLATPAK_BWRAP).
|
||||
PACKAGES="flatpak ostree appstream libxmlb libmalcontent libfyaml accountsservice composefs xdg-dbus-proxy"
|
||||
# Libraries Flatpak and the store's helper also need, which the Desktop package brings but a
|
||||
# runtime without it may lack: each is fetched only when its file is not already there.
|
||||
@@ -97,7 +97,7 @@ python3 -c 'import gi; gi.require_version("Flatpak", "1.0"); from gi.repository
|
||||
|| fail "the store helper cannot load libflatpak from Python"
|
||||
|
||||
step "Adding Flathub"
|
||||
export FLATPAK_BWRAP=/usr/local/bin/bannerlator-bwrap
|
||||
export FLATPAK_BWRAP=/usr/local/bin/droiddeck-bwrap
|
||||
# Flathub's descriptor - its URL and the key its commits are signed with - is carried here rather
|
||||
# than fetched: adding the remote then needs no network, and a descriptor that did not arrive
|
||||
# whole cannot be what failed. Flathub's own copy: https://dl.flathub.org/repo/flathub.flatpakrepo
|
||||
+78
-9
@@ -2,9 +2,13 @@
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import runpy
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
SYNC_KEYS = ("BL_SYNC_FALLBACK", "BL_FSYNC_FIRST", "BL_SYNC_MIN_NOFILE", "PROTON_NO_ESYNC", "PROTON_NO_FSYNC", "PROTON_NO_NTSYNC", "WINEESYNC")
|
||||
PACK_KEYS = ("WINESERVER", "BL_SYNC_PACK", "WINEESYNC", "PROTON_NO_ESYNC", "PROTON_NO_FSYNC")
|
||||
|
||||
|
||||
def game_id(env):
|
||||
prefix = env.get("STEAM_COMPAT_DATA_PATH", "").rstrip("/")
|
||||
@@ -144,26 +148,91 @@ def apply_config(env, config, app_id, fixes=None):
|
||||
return result
|
||||
|
||||
|
||||
def sync_config(config, app_id):
|
||||
games = config.get("games", {})
|
||||
return {
|
||||
"version": config.get("version"),
|
||||
"shared": {name: value for name, value in config.get("shared", {}).items() if name in SYNC_KEYS},
|
||||
"games": {app_id: {name: value for name, value in games.get(app_id, {}).items() if name in SYNC_KEYS}},
|
||||
}
|
||||
|
||||
|
||||
def load_sync():
|
||||
try:
|
||||
return runpy.run_path(str(Path(__file__).resolve().parent / "droiddeck-esync"))
|
||||
except Exception as error:
|
||||
print("droiddeck-game-env: sync selection failed (%s); stock launch" % error, file=sys.stderr)
|
||||
return None
|
||||
|
||||
|
||||
def select_sync(command, env, sync=None):
|
||||
try:
|
||||
sync = sync if sync is not None else load_sync()
|
||||
if sync is None:
|
||||
return command, env
|
||||
chosen, chosen_env = sync["select"](command, env)
|
||||
if chosen and all(isinstance(value, str) for value in chosen) and isinstance(chosen_env, dict):
|
||||
return list(chosen), dict(chosen_env)
|
||||
except Exception as error:
|
||||
print("droiddeck-game-env: sync selection failed (%s); stock launch" % error, file=sys.stderr)
|
||||
return command, env
|
||||
|
||||
|
||||
def record_stock(sync, command, env):
|
||||
try:
|
||||
if sync is not None and "record" in sync:
|
||||
sync["record"](command, env)
|
||||
except Exception as error:
|
||||
print("droiddeck-game-env: stock launch not recorded (%s)" % error, file=sys.stderr)
|
||||
|
||||
|
||||
def without_pack(chosen_env, env):
|
||||
result = dict(chosen_env)
|
||||
for name in PACK_KEYS:
|
||||
if name in env:
|
||||
result[name] = env[name]
|
||||
else:
|
||||
result.pop(name, None)
|
||||
return result
|
||||
|
||||
|
||||
def main():
|
||||
command = sys.argv[1:]
|
||||
if not command:
|
||||
return 2
|
||||
env = os.environ.copy()
|
||||
app_id = game_id(env)
|
||||
if len(command) > 1 and command[1] == "waitforexitandrun" and app_id:
|
||||
fixes, extra, notes = engine_fixes(command[2], command[3:]) if len(command) > 2 else ({}, [], [])
|
||||
for note in notes:
|
||||
print("bannerlator-game-env: " + note, file=sys.stderr)
|
||||
command += extra
|
||||
if app_id:
|
||||
waiting = len(command) > 1 and command[1] == "waitforexitandrun"
|
||||
fixes = {}
|
||||
if waiting:
|
||||
fixes, extra, notes = engine_fixes(command[2], command[3:]) if len(command) > 2 else ({}, [], [])
|
||||
for note in notes:
|
||||
print("droiddeck-game-env: " + note, file=sys.stderr)
|
||||
command += extra
|
||||
path = Path.home() / ".config/droiddeck/game-environment.json"
|
||||
try:
|
||||
with path.open(encoding="utf-8") as source:
|
||||
env = apply_config(env, json.load(source), app_id, fixes)
|
||||
config = json.load(source)
|
||||
if waiting:
|
||||
env = apply_config(env, config, app_id, fixes)
|
||||
else:
|
||||
env = apply_config(env, sync_config(config, app_id), app_id)
|
||||
except FileNotFoundError:
|
||||
env = apply_config(env, {"version": 1}, app_id, fixes)
|
||||
if waiting:
|
||||
env = apply_config(env, {"version": 1}, app_id, fixes)
|
||||
except (OSError, ValueError, TypeError, AttributeError):
|
||||
print("bannerlator-game-env: invalid configuration; using inherited environment", file=sys.stderr)
|
||||
os.execvpe(command[0], command, env)
|
||||
print("droiddeck-game-env: invalid configuration; using inherited environment", file=sys.stderr)
|
||||
sync = load_sync()
|
||||
launch, launch_env = select_sync(command, env, sync)
|
||||
if launch[0] != command[0]:
|
||||
try:
|
||||
os.execvpe(launch[0], launch, launch_env)
|
||||
except OSError as error:
|
||||
print("droiddeck-game-env: %s could not start (%s); stock launch" % (launch[0], error), file=sys.stderr)
|
||||
launch, launch_env = command, without_pack(launch_env, env)
|
||||
record_stock(sync, launch, launch_env)
|
||||
os.execvpe(launch[0], launch, launch_env)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
+1
-1
@@ -126,7 +126,7 @@ class LoginManager:
|
||||
def main():
|
||||
directory = os.environ.get("BL_LAUNCH_DIR")
|
||||
if not directory or not Path(directory).is_dir():
|
||||
sys.exit("bannerlator-login1: no DroidDeck session directory")
|
||||
sys.exit("droiddeck-login1: no DroidDeck session directory")
|
||||
ready = Path(directory) / "steam-sleep-ready"
|
||||
ready.unlink(missing_ok=True)
|
||||
loop = GLib.MainLoop()
|
||||
+2
-2
@@ -27,8 +27,8 @@ IP6 = ROOT + "/IP6Config/1"
|
||||
AP = ROOT + "/AccessPoint/1"
|
||||
PROFILE = SETTINGS + "/1"
|
||||
UUID = "b1d0c8e4-57f0-4c0e-9d60-77696e6e6174"
|
||||
SNAPSHOT = Path("/etc/bannerlator-network.json")
|
||||
SCAN_REQUEST = Path("/etc/bannerlator-wifi-scan-request")
|
||||
SNAPSHOT = Path("/etc/droiddeck-network.json")
|
||||
SCAN_REQUEST = Path("/etc/droiddeck-wifi-scan-request")
|
||||
OBJECT_MANAGER = "org.freedesktop.DBus.ObjectManager"
|
||||
PROPERTIES = "org.freedesktop.DBus.Properties"
|
||||
|
||||
+22
-22
@@ -17,7 +17,7 @@ def seed(path, text, what, done="Player 1 on the controller"):
|
||||
with open(path + ".tmp", "w", encoding="utf-8") as f:
|
||||
f.write(text)
|
||||
os.replace(path + ".tmp", path)
|
||||
print(f"bannerlator-pad-defaults: {what}: {done} ({path})")
|
||||
print(f"droiddeck-pad-defaults: {what}: {done} ({path})")
|
||||
return True
|
||||
|
||||
|
||||
@@ -97,7 +97,7 @@ def rpcs3_shader_mode():
|
||||
with open(cfg + ".tmp", "w", encoding="utf-8") as f:
|
||||
f.write(text)
|
||||
os.replace(cfg + ".tmp", cfg)
|
||||
print(f"bannerlator-pad-defaults: RPCS3: shader mode {RPCS3_RECOMPILER} ({cfg})")
|
||||
print(f"droiddeck-pad-defaults: RPCS3: shader mode {RPCS3_RECOMPILER} ({cfg})")
|
||||
open(marker, "w").close()
|
||||
|
||||
|
||||
@@ -144,7 +144,7 @@ def patch_ini_section(path, section, body, what, needle="SDL-", require=None, do
|
||||
with open(path + ".tmp", "w", encoding="utf-8") as f:
|
||||
f.write("\n".join(lines) + "\n")
|
||||
os.replace(path + ".tmp", path)
|
||||
print(f"bannerlator-pad-defaults: {what}: {done} ({path})")
|
||||
print(f"droiddeck-pad-defaults: {what}: {done} ({path})")
|
||||
|
||||
|
||||
# DuckStation: SDL-<n>/<name>, axes signed (src/util/sdl_input_source.cpp); Pad1 keys from
|
||||
@@ -285,12 +285,12 @@ def duckstation():
|
||||
# One set up by an earlier build still has its first-time setup pending, in the way of a game.
|
||||
if ini_get(ini, "Main", "SetupWizardIncomplete") == "true":
|
||||
ini_set(ini, "Main", "SetupWizardIncomplete", "false")
|
||||
print("bannerlator-pad-defaults: DuckStation: first-time setup already done here")
|
||||
print("droiddeck-pad-defaults: DuckStation: first-time setup already done here")
|
||||
# Keeping the screen awake goes through org.freedesktop.ScreenSaver, which nothing in the session
|
||||
# provides (Android decides when the screen sleeps): DuckStation only warns it failed, every game.
|
||||
if (ini_get(ini, "Main", "InhibitScreensaver") or "true") == "true":
|
||||
ini_set(ini, "Main", "InhibitScreensaver", "false")
|
||||
print("bannerlator-pad-defaults: DuckStation: no screensaver inhibit (no such service here)")
|
||||
print("droiddeck-pad-defaults: DuckStation: no screensaver inhibit (no such service here)")
|
||||
# Once, for a DuckStation set up before this: its own empty BIOS folder moves to the ROMs folder,
|
||||
# and Automatic becomes Vulkan. A later choice in DuckStation's settings is kept.
|
||||
marker = os.path.join(os.path.dirname(ini), ".droiddeck-setup")
|
||||
@@ -300,10 +300,10 @@ def duckstation():
|
||||
own = current if os.path.isabs(current) else os.path.join(os.path.dirname(ini), current)
|
||||
if not (os.path.isdir(own) and os.listdir(own)):
|
||||
ini_set(ini, "BIOS", "SearchDirectory", bios_folder(ps1))
|
||||
print(f"bannerlator-pad-defaults: DuckStation: BIOS from {bios_folder(ps1)}")
|
||||
print(f"droiddeck-pad-defaults: DuckStation: BIOS from {bios_folder(ps1)}")
|
||||
if (ini_get(ini, "GPU", "Renderer") or "Automatic") == "Automatic":
|
||||
ini_set(ini, "GPU", "Renderer", "Vulkan")
|
||||
print("bannerlator-pad-defaults: DuckStation: renderer Vulkan")
|
||||
print("droiddeck-pad-defaults: DuckStation: renderer Vulkan")
|
||||
open(marker, "w").close()
|
||||
|
||||
|
||||
@@ -451,7 +451,7 @@ def armsx2():
|
||||
src = os.path.join(old, sub)
|
||||
if os.path.isdir(src):
|
||||
shutil.copytree(src, os.path.join(root, sub), dirs_exist_ok=True)
|
||||
print(f"bannerlator-pad-defaults: ARMSX2: settings and memory cards copied from PCSX2 ({root})")
|
||||
print(f"droiddeck-pad-defaults: ARMSX2: settings and memory cards copied from PCSX2 ({root})")
|
||||
elif not os.path.isfile(ini):
|
||||
# A new player: everything ARMSX2's first-time setup asks is answered here - the BIOS
|
||||
# folder in the ROMs folder, the ps2 folder as its game list, the controller on Player 1 -
|
||||
@@ -482,7 +482,7 @@ def armsx2():
|
||||
require="SettingsVersion", done="games listed from the ROMs folder")
|
||||
if ini_get(ini, "UI", "SetupWizardIncomplete") == "true":
|
||||
ini_set(ini, "UI", "SetupWizardIncomplete", "false")
|
||||
print("bannerlator-pad-defaults: ARMSX2: first-time setup already done here")
|
||||
print("droiddeck-pad-defaults: ARMSX2: first-time setup already done here")
|
||||
armsx2_bios(ini)
|
||||
|
||||
|
||||
@@ -507,7 +507,7 @@ def armsx2_bios(ini):
|
||||
us = [f for f in dumps if any(t in f.lower() for t in ("usa", "(us)", "(us,", "ntsc-u"))]
|
||||
pick = (us or dumps)[0]
|
||||
ini_set(ini, "Filenames", "BIOS", pick)
|
||||
print(f"bannerlator-pad-defaults: ARMSX2: BIOS {pick}")
|
||||
print(f"droiddeck-pad-defaults: ARMSX2: BIOS {pick}")
|
||||
|
||||
|
||||
# Dolphin (PC) has no controller menu, so the guide button is its Toggle Fullscreen hotkey: out of full
|
||||
@@ -596,7 +596,7 @@ def dolphin_data():
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=600)
|
||||
src = os.path.join(work, "squashfs-root/usr/share/dolphin-emu")
|
||||
if not os.path.isfile(os.path.join(src, "Sys/GC/font_western.bin")):
|
||||
print("bannerlator-pad-defaults: Dolphin: could not unpack its data from the AppImage")
|
||||
print("droiddeck-pad-defaults: Dolphin: could not unpack its data from the AppImage")
|
||||
return
|
||||
new = DOLPHIN_DATA + ".new"
|
||||
shutil.rmtree(new, ignore_errors=True)
|
||||
@@ -605,9 +605,9 @@ def dolphin_data():
|
||||
f.write(stamp)
|
||||
shutil.rmtree(DOLPHIN_DATA, ignore_errors=True)
|
||||
os.rename(new, DOLPHIN_DATA)
|
||||
print("bannerlator-pad-defaults: Dolphin: its data (fonts, per-game fixes) in " + DOLPHIN_DATA)
|
||||
print("droiddeck-pad-defaults: Dolphin: its data (fonts, per-game fixes) in " + DOLPHIN_DATA)
|
||||
except (OSError, subprocess.SubprocessError) as e:
|
||||
print("bannerlator-pad-defaults: Dolphin: unpacking its data failed: %s" % e)
|
||||
print("droiddeck-pad-defaults: Dolphin: unpacking its data failed: %s" % e)
|
||||
finally:
|
||||
shutil.rmtree(work, ignore_errors=True)
|
||||
|
||||
@@ -622,7 +622,7 @@ def dolphin():
|
||||
wii_pad = os.path.join(d, "WiimoteNew.ini")
|
||||
if ini_get(wii_pad, "Wiimote1", "Buttons/Home") == "`Guide`":
|
||||
ini_set(wii_pad, "Wiimote1", "Buttons/Home", "`Shoulder R`")
|
||||
print("bannerlator-pad-defaults: Dolphin (Wii): Home on the right shoulder button (guide = Dolphin's window)")
|
||||
print("droiddeck-pad-defaults: Dolphin (Wii): Home on the right shoulder button (guide = Dolphin's window)")
|
||||
hotkeys = os.path.join(d, "Hotkeys.ini")
|
||||
if not os.path.isfile(hotkeys):
|
||||
seed(hotkeys, DOLPHIN_HOTKEYS, "Dolphin", "the guide button shows Dolphin's window (Toggle Fullscreen)")
|
||||
@@ -631,7 +631,7 @@ def dolphin():
|
||||
if current is not None and DOLPHIN_GUIDE not in current:
|
||||
ini_set(hotkeys, "Hotkeys", "General/Toggle Fullscreen",
|
||||
(current + " | " if current else "") + DOLPHIN_GUIDE)
|
||||
print("bannerlator-pad-defaults: Dolphin: the guide button shows Dolphin's window (Toggle Fullscreen)")
|
||||
print("droiddeck-pad-defaults: Dolphin: the guide button shows Dolphin's window (Toggle Fullscreen)")
|
||||
# Games from the ROMs folder's gamecube and wii folders, subfolders included; Vulkan; no
|
||||
# NKit warning (it will not let a game start until a box is ticked - games run either way,
|
||||
# the warning is about loading times, netplay and save states); no statistics question.
|
||||
@@ -647,7 +647,7 @@ def dolphin():
|
||||
"[Core]\nGFXBackend = Vulkan\n"
|
||||
"[General]\nISOPaths = 2\nISOPath0 = %s\nISOPath1 = %s\nRecursiveISOPaths = True\n"
|
||||
"[Interface]\nSkipNKitWarning = True\n" % (gc, wii))
|
||||
print("bannerlator-pad-defaults: Dolphin: first-time setup (Vulkan, games from %s and %s)" % (gc, wii))
|
||||
print("droiddeck-pad-defaults: Dolphin: first-time setup (Vulkan, games from %s and %s)" % (gc, wii))
|
||||
return
|
||||
try:
|
||||
count = int(ini_get(ini, "General", "ISOPaths") or "0")
|
||||
@@ -679,7 +679,7 @@ def dolphin():
|
||||
ini_set(ini, "General", "RecursiveISOPaths", "True")
|
||||
changed.append("subfolders")
|
||||
if changed:
|
||||
print("bannerlator-pad-defaults: Dolphin: games from " + ", ".join(changed))
|
||||
print("droiddeck-pad-defaults: Dolphin: games from " + ", ".join(changed))
|
||||
# Once, for a Dolphin set up before this: Vulkan unless it was chosen already, and the NKit box.
|
||||
marker = os.path.join(d, ".droiddeck-setup")
|
||||
if os.path.exists(marker):
|
||||
@@ -691,7 +691,7 @@ def dolphin():
|
||||
ini_set(ini, "Analytics", "Enabled", "False")
|
||||
ini_set(ini, "Analytics", "PermissionAsked", "True")
|
||||
open(marker, "w").close()
|
||||
print("bannerlator-pad-defaults: Dolphin: Vulkan, no NKit warning")
|
||||
print("droiddeck-pad-defaults: Dolphin: Vulkan, no NKit warning")
|
||||
|
||||
|
||||
# Cemu: an SDLController profile for the GamePad. The uuid is "<index>_<SDL GUID>" and SDL's GUID
|
||||
@@ -954,7 +954,7 @@ def melonds():
|
||||
with open(path + ".tmp", "w", encoding="utf-8") as f:
|
||||
f.write("\n".join(lines).rstrip("\n") + "\n")
|
||||
os.replace(path + ".tmp", path)
|
||||
print(f"bannerlator-pad-defaults: melonDS: {'; '.join(done)} ({path})")
|
||||
print(f"droiddeck-pad-defaults: melonDS: {'; '.join(done)} ({path})")
|
||||
|
||||
|
||||
# PPSSPP (SDL): its pad defaults leave the shoulders, the right stick and the triggers unbound on
|
||||
@@ -1041,7 +1041,7 @@ def retroarch():
|
||||
with open(cfg + ".tmp", "w", encoding="utf-8") as f:
|
||||
f.write("\n".join(lines) + "\n")
|
||||
os.replace(cfg + ".tmp", cfg)
|
||||
print(f"bannerlator-pad-defaults: RetroArch: joypad driver udev -> sdl2 ({cfg})")
|
||||
print(f"droiddeck-pad-defaults: RetroArch: joypad driver udev -> sdl2 ({cfg})")
|
||||
|
||||
|
||||
# yuzu and its forks: Player 1 in [Controls] of <name>/qt-config.ini, which each writes at its first
|
||||
@@ -1090,11 +1090,11 @@ def switch_emulators():
|
||||
f.write("\n".join(lines) + "\n")
|
||||
os.replace(cfg + ".tmp", cfg)
|
||||
open(marker, "w").close()
|
||||
print(f"bannerlator-pad-defaults: {name}: Player 1 on the controller ({cfg})")
|
||||
print(f"droiddeck-pad-defaults: {name}: Player 1 on the controller ({cfg})")
|
||||
|
||||
|
||||
for step in (rpcs3, duckstation, pcsx2, armsx2, dolphin, cemu, melonds, ppsspp, retroarch, switch_emulators):
|
||||
try:
|
||||
step()
|
||||
except Exception as e:
|
||||
print(f"bannerlator-pad-defaults: {step.__name__}: {e}")
|
||||
print(f"droiddeck-pad-defaults: {step.__name__}: {e}")
|
||||
+21
-20
@@ -1,12 +1,12 @@
|
||||
#!/usr/bin/python3
|
||||
# Installs a third-party Proton build into the client's compatibilitytools.d, so it appears in the
|
||||
# Compatibility dropdown beside Bannerlator Proton (ARM64) and can be picked per game.
|
||||
# Compatibility dropdown beside our own Proton ARM64 and can be picked per game.
|
||||
#
|
||||
# bannerlator-proton-extra <steam root> ge [--tag GE-Proton11-7]
|
||||
# bannerlator-proton-extra <steam root> cachyos [--tag cachyos-11.0-20260703-slr]
|
||||
# bannerlator-proton-extra <steam root> <url of an aarch64 tarball>
|
||||
# bannerlator-proton-extra <steam root> /path/to/an/aarch64/tarball
|
||||
# bannerlator-proton-extra <steam root> --list what is installed now
|
||||
# droiddeck-proton-extra <steam root> ge [--tag GE-Proton11-7]
|
||||
# droiddeck-proton-extra <steam root> cachyos [--tag cachyos-11.0-20260703-slr]
|
||||
# droiddeck-proton-extra <steam root> <url of an aarch64 tarball>
|
||||
# droiddeck-proton-extra <steam root> /path/to/an/aarch64/tarball
|
||||
# droiddeck-proton-extra <steam root> --list what is installed now
|
||||
#
|
||||
# Both projects publish native ARM64 builds - GloriousEggroll as "*-aarch64.tar.gz", CachyOS as
|
||||
# "*-arm64.tar.xz" - and both are ordinary Proton trees: a python entry point beside a files/
|
||||
@@ -16,7 +16,7 @@
|
||||
# What it cannot use is their toolmanifest. Like Valve's ARM64 depot they declare
|
||||
# require_tool_appid, which makes Steam stack pressure-vessel underneath - and pressure-vessel
|
||||
# needs unprivileged user namespaces, which an Android app does not get. Patching that out is
|
||||
# bannerlator-steam-compat's job (adopt_extras); this script only puts the tree in place and then
|
||||
# steam-compatibility's job (adopt_extras); this script only puts the tree in place and then
|
||||
# calls it, so an install is usable without restarting the client.
|
||||
import hashlib
|
||||
import json
|
||||
@@ -36,14 +36,14 @@ SOURCES = {
|
||||
"ge": ("GloriousEggroll/proton-ge-custom", re.compile(r"aarch64\.tar\.(gz|xz)$")),
|
||||
"cachyos": ("CachyOS/proton-cachyos", re.compile(r"arm64\.tar\.(gz|xz)$")),
|
||||
}
|
||||
USER_AGENT = "bannerlator-proton-extra"
|
||||
USER_AGENT = "droiddeck-proton-extra"
|
||||
# Room for the tarball and the tree it unpacks to. GE-Proton's aarch64 build is ~650 MB packed and
|
||||
# unpacks to about three times that; refusing early beats a half-written tool directory.
|
||||
NEED_BYTES = 4 * 1024 * 1024 * 1024
|
||||
|
||||
|
||||
def log(*args):
|
||||
print("bannerlator-proton-extra:", *args, flush=True)
|
||||
print("droiddeck-proton-extra:", *args, flush=True)
|
||||
|
||||
|
||||
def fetch_json(url):
|
||||
@@ -77,7 +77,7 @@ def release_asset(source, tag):
|
||||
sums = [u for n, u in assets.items()
|
||||
if n.startswith(name.split(".tar")[0]) and "sha512" in n]
|
||||
return tag, assets[name], (sums[0] if sums else None)
|
||||
raise SystemExit("bannerlator-proton-extra: %s has no ARM64 asset" % tag)
|
||||
raise SystemExit("droiddeck-proton-extra: %s has no ARM64 asset" % tag)
|
||||
|
||||
|
||||
def download(url, path):
|
||||
@@ -88,7 +88,7 @@ def download(url, path):
|
||||
"curl", "-fL", "--retry", "5", "--retry-delay", "3", "--retry-connrefused",
|
||||
"-C", "-", "-A", USER_AGENT, "-o", path, url])
|
||||
if rc != 0:
|
||||
raise SystemExit("bannerlator-proton-extra: download failed (curl %d)" % rc)
|
||||
raise SystemExit("droiddeck-proton-extra: download failed (curl %d)" % rc)
|
||||
log("downloaded %.0f MB" % (os.path.getsize(path) / 1048576.0))
|
||||
|
||||
|
||||
@@ -109,7 +109,7 @@ def verify(path, sums_url):
|
||||
h.update(chunk)
|
||||
if h.hexdigest() != want:
|
||||
os.unlink(path)
|
||||
raise SystemExit("bannerlator-proton-extra: checksum mismatch; the download was deleted")
|
||||
raise SystemExit("droiddeck-proton-extra: checksum mismatch; the download was deleted")
|
||||
log("checksum ok")
|
||||
|
||||
|
||||
@@ -118,7 +118,7 @@ def extract(tarball, into):
|
||||
log("unpacking (a few minutes; nothing is shown while tar runs)")
|
||||
rc = subprocess.call(["tar", "-xf", tarball, "-C", into])
|
||||
if rc != 0:
|
||||
raise SystemExit("bannerlator-proton-extra: tar failed (%d)" % rc)
|
||||
raise SystemExit("droiddeck-proton-extra: tar failed (%d)" % rc)
|
||||
# A Proton tarball holds one top-level directory. Take whichever entry has the entry point so a
|
||||
# stray ._ file or a nested layout does not decide it.
|
||||
entries = [e for e in sorted(os.listdir(into)) if not e.startswith(".")]
|
||||
@@ -128,7 +128,7 @@ def extract(tarball, into):
|
||||
return path
|
||||
if len(entries) == 1 and os.path.isdir(os.path.join(into, entries[0])):
|
||||
return os.path.join(into, entries[0])
|
||||
raise SystemExit("bannerlator-proton-extra: no Proton tree in the archive")
|
||||
raise SystemExit("droiddeck-proton-extra: no Proton tree in the archive")
|
||||
|
||||
|
||||
def installed(tools):
|
||||
@@ -144,7 +144,7 @@ def installed(tools):
|
||||
def main():
|
||||
argv = sys.argv[1:]
|
||||
if not argv:
|
||||
raise SystemExit(__doc__ or "usage: bannerlator-proton-extra <steam root> ge|cachyos|<url>")
|
||||
raise SystemExit(__doc__ or "usage: droiddeck-proton-extra <steam root> ge|cachyos|<url>")
|
||||
steam_root = argv.pop(0)
|
||||
tools = os.path.join(steam_root, "compatibilitytools.d")
|
||||
os.makedirs(tools, exist_ok=True)
|
||||
@@ -167,7 +167,7 @@ def main():
|
||||
if what in SOURCES:
|
||||
tag, url, sums = release_asset(what, tag) if tag else pick_asset(what)
|
||||
if not url:
|
||||
raise SystemExit("bannerlator-proton-extra: no ARM64 build published for %s" % what)
|
||||
raise SystemExit("droiddeck-proton-extra: no ARM64 build published for %s" % what)
|
||||
log("%s -> %s" % (what, tag))
|
||||
elif what.startswith("http"):
|
||||
url, sums = what, None
|
||||
@@ -176,14 +176,15 @@ def main():
|
||||
log("using %s" % what)
|
||||
else:
|
||||
raise SystemExit(
|
||||
"bannerlator-proton-extra: expected ge, cachyos, a URL or a tarball path, got %r" % what)
|
||||
"droiddeck-proton-extra: expected ge, cachyos, a URL or a tarball path, got %r" % what)
|
||||
|
||||
free = shutil.disk_usage(tools).free
|
||||
if free < NEED_BYTES:
|
||||
raise SystemExit("bannerlator-proton-extra: needs about %d GB free, has %.1f GB" % (
|
||||
raise SystemExit("droiddeck-proton-extra: needs about %d GB free, has %.1f GB" % (
|
||||
NEED_BYTES // (1024 ** 3), free / float(1024 ** 3)))
|
||||
|
||||
staging = os.path.join(tools, ".bannerlator-download")
|
||||
shutil.rmtree(os.path.join(tools, ".bannerlator-download"), ignore_errors=True)
|
||||
staging = os.path.join(tools, ".droiddeck-download")
|
||||
os.makedirs(staging, exist_ok=True)
|
||||
if local:
|
||||
tarball = local
|
||||
@@ -210,7 +211,7 @@ def main():
|
||||
|
||||
# Patches out require_tool_appid and wraps the entry point, which is what makes it launchable
|
||||
# here. Doing it now means the client picks the tool up on its next restart with no extra step.
|
||||
subprocess.call(["bannerlator-steam-compat", steam_root])
|
||||
subprocess.call(["steam-compatibility", steam_root])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
@@ -0,0 +1,51 @@
|
||||
#!/bin/bash
|
||||
# A script added on the Desktop page (UserApps), run from its own folder:
|
||||
# droiddeck-script-run /opt/droiddeck-apps/<id> [args...]
|
||||
set -u
|
||||
dir=${1:?usage: droiddeck-script-run <added app directory> [args...]}
|
||||
shift
|
||||
entry=$(cat "$dir/entry" 2>/dev/null) || { echo "droiddeck-script-run: $dir has no entry" >&2; exit 127; }
|
||||
cd -P "$dir/files" 2>/dev/null || { echo "droiddeck-script-run: $dir/files is missing; add the script again" >&2; exit 127; }
|
||||
folder=$PWD
|
||||
# Shared storage is noexec, so the script is handed to its interpreter rather than executed.
|
||||
first=
|
||||
IFS= read -r first < "$entry"
|
||||
first=${first%$'\r'}
|
||||
interp=(/bin/bash)
|
||||
case $first in '#!'*) read -r -a interp <<< "${first#'#!'}" ;; esac
|
||||
fex=$(cat "$dir/fex" 2>/dev/null)
|
||||
case $fex in on|off) ;; *) fex=auto ;; esac
|
||||
run=("${interp[@]}" "./$entry")
|
||||
if [ -x /usr/local/bin/droiddeck-fex ]; then
|
||||
run=(/usr/local/bin/droiddeck-fex run --mode "$fex" --for "$folder" -- "${interp[@]}" "./$entry")
|
||||
fi
|
||||
echo "== script $entry in $folder (${interp[*]}, FEX $fex)"
|
||||
case ${DBUS_SESSION_BUS_ADDRESS:-} in
|
||||
unix:*) "${run[@]}" "$@" ;;
|
||||
*) unset DBUS_SESSION_BUS_ADDRESS
|
||||
if command -v dbus-run-session >/dev/null 2>&1; then
|
||||
dbus-run-session -- "${run[@]}" "$@"
|
||||
else
|
||||
"${run[@]}" "$@"
|
||||
fi ;;
|
||||
esac
|
||||
rc=$?
|
||||
# A launcher script often starts the game and returns; the session lasts while it runs.
|
||||
running() {
|
||||
local p exe arg cwd
|
||||
for p in /proc/[0-9]*; do
|
||||
exe=$(readlink "$p/exe" 2>/dev/null) || continue
|
||||
case $exe in "$folder"/*) return 0 ;; esac
|
||||
case $exe in
|
||||
*/FEX|*/FEXInterpreter)
|
||||
arg=$(tr '\0' '\n' < "$p/cmdline" 2>/dev/null | sed -n 2p)
|
||||
cwd=$(readlink "$p/cwd" 2>/dev/null)
|
||||
case $arg in "$folder"/*) return 0 ;; esac
|
||||
case $cwd in "$folder"|"$folder"/*) return 0 ;; esac
|
||||
;;
|
||||
esac
|
||||
done
|
||||
return 1
|
||||
}
|
||||
while running; do sleep 2; done
|
||||
exit $rc
|
||||
+5
-1
@@ -81,7 +81,11 @@ for reg in "$steam_root"/steamapps/common/Proton*/files/share/default_pfx*/syste
|
||||
"$steam_root"/steamapps/compatdata/*/pfx/system.reg \
|
||||
/mnt/droiddeck-sd/steamapps/compatdata/*/pfx/system.reg; do
|
||||
[ -f "$reg" ] || continue
|
||||
seeded=$(dirname "$reg")/.bannerlator-redists
|
||||
seeded=$(dirname "$reg")/.droiddeck-redists
|
||||
legacy=$(dirname "$reg")/.bannerlator-redists
|
||||
if [ -f "$legacy" ] && [ ! -f "$seeded" ]; then
|
||||
mv -f "$legacy" "$seeded"
|
||||
fi
|
||||
[ "$(cat "$seeded" 2>/dev/null)" = "$stamp" ] && continue
|
||||
dated=$(mktemp) || continue
|
||||
touch -r "$reg" "$dated"
|
||||
+76
-46
@@ -1,10 +1,10 @@
|
||||
#!/bin/bash
|
||||
# The Linux runtime's session. Bannerlator execs this under proot with the output size and mode;
|
||||
# The Linux runtime's session. DroidDeck execs this under proot with the output size and mode;
|
||||
# the first pass starts gamescope, which execs this script again inside it for the program:
|
||||
# bannerlator-session desktop the file manager
|
||||
# bannerlator-session run <path> a Linux program (AppImage, script or ELF)
|
||||
# bannerlator-session steam [steam-url] the native Steam client
|
||||
# bannerlator-session lxqt the LXQt/labwc desktop (DroidDeck's desktop package)
|
||||
# droiddeck-session desktop the file manager
|
||||
# droiddeck-session run <path> a Linux program (AppImage, script or ELF)
|
||||
# droiddeck-session steam [steam-url] the native Steam client
|
||||
# droiddeck-session lxqt the LXQt/labwc desktop (DroidDeck's desktop package)
|
||||
# BL_WIDTH / BL_HEIGHT size the output, BL_FPS limits it, BL_LOG collects everything said here.
|
||||
set -u
|
||||
export HOME=${HOME:-/root}
|
||||
@@ -22,8 +22,8 @@ if [ -n "${BL_LOG:-}" ] && [ -z "${BL_INSIDE:-}" ]; then
|
||||
# A guest looping on an error writes gigabytes in minutes (an Xwayland proot had lost track of
|
||||
# managed 9 GB of one line in 19 min): the log keeps its first BL_LOG_CAP bytes and the rest is
|
||||
# drained, not refused - a writer that filled it must not die of SIGPIPE.
|
||||
exec > >({ head -c "${BL_LOG_CAP:-268435456}" >>"$BL_LOG"; cat >/dev/null; }) 2>&1
|
||||
echo "== bannerlator-session $(date) mode=$mode $*"
|
||||
exec > >({ dd of="$BL_LOG" oflag=append conv=notrunc iflag=count_bytes count="${BL_LOG_CAP:-268435456}" bs=65536 status=none; cat >/dev/null; }) 2>&1
|
||||
echo "== droiddeck-session $(date) mode=$mode $*"
|
||||
echo "== uid=$(id -u) size=${BL_WIDTH:-?}x${BL_HEIGHT:-?} fps=${BL_FPS:-0} icd=${VK_ICD_FILENAMES:-none}"
|
||||
echo "== gamescope: $(gamescope --version 2>&1 | head -1) at $(command -v gamescope)"
|
||||
echo "== rootfs: $(cat /.version 2>/dev/null || echo unversioned)"
|
||||
@@ -42,6 +42,16 @@ collect_steam_logs() {
|
||||
[ -f "$HOME/.steam/steam/logs/steamwebhelper.log" ] && cp "$HOME/.steam/steam/logs/steamwebhelper.log" "$BL_DEBUG_DIR/steam/" 2>/dev/null
|
||||
# NOT copied, ever: loginusers.vdf, config.vdf and the ssfn* files, which hold the credentials
|
||||
# themselves rather than a mention of them.
|
||||
local sync_store=$HOME/.local/share/droiddeck-esync sync_file
|
||||
if [ -d "$sync_store" ] && mkdir -p "$BL_DEBUG_DIR/droiddeck-esync" 2>/dev/null; then
|
||||
for sync_file in launches.log tools.tsv wanted.tsv prefixes.json; do
|
||||
[ -f "$sync_store/$sync_file" ] && cp "$sync_store/$sync_file" "$BL_DEBUG_DIR/droiddeck-esync/" 2>/dev/null
|
||||
done
|
||||
fi
|
||||
local fex_state=$HOME/.local/share/droiddeck-fex
|
||||
if [ -d "$fex_state" ] && mkdir -p "$BL_DEBUG_DIR/droiddeck-fex" 2>/dev/null; then
|
||||
cp "$fex_state/status.json" "$fex_state/config/Config.json" "$BL_DEBUG_DIR/droiddeck-fex/" 2>/dev/null
|
||||
fi
|
||||
echo "== steam logs copied to $BL_DEBUG_DIR/steam"
|
||||
}
|
||||
# A session that is killed never reaches the copy below, and those are the sessions worth reading.
|
||||
@@ -93,11 +103,11 @@ export XDG_CONFIG_HOME=${XDG_CONFIG_HOME:-$HOME/.config}
|
||||
export XDG_CACHE_HOME=${XDG_CACHE_HOME:-$HOME/.cache}
|
||||
mkdir -p "$XDG_DATA_HOME" "$XDG_CONFIG_HOME" "$XDG_CACHE_HOME"
|
||||
if [ "$mode" = lxqt ] || [ "$mode" = desktop ]; then
|
||||
/usr/local/bin/bannerlator-desktop-bookmarks || true
|
||||
/usr/local/bin/droiddeck-desktop-bookmarks || true
|
||||
fi
|
||||
# Flatpak (the store's apps): its sandboxes through the app instead of bubblewrap, which needs the
|
||||
# user namespaces Android keeps from apps, and its apps' menu entries and icons on the desktop.
|
||||
export FLATPAK_BWRAP=/usr/local/bin/bannerlator-bwrap
|
||||
export FLATPAK_BWRAP=/usr/local/bin/droiddeck-bwrap
|
||||
export XDG_DATA_DIRS=$XDG_DATA_HOME/flatpak/exports/share:${XDG_DATA_DIRS:-/usr/local/share:/usr/share}
|
||||
|
||||
# The cores a program runs on outside Steam (the desktop and everything started from it, a
|
||||
@@ -238,32 +248,41 @@ case $mode in
|
||||
taskset -cp "$cores" $$ >/dev/null 2>&1 || true
|
||||
fi
|
||||
# Player 1 on the controller in an emulator that has no profile of its own yet.
|
||||
python3 /usr/local/bin/bannerlator-pad-defaults 2>&1 || true
|
||||
python3 /usr/local/bin/droiddeck-pad-defaults 2>&1 || true
|
||||
fex=()
|
||||
if [ -x /usr/local/bin/droiddeck-fex ]; then
|
||||
case $(od -An -tu2 -j18 -N2 "$target" 2>/dev/null | tr -d ' ') in
|
||||
3|62) fex=(/usr/local/bin/droiddeck-fex run --mode on --) ;;
|
||||
esac
|
||||
fi
|
||||
case ${target,,} in
|
||||
*.appimage)
|
||||
export APPIMAGE_EXTRACT_AND_RUN=1
|
||||
chmod +x "$target" 2>/dev/null
|
||||
exec "$target" "$@"
|
||||
exec "${fex[@]}" "$target" "$@"
|
||||
;;
|
||||
*.sh)
|
||||
if [ -x /usr/local/bin/droiddeck-fex ]; then
|
||||
exec /usr/local/bin/droiddeck-fex run --for "$target" -- bash "$target" "$@"
|
||||
fi
|
||||
exec bash "$target" "$@"
|
||||
;;
|
||||
*)
|
||||
chmod +x "$target" 2>/dev/null
|
||||
cd "$(dirname "$target")" && exec "$target" "$@"
|
||||
cd "$(dirname "$target")" && exec "${fex[@]}" "$target" "$@"
|
||||
;;
|
||||
esac
|
||||
;;
|
||||
steam)
|
||||
step "checking the Steam client (first run downloads it, ~1-2 min with nothing on screen)"
|
||||
bannerlator-steam-install || exit $?
|
||||
droiddeck-steam-install || exit $?
|
||||
step "Steam client ready"
|
||||
steam_root=$XDG_DATA_HOME/Steam
|
||||
# Register the card library (bound at /mnt/droiddeck-sd) with the client - internal storage is
|
||||
# its main library already - and the ARM64 Proton that lets it launch the Windows ones.
|
||||
# A request left in ~/.bl-proton-extra installs a third-party Proton before the client starts,
|
||||
# so it is in the Compatibility dropdown the first time the user looks. One per line, each the
|
||||
# arguments to bannerlator-proton-extra: "ge", "cachyos", "ge --tag GE-Proton11-7", or a URL.
|
||||
# arguments to droiddeck-proton-extra: "ge", "cachyos", "ge --tag GE-Proton11-7", or a URL.
|
||||
# Hundreds of megabytes each, so it is only ever done on request, and the line is dropped once
|
||||
# it has succeeded - a failed download stays and is retried next session.
|
||||
if [ -s "$HOME/.bl-proton-extra" ]; then
|
||||
@@ -272,7 +291,7 @@ case $mode in
|
||||
while read -r _bl_extra || [ -n "$_bl_extra" ]; do
|
||||
case ${_bl_extra# } in ""|"#"*) continue ;; esac
|
||||
step "installing Proton '$_bl_extra' (large download, several minutes)"
|
||||
if bannerlator-proton-extra "$steam_root" $_bl_extra; then
|
||||
if droiddeck-proton-extra "$steam_root" $_bl_extra; then
|
||||
step "installed Proton '$_bl_extra'"
|
||||
else
|
||||
step "Proton '$_bl_extra' failed; will retry next session"
|
||||
@@ -323,27 +342,27 @@ case $mode in
|
||||
fi
|
||||
|
||||
step "registering the app's game library with Steam"
|
||||
bannerlator-steam-library "$steam_root" || true
|
||||
droiddeck-steam-library "$steam_root" || true
|
||||
step "setting up the ARM64 Proton compatibility tool"
|
||||
bannerlator-steam-compat "$steam_root" || true
|
||||
steam-compatibility "$steam_root" || true
|
||||
if [ -z "${BL_DESKTOP:-}" ] && [ "${BL_STEAM_UI:-}" != desktop ]; then
|
||||
bannerlator-steam-ui-scale "$steam_root" "${BL_WIDTH:-1280}" "${BL_HEIGHT:-720}" || true
|
||||
droiddeck-steam-ui-scale "$steam_root" "${BL_WIDTH:-1280}" "${BL_HEIGHT:-720}" || true
|
||||
fi
|
||||
# The user's own games, as non-Steam shortcuts under that tool; the list is written by the app
|
||||
# each session (empty = the app's earlier entries are removed, the client's own are kept).
|
||||
if [ -n "${BL_ADDED_GAMES:-}" ]; then
|
||||
step "adding the app's own games to the client's library"
|
||||
bannerlator-steam-shortcuts "$steam_root" "$BL_ADDED_GAMES" || true
|
||||
droiddeck-steam-shortcuts "$steam_root" "$BL_ADDED_GAMES" || true
|
||||
fi
|
||||
# Steam runs a game's shared redistributables inside its prefix on first launch; marking
|
||||
# them as already run keeps those x86 installers from starting under emulation at all.
|
||||
bannerlator-seed-redists "$steam_root" || true
|
||||
droiddeck-seed-redists "$steam_root" || true
|
||||
# The compatibility tool runs Valve's arm64 Proton, which the client fetches like any depot.
|
||||
# Asked for on the command line the first time, so a Windows title has it before it is needed.
|
||||
if [ ! -f "$steam_root/steamapps/appmanifest_4427310.acf" ]; then
|
||||
step "asking the client to fetch the ARM64 Proton"
|
||||
set -- "$@" steam://install/4427310
|
||||
# Ported from Bannerlator (bannerlator-session, device-proven 2026-09-22). The client decides
|
||||
# Ported from Bannerlator's session script (device-proven 2026-09-22). The client decides
|
||||
# a title's compatibility tool when the title is installed and keeps that decision for the
|
||||
# rest of its run, and the tool is set up before the client comes up. So once the depot has
|
||||
# fully landed, restart the client once - its own -shutdown, then the loop below, which knows
|
||||
@@ -357,7 +376,7 @@ case $mode in
|
||||
# StateFlags 4 = fully installed; a moment more for the client to finish its bookkeeping.
|
||||
if grep -q '"StateFlags"[[:space:]]*"4"' "$_bl_acf" 2>/dev/null; then
|
||||
sleep 10
|
||||
bannerlator-steam-compat "$steam_root" >/dev/null 2>&1 || true
|
||||
steam-compatibility "$steam_root" >/dev/null 2>&1 || true
|
||||
step "compatibility layer installed: restarting the Steam client once"
|
||||
: > "$HOME/.bl-restart-once"
|
||||
"$steam_root/steamrtarm64/steam" -shutdown >/dev/null 2>&1 || true
|
||||
@@ -514,10 +533,10 @@ case $mode in
|
||||
nap 5
|
||||
beat=$((beat + 1))
|
||||
[ "$((beat % 3))" -eq 0 ] || continue
|
||||
bannerlator-seed-redists "$steam_root" >/dev/null 2>&1 || true
|
||||
droiddeck-seed-redists "$steam_root" >/dev/null 2>&1 || true
|
||||
if compat_due; then
|
||||
: > "$compat_stamp"
|
||||
bannerlator-steam-compat "$steam_root" >/dev/null 2>&1 || true
|
||||
steam-compatibility "$steam_root" >/dev/null 2>&1 || true
|
||||
fi
|
||||
done
|
||||
) &
|
||||
@@ -542,9 +561,9 @@ case $mode in
|
||||
# refuses what it cannot do, since the app has no say over Wi-Fi - answer what the client asks.
|
||||
# The bus config is written here rather than shipped, so a runtime installed earlier gets this
|
||||
# from the app's copy of the session scripts without a re-host. (WinNative, maxjivi05, e7a224ae.)
|
||||
if command -v dbus-daemon >/dev/null 2>&1 && command -v bannerlator-netmanager >/dev/null 2>&1; then
|
||||
mkdir -p /run/dbus /usr/local/share/bannerlator
|
||||
cat > /usr/local/share/bannerlator/system-bus.conf <<'BUSCONF'
|
||||
if command -v dbus-daemon >/dev/null 2>&1 && command -v droiddeck-netmanager >/dev/null 2>&1; then
|
||||
mkdir -p /run/dbus /usr/local/share/droiddeck
|
||||
cat > /usr/local/share/droiddeck/system-bus.conf <<'BUSCONF'
|
||||
<!DOCTYPE busconfig PUBLIC "-//freedesktop//DTD D-Bus Bus Configuration 1.0//EN"
|
||||
"http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd">
|
||||
<busconfig>
|
||||
@@ -560,21 +579,21 @@ case $mode in
|
||||
</busconfig>
|
||||
BUSCONF
|
||||
rm -f /run/dbus/system_bus_socket
|
||||
dbus-daemon --config-file=/usr/local/share/bannerlator/system-bus.conf --nofork --nopidfile &
|
||||
dbus-daemon --config-file=/usr/local/share/droiddeck/system-bus.conf --nofork --nopidfile &
|
||||
system_bus=$!
|
||||
for _ in $(seq 1 50); do
|
||||
[ -S /run/dbus/system_bus_socket ] && break
|
||||
sleep 0.1
|
||||
done
|
||||
if [ -S /run/dbus/system_bus_socket ]; then
|
||||
bannerlator-netmanager &
|
||||
droiddeck-netmanager &
|
||||
netmanager=$!
|
||||
echo "== network: system bus up, NetworkManager stand-in running"
|
||||
# Steam blanks its main UI before calling login1.Suspend. Without the
|
||||
# matching resume notification it stays black although the menus work.
|
||||
# Own the name before Steam constructs its login1 proxy at startup.
|
||||
rm -f "$BL_LAUNCH_DIR/steam-sleep-ready"
|
||||
bannerlator-login1 &
|
||||
droiddeck-login1 &
|
||||
login_manager=$!
|
||||
for ((_i = 0; _i < 50; _i++)); do
|
||||
[ -f "$BL_LAUNCH_DIR/steam-sleep-ready" ] && break
|
||||
@@ -598,26 +617,20 @@ BUSCONF
|
||||
export STEAM_RUNTIME=1
|
||||
export LD_LIBRARY_PATH=$steam_root/steamrtarm64:$steam_root/steamrtarm64/panorama${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}
|
||||
export SDL_VIDEO_X11_DGAMOUSE=0
|
||||
# Native-Linux x86 games go through Valve's FEX compat tool, which runs FEX with FEX_PORTABLE=1
|
||||
# - that makes FEX look for its config next to the binary, while the tool writes one into the
|
||||
# app's compatdata instead. FEX therefore starts with no rootfs, every x86_64 library lookup
|
||||
# falls through to the host, and the guest shell dies on libreadline before the game is reached.
|
||||
# FEX_ROOTFS names it outright and is read whatever the config situation.
|
||||
[ -d /usr/share/guestos/fex-mesa ] && export FEX_ROOTFS=/usr/share/guestos/fex-mesa
|
||||
# Decky is optional and session scoped: the app's marker opts in, and this supervisor is
|
||||
# reaped with the client session. Native ARM64 runs directly. A legacy x86_64 asset is used
|
||||
# only when its recorded architecture and this guest's existing FEX installation agree.
|
||||
# only when its recorded architecture says so and droiddeck-fex has FEX and its runtime ready.
|
||||
decky_loader=$HOME/homebrew/services/PluginLoader
|
||||
if [ -f "$HOME/.droiddeck-decky-enabled" ] && [ -x "$decky_loader" ]; then
|
||||
decky_arch=$(cat "$HOME/homebrew/services/.droiddeck-decky-arch" 2>/dev/null || echo unknown)
|
||||
if [ "$decky_arch" = arm64 ] || { [ "$decky_arch" = x86_64 ] && [ -x /usr/bin/FEX ] && [ -n "${FEX_ROOTFS:-}" ]; }; then
|
||||
if [ "$decky_arch" = arm64 ] || { [ "$decky_arch" = x86_64 ] && /usr/local/bin/droiddeck-fex prepare >/dev/null; }; then
|
||||
(
|
||||
decky_child=
|
||||
decky_stop() { [ -z "$decky_child" ] || kill "$decky_child" 2>/dev/null; [ -z "$decky_child" ] || wait "$decky_child" 2>/dev/null; exit 0; }
|
||||
trap decky_stop TERM INT HUP
|
||||
decky_exits=0
|
||||
while :; do
|
||||
if [ "$decky_arch" = x86_64 ]; then /usr/bin/FEX "$decky_loader" >>"$HOME/homebrew/services/PluginLoader.log" 2>&1 &
|
||||
if [ "$decky_arch" = x86_64 ]; then /usr/local/bin/droiddeck-fex run --mode on -- "$decky_loader" >>"$HOME/homebrew/services/PluginLoader.log" 2>&1 &
|
||||
else "$decky_loader" >>"$HOME/homebrew/services/PluginLoader.log" 2>&1 &
|
||||
fi
|
||||
decky_child=$!
|
||||
@@ -640,6 +653,20 @@ BUSCONF
|
||||
echo "== Decky: installed loader architecture is unsupported by this guest; not starting"
|
||||
fi
|
||||
fi
|
||||
_bl_cdp=()
|
||||
if [ -f "$steam_root/.cef-enable-remote-debugging" ]; then
|
||||
export BL_CDP_PORT=8080
|
||||
else
|
||||
export BL_CDP_PORT=$((20000 + RANDOM % 30000))
|
||||
_bl_cdp=(-cef-enable-debugging -devtools-port "$BL_CDP_PORT")
|
||||
fi
|
||||
if [ -f "$HOME/.droiddeck-decky-enabled" ] && [ "${decky_arch:-}" = x86_64 ]; then
|
||||
echo "== steam: devtools port $BL_CDP_PORT left open for the x86_64 Decky loader"
|
||||
else
|
||||
export BL_CDP_GUARD=$BL_CDP_PORT
|
||||
echo "== steam: devtools port $BL_CDP_PORT, guest processes only"
|
||||
fi
|
||||
droiddeck-steam-compat "$steam_root" 2>&1 &
|
||||
# The client exits 42 when it has updated itself and wants a fresh start (steam.sh does this).
|
||||
# BL_STEAM_UI=desktop = the client's desktop UI (a window, the library as a list), which the
|
||||
# desktop's launchers ask for; gamescope shows one window at a time and the game takes over.
|
||||
@@ -682,7 +709,7 @@ BUSCONF
|
||||
steam_channel=${BL_STEAM_CHANNEL:-steamdeck_publicbeta}
|
||||
steam_beta=$steam_root/package/beta
|
||||
if [ -n "${BL_ADDED_GAMES:-}" ] && [ -f "$BL_ADDED_GAMES" ]; then
|
||||
bannerlator-steam-games watch "$steam_root" "$BL_ADDED_GAMES" &
|
||||
droiddeck-steam-games watch "$steam_root" "$BL_ADDED_GAMES" &
|
||||
games_watcher=$!
|
||||
fi
|
||||
# Lossless Scaling (Steam app 993090): whether this account owns it, asked of the signed-in
|
||||
@@ -694,7 +721,7 @@ BUSCONF
|
||||
for ((_i = 0; _i < 60; _i++)); do
|
||||
nap 30
|
||||
[ -e "$owned" ] && exit 0
|
||||
answer=$(bannerlator-steam-games probe "$steam_root" 993090 2>/dev/null) || continue
|
||||
answer=$(droiddeck-steam-games probe "$steam_root" 993090 2>/dev/null) || continue
|
||||
case $answer in
|
||||
*'"993090": true'*) mkdir -p "${owned%/*}" && : > "$owned" && echo "== Lossless Scaling: owned" ;;
|
||||
*) echo "== Lossless Scaling: not owned by this account" ;;
|
||||
@@ -703,7 +730,7 @@ BUSCONF
|
||||
done
|
||||
) &
|
||||
fi
|
||||
echo "== steam args: ${_bl_ui[*]} -clientbeta $steam_channel -no-cef-sandbox -cef-force-gpu -cef-ozone-platform=x11 -cef-use-gl=angle -cef-use-angle=vulkan $*"
|
||||
echo "== steam args: ${_bl_ui[*]} ${_bl_cdp[*]} -clientbeta $steam_channel -no-cef-sandbox -cef-force-gpu -cef-ozone-platform=x11 -cef-use-gl=angle -cef-use-angle=vulkan $*"
|
||||
# An update that cannot install asks for a restart (rc=42) every time; the count is capped so a
|
||||
# session can never again loop in silence, which reads as a menu opening and closing by itself.
|
||||
steam_updates=0
|
||||
@@ -749,14 +776,17 @@ BUSCONF
|
||||
echo "$steam_channel" > "$steam_beta"
|
||||
fi
|
||||
step "starting the Steam client${BL_STEAM_UI:+ ($BL_STEAM_UI UI)}"
|
||||
"$steam_root/steamrtarm64/steam" "${_bl_ui[@]}" -clientbeta "$steam_channel" \
|
||||
"$steam_root/steamrtarm64/steam" "${_bl_ui[@]}" "${_bl_cdp[@]}" -clientbeta "$steam_channel" \
|
||||
-no-cef-sandbox -cef-force-gpu -cef-ozone-platform=x11 \
|
||||
-cef-use-gl=angle -cef-use-angle=vulkan "$@"
|
||||
rc=$?
|
||||
echo "== steam exited rc=$rc"
|
||||
collect_steam_logs
|
||||
if [ -f "$HOME/.config/droiddeck/fex-wanted" ] && [ -x /usr/local/bin/droiddeck-fex ]; then
|
||||
/usr/local/bin/droiddeck-fex status >/dev/null 2>&1 || true
|
||||
fi
|
||||
if [ -n "${BL_ADDED_GAMES:-}" ] && [ -f "$BL_ADDED_GAMES" ]; then
|
||||
bannerlator-steam-shortcuts "$steam_root" "$BL_ADDED_GAMES" || true
|
||||
droiddeck-steam-shortcuts "$steam_root" "$BL_ADDED_GAMES" || true
|
||||
fi
|
||||
if [ -f "$HOME/.bl-stop-requested" ]; then
|
||||
rm -f "$HOME/.bl-stop-requested" "$HOME/.bl-restart-once"
|
||||
@@ -787,7 +817,7 @@ BUSCONF
|
||||
wait "$games_watcher" 2>/dev/null || true
|
||||
fi
|
||||
if [ -n "${BL_DESKTOP:-}" ]; then
|
||||
# Started from the desktop (bannerlator-steam-launch): the desktop's own programs share this
|
||||
# Started from the desktop (droiddeck-steam-launch): the desktop's own programs share this
|
||||
# script's parent, so reap_orphans - right under gamescope, where everything is the client's -
|
||||
# is not for here. The helpers this run started (the cores and redistributables beats, the
|
||||
# system bus and the NetworkManager stand-in) go with the client instead.
|
||||
@@ -812,7 +842,7 @@ BUSCONF
|
||||
exit "$rc"
|
||||
;;
|
||||
*)
|
||||
echo "bannerlator-session: unknown mode '$mode'" >&2
|
||||
echo "droiddeck-session: unknown mode '$mode'" >&2
|
||||
exit 64
|
||||
;;
|
||||
esac
|
||||
+495
@@ -0,0 +1,495 @@
|
||||
#!/usr/bin/python3
|
||||
import base64
|
||||
import ctypes
|
||||
import json
|
||||
import os
|
||||
import runpy
|
||||
import select
|
||||
import signal
|
||||
import socket
|
||||
import struct
|
||||
import sys
|
||||
import time
|
||||
|
||||
HERE = os.path.dirname(os.path.realpath(__file__))
|
||||
COMPAT = runpy.run_path(os.path.join(HERE, "steam-compatibility"))
|
||||
BINDING = "droiddeckCompatChanged"
|
||||
INSTALL_JS = r"""
|
||||
(() => {
|
||||
if (window.__droiddeckCompat) return "present";
|
||||
const enc = new TextEncoder(), dec = new TextDecoder();
|
||||
const varint = (value, out) => { let n = BigInt(value); do { let b = Number(n & 0x7fn); n >>= 7n; if (n) b |= 0x80; out.push(b); } while (n); };
|
||||
const key = (field, wire, out) => varint(field * 8 + wire, out);
|
||||
const str = (field, s, out) => { const b = enc.encode(s); key(field, 2, out); varint(b.length, out); for (const x of b) out.push(x); };
|
||||
const uint = (field, v, out) => { key(field, 0, out); varint(v, out); };
|
||||
const fixed64 = (field, v, out) => { key(field, 1, out); let n = BigInt(v); for (let i = 0; i < 8; i++) { out.push(Number(n & 0xffn)); n >>= 8n; } };
|
||||
const parse = (bytes) => {
|
||||
const fields = {};
|
||||
let i = 0;
|
||||
const read = () => { let r = 0n, s = 0n, b; do { b = bytes[i++]; r |= BigInt(b & 0x7f) << s; s += 7n; } while (b & 0x80); return r; };
|
||||
while (i < bytes.length) {
|
||||
const k = Number(read()), field = k >> 3, wire = k & 7;
|
||||
let v;
|
||||
if (wire === 0) v = read();
|
||||
else if (wire === 1) { v = 0n; for (let j = 0; j < 8; j++) v |= BigInt(bytes[i + j]) << BigInt(8 * j); i += 8; }
|
||||
else if (wire === 2) { const n = Number(read()); v = bytes.subarray(i, i + n); i += n; }
|
||||
else if (wire === 5) { v = bytes.subarray(i, i + 4); i += 4; }
|
||||
else throw new Error("unexpected wire type " + wire);
|
||||
(fields[field] = fields[field] || []).push(v);
|
||||
}
|
||||
return fields;
|
||||
};
|
||||
const text = (f, n) => f[n] ? dec.decode(f[n][0]) : "";
|
||||
const self = { seq: 0, pending: new Map(), ws: null, opening: null, changes: 0 };
|
||||
const frame = (method, body, auth) => {
|
||||
const h = [];
|
||||
fixed64(10, ++self.seq, h);
|
||||
str(12, method, h);
|
||||
if (auth) str(40, auth, h);
|
||||
const out = new Uint8Array(8 + h.length + body.length);
|
||||
const view = new DataView(out.buffer);
|
||||
view.setUint32(0, (0x80000000 | 146) >>> 0, true);
|
||||
view.setUint32(4, h.length, true);
|
||||
out.set(h, 8);
|
||||
out.set(body, 8 + h.length);
|
||||
return [self.seq, out];
|
||||
};
|
||||
const onMessage = (event) => {
|
||||
const bytes = new Uint8Array(event.data);
|
||||
const length = new DataView(event.data).getUint32(4, true);
|
||||
const header = parse(bytes.subarray(8, 8 + length));
|
||||
const target = header[11] ? Number(header[11][0] & 0xffffffffn) : -1;
|
||||
if (self.pending.has(target)) {
|
||||
const done = self.pending.get(target);
|
||||
self.pending.delete(target);
|
||||
const result = header[13] ? Number(header[13][0]) : 2;
|
||||
done(result === 1 ? { ok: true, body: parse(bytes.subarray(8 + length)) } : { ok: false, eresult: result, error: text(header, 14) });
|
||||
return;
|
||||
}
|
||||
if (text(header, 12).startsWith("CompatManager.NotifyStateChanged")) {
|
||||
self.changes++;
|
||||
if (typeof window.__BINDING__ === "function") window.__BINDING__(String(self.changes));
|
||||
}
|
||||
};
|
||||
const send = (method, body, auth) => new Promise((resolve, reject) => {
|
||||
const [id, out] = frame(method, Uint8Array.from(body), auth);
|
||||
const timer = setTimeout(() => { self.pending.delete(id); reject(new Error(method + " timed out")); }, 10000);
|
||||
self.pending.set(id, (r) => { clearTimeout(timer); resolve(r); });
|
||||
self.ws.send(out);
|
||||
});
|
||||
const open = async () => {
|
||||
const info = await SteamClient.WebUITransport.GetTransportInfo();
|
||||
const ws = new WebSocket("ws://127.0.0.1:" + info.portClientdll + "/transportsocket/");
|
||||
ws.binaryType = "arraybuffer";
|
||||
await new Promise((resolve, reject) => { ws.onopen = resolve; ws.onerror = () => reject(new Error("the client's transport refused the connection")); });
|
||||
ws.onmessage = onMessage;
|
||||
ws.onclose = () => {
|
||||
if (self.ws === ws) self.ws = null;
|
||||
for (const done of self.pending.values()) done({ ok: false, eresult: 0, error: "connection closed" });
|
||||
self.pending.clear();
|
||||
};
|
||||
self.ws = ws;
|
||||
const body = [];
|
||||
str(1, info.authKeyClientdll, body);
|
||||
const r = await send("TransportAuth.Authenticate#1", body, info.authKeyClientdll);
|
||||
if (!r.ok) { ws.close(); throw new Error("the client's transport refused authentication (" + r.eresult + ")"); }
|
||||
};
|
||||
const ready = async () => {
|
||||
if (self.ws && self.ws.readyState === 1) return;
|
||||
if (!self.opening) self.opening = open().finally(() => { self.opening = null; });
|
||||
await self.opening;
|
||||
};
|
||||
self.get = async (appid) => {
|
||||
await ready();
|
||||
const body = [];
|
||||
uint(1, appid, body);
|
||||
const r = await send("CompatManager.GetCompatTools#1", body);
|
||||
if (!r.ok) throw new Error("GetCompatTools " + appid + " failed (" + r.eresult + " " + r.error + ")");
|
||||
return { selected: text(r.body, 3), fallback: text(r.body, 4), tools: (r.body[1] || []).map((t) => text(parse(t), 1)) };
|
||||
};
|
||||
self.set = async (appid, name) => {
|
||||
await ready();
|
||||
const body = [];
|
||||
uint(1, appid, body);
|
||||
str(2, name, body);
|
||||
const r = await send("CompatManager.SpecifyCompatTool#1", body);
|
||||
if (!r.ok) throw new Error("SpecifyCompatTool " + appid + " " + name + " failed (" + r.eresult + " " + r.error + ")");
|
||||
return true;
|
||||
};
|
||||
self.many = async (apps) => {
|
||||
const out = {};
|
||||
for (const app of apps) out[app] = (await self.get(Number(app))).selected;
|
||||
return out;
|
||||
};
|
||||
window.__droiddeckCompat = self;
|
||||
return "installed";
|
||||
})()
|
||||
""".replace("__BINDING__", BINDING)
|
||||
|
||||
|
||||
class Closed(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def say(message):
|
||||
print("droiddeck-steam-compat: %s" % message, flush=True)
|
||||
|
||||
|
||||
def connect(port, timeout=5):
|
||||
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
sock.settimeout(timeout)
|
||||
try:
|
||||
sock.bind(("127.0.0.1", 0))
|
||||
sock.connect(("127.0.0.1", port))
|
||||
except OSError:
|
||||
sock.close()
|
||||
raise
|
||||
return sock
|
||||
|
||||
|
||||
def http_get(port, path):
|
||||
sock = connect(port)
|
||||
try:
|
||||
sock.sendall(("GET %s HTTP/1.1\r\nHost: 127.0.0.1:%d\r\nConnection: close\r\n\r\n" % (path, port)).encode())
|
||||
data = b""
|
||||
length = None
|
||||
while length is None or len(data) < length:
|
||||
chunk = sock.recv(65536)
|
||||
if not chunk:
|
||||
break
|
||||
data += chunk
|
||||
if length is None and b"\r\n\r\n" in data:
|
||||
head, _, rest = data.partition(b"\r\n\r\n")
|
||||
for line in head.split(b"\r\n")[1:]:
|
||||
name, _, value = line.partition(b":")
|
||||
if name.strip().lower() == b"content-length":
|
||||
length = int(value.strip())
|
||||
if length is None:
|
||||
length = float("inf")
|
||||
data = rest
|
||||
if not head.startswith(b"HTTP/1.1 200"):
|
||||
raise OSError("devtools answered %r" % head[:40])
|
||||
finally:
|
||||
sock.close()
|
||||
return json.loads(data.decode("utf-8", "replace"))
|
||||
|
||||
|
||||
class WebSocket:
|
||||
def __init__(self, port, path):
|
||||
self.sock = connect(port)
|
||||
key = base64.b64encode(os.urandom(16)).decode()
|
||||
self.sock.sendall(("GET %s HTTP/1.1\r\nHost: 127.0.0.1:%d\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n"
|
||||
"Sec-WebSocket-Key: %s\r\nSec-WebSocket-Version: 13\r\n\r\n" % (path, port, key)).encode())
|
||||
self.buffer = b""
|
||||
while b"\r\n\r\n" not in self.buffer:
|
||||
self.fill()
|
||||
head, _, self.buffer = self.buffer.partition(b"\r\n\r\n")
|
||||
if not head.startswith(b"HTTP/1.1 101"):
|
||||
raise OSError("devtools refused the websocket: %r" % head[:60])
|
||||
self.sock.settimeout(None)
|
||||
|
||||
def fileno(self):
|
||||
return self.sock.fileno()
|
||||
|
||||
def fill(self):
|
||||
chunk = self.sock.recv(65536)
|
||||
if not chunk:
|
||||
raise Closed("devtools closed the connection")
|
||||
self.buffer += chunk
|
||||
|
||||
def take(self, n):
|
||||
while len(self.buffer) < n:
|
||||
self.fill()
|
||||
data, self.buffer = self.buffer[:n], self.buffer[n:]
|
||||
return data
|
||||
|
||||
def send(self, text, opcode=1):
|
||||
payload = text.encode() if isinstance(text, str) else text
|
||||
mask = os.urandom(4)
|
||||
n = len(payload)
|
||||
if n < 126:
|
||||
head = struct.pack("!BB", 0x80 | opcode, 0x80 | n)
|
||||
elif n < 65536:
|
||||
head = struct.pack("!BBH", 0x80 | opcode, 0xFE, n)
|
||||
else:
|
||||
head = struct.pack("!BBQ", 0x80 | opcode, 0xFF, n)
|
||||
self.sock.sendall(head + mask + bytes(b ^ mask[i % 4] for i, b in enumerate(payload)))
|
||||
|
||||
def pending(self):
|
||||
return len(self.buffer) > 0
|
||||
|
||||
def recv(self):
|
||||
message = b""
|
||||
while True:
|
||||
first, second = self.take(2)
|
||||
n = second & 0x7F
|
||||
if n == 126:
|
||||
n = struct.unpack("!H", self.take(2))[0]
|
||||
elif n == 127:
|
||||
n = struct.unpack("!Q", self.take(8))[0]
|
||||
mask = self.take(4) if second & 0x80 else None
|
||||
payload = self.take(n)
|
||||
if mask:
|
||||
payload = bytes(b ^ mask[i % 4] for i, b in enumerate(payload))
|
||||
opcode = first & 0x0F
|
||||
if opcode == 8:
|
||||
raise Closed("devtools closed the websocket")
|
||||
if opcode == 9:
|
||||
self.send(payload, 10)
|
||||
continue
|
||||
if opcode == 10:
|
||||
continue
|
||||
message += payload
|
||||
if first & 0x80:
|
||||
return message.decode("utf-8", "replace")
|
||||
|
||||
def close(self):
|
||||
try:
|
||||
self.sock.close()
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
class Page:
|
||||
def __init__(self, port, path):
|
||||
self.ws = WebSocket(port, path)
|
||||
self.next_id = 0
|
||||
self.events = []
|
||||
|
||||
def call(self, method, params=None, timeout=30):
|
||||
self.next_id += 1
|
||||
mine = self.next_id
|
||||
self.ws.send(json.dumps({"id": mine, "method": method, "params": params or {}}))
|
||||
deadline = time.monotonic() + timeout
|
||||
while True:
|
||||
if not self.ws.pending():
|
||||
left = deadline - time.monotonic()
|
||||
if left <= 0 or not select.select([self.ws], [], [], left)[0]:
|
||||
raise TimeoutError("%s timed out" % method)
|
||||
message = json.loads(self.ws.recv())
|
||||
if message.get("id") == mine:
|
||||
if "error" in message:
|
||||
raise RuntimeError("%s: %s" % (method, message["error"].get("message")))
|
||||
return message.get("result", {})
|
||||
if "method" in message:
|
||||
self.events.append(message)
|
||||
|
||||
def evaluate(self, expression, timeout=30):
|
||||
result = self.call("Runtime.evaluate", {"expression": expression, "awaitPromise": True, "returnByValue": True}, timeout)
|
||||
if "exceptionDetails" in result:
|
||||
details = result["exceptionDetails"]
|
||||
raise RuntimeError((details.get("exception") or {}).get("description") or details.get("text") or "script failed")
|
||||
return result.get("result", {}).get("value")
|
||||
|
||||
def compat(self, call):
|
||||
return self.evaluate("%s;\nwindow.__droiddeckCompat.%s" % (INSTALL_JS, call))
|
||||
|
||||
def drain(self):
|
||||
while True:
|
||||
if not self.ws.pending() and not select.select([self.ws], [], [], 0)[0]:
|
||||
break
|
||||
message = json.loads(self.ws.recv())
|
||||
if "method" in message:
|
||||
self.events.append(message)
|
||||
events, self.events = self.events, []
|
||||
return events
|
||||
|
||||
|
||||
def shared_context(port):
|
||||
for target in http_get(port, "/json/list"):
|
||||
if target.get("title") == "SharedJSContext" and target.get("webSocketDebuggerUrl"):
|
||||
path = target["webSocketDebuggerUrl"].split("/", 3)[3]
|
||||
return "/" + path
|
||||
return None
|
||||
|
||||
|
||||
class Watcher:
|
||||
MASK = 0x00000008 | 0x00000080 | 0x00000100 | 0x00000200
|
||||
|
||||
def __init__(self, files):
|
||||
self.files = files
|
||||
self.fd = -1
|
||||
try:
|
||||
libc = ctypes.CDLL(None, use_errno=True)
|
||||
fd = libc.inotify_init1(os.O_NONBLOCK | os.O_CLOEXEC)
|
||||
dirs = sorted({os.path.dirname(f) for f in files if os.path.isdir(os.path.dirname(f))})
|
||||
if fd >= 0 and dirs and all(libc.inotify_add_watch(fd, d.encode(), self.MASK) >= 0 for d in dirs):
|
||||
self.fd = fd
|
||||
elif fd >= 0:
|
||||
os.close(fd)
|
||||
except (OSError, AttributeError):
|
||||
self.fd = -1
|
||||
self.stamp = self.snapshot()
|
||||
|
||||
def snapshot(self):
|
||||
stamp = []
|
||||
for f in self.files:
|
||||
for p in (f, os.path.dirname(f)):
|
||||
try:
|
||||
stamp.append(os.stat(p).st_mtime_ns)
|
||||
except OSError:
|
||||
stamp.append(0)
|
||||
return stamp
|
||||
|
||||
def fileno(self):
|
||||
return self.fd
|
||||
|
||||
def changed(self):
|
||||
if self.fd < 0:
|
||||
stamp = self.snapshot()
|
||||
moved, self.stamp = stamp != self.stamp, stamp
|
||||
return moved
|
||||
names = set()
|
||||
try:
|
||||
while True:
|
||||
data = os.read(self.fd, 65536)
|
||||
if not data:
|
||||
break
|
||||
at = 0
|
||||
while at + 16 <= len(data):
|
||||
_, _, _, size = struct.unpack_from("iIII", data, at)
|
||||
names.add(data[at + 16:at + 16 + size].split(b"\0", 1)[0].decode("utf-8", "replace"))
|
||||
at += 16 + size
|
||||
except BlockingIOError:
|
||||
pass
|
||||
wanted = {os.path.basename(f) for f in self.files}
|
||||
return any(n in wanted or n.startswith("appmanifest_") for n in names)
|
||||
|
||||
|
||||
class Helper:
|
||||
def __init__(self, steam_root, port):
|
||||
self.steam_root = steam_root
|
||||
self.port = port
|
||||
self.page = None
|
||||
self.known = set()
|
||||
self.installed = None
|
||||
self.fex_asked = set()
|
||||
|
||||
def attach(self):
|
||||
path = shared_context(self.port)
|
||||
if path is None:
|
||||
raise LookupError("no SharedJSContext yet")
|
||||
page = Page(self.port, path)
|
||||
try:
|
||||
if page.evaluate("typeof SteamClient === 'object' && typeof SteamClient.WebUITransport === 'object'") is not True:
|
||||
raise LookupError("SteamClient is not ready")
|
||||
page.call("Runtime.addBinding", {"name": BINDING})
|
||||
page.compat("get(0)")
|
||||
except Exception:
|
||||
page.ws.close()
|
||||
raise
|
||||
self.page = page
|
||||
return True
|
||||
|
||||
def reconcile(self):
|
||||
page = self.page
|
||||
with COMPAT["locked"]():
|
||||
state_file = COMPAT["state_path"]("state.json")
|
||||
state = COMPAT["read_json"](state_file)
|
||||
request = COMPAT["read_json"](COMPAT["state_path"]("request.json"))
|
||||
catalog = COMPAT["tool_catalog"](self.steam_root)
|
||||
top = page.compat("get(0)")
|
||||
self.known = set(top["tools"])
|
||||
live = [t for t in catalog if t["name"] in self.known]
|
||||
wanted = COMPAT["requested_tool"](request, catalog)
|
||||
newer = isinstance(request.get("seq"), int) and request["seq"] > int(state.get("applied", 0) or 0)
|
||||
waiting = newer and wanted is not None and wanted not in self.known
|
||||
default, state = COMPAT["choose_default"](top["selected"], state, request, live, apply_request=not waiting)
|
||||
installed = COMPAT["installed_apps"](self.steam_root)
|
||||
self.installed = installed
|
||||
apps = sorted(set(installed) | set(state.get("auto", {})), key=COMPAT["app_order"])
|
||||
current = dict(page.compat("many(%s)" % json.dumps(apps)) or {})
|
||||
current["0"] = top["selected"]
|
||||
native = COMPAT["native_targets"](self.steam_root, installed)
|
||||
changes, auto = COMPAT["plan_mapping"](current, installed, [t["name"] for t in live], default, COMPAT["followers"](state, current), native)
|
||||
for app, tool in sorted(changes.items(), key=lambda item: COMPAT["app_order"](item[0])):
|
||||
page.compat("set(%d, %s)" % (int(app), json.dumps(tool)))
|
||||
say("%s -> %s" % ("default" if app == "0" else "app %s" % app, tool))
|
||||
state.update(auto=auto, tools=catalog, live=True)
|
||||
if waiting:
|
||||
state["pending"] = wanted
|
||||
say("%s is new to the running client; it applies when Steam next starts" % wanted)
|
||||
else:
|
||||
state.pop("pending", None)
|
||||
COMPAT["write_json"](state_file, state)
|
||||
if native or os.path.exists(COMPAT["fex_wanted_marker"]()):
|
||||
for app in COMPAT["request_fex"](self.steam_root, self.fex_asked):
|
||||
say("asked the client to install %s for x86 Linux titles and programs" % app)
|
||||
|
||||
def request_waiting(self):
|
||||
request = COMPAT["read_json"](COMPAT["state_path"]("request.json"))
|
||||
state = COMPAT["read_json"](COMPAT["state_path"]("state.json"))
|
||||
return isinstance(request.get("seq"), int) and request["seq"] > int(state.get("applied", 0) or 0)
|
||||
|
||||
def serve(self, watcher):
|
||||
with open(COMPAT["state_path"]("live.pid"), "w") as f:
|
||||
f.write("%d\n" % os.getpid())
|
||||
say("attached to the client on port %d" % self.port)
|
||||
self.reconcile()
|
||||
while True:
|
||||
sources = [self.page.ws] + ([watcher] if watcher.fileno() >= 0 else [])
|
||||
ready = [self.page.ws] if self.page.ws.pending() else select.select(sources, [], [], 30 if watcher.fileno() >= 0 else 2)[0]
|
||||
due = False
|
||||
if self.page.ws in ready:
|
||||
due = any(e.get("method") == "Runtime.bindingCalled" and e.get("params", {}).get("name") == BINDING
|
||||
for e in self.page.drain())
|
||||
if (watcher in ready or watcher.fileno() < 0) and watcher.changed():
|
||||
due = self.installed != COMPAT["installed_apps"](self.steam_root) or self.request_waiting()
|
||||
if due:
|
||||
time.sleep(0.3)
|
||||
if watcher.fileno() >= 0 and select.select([watcher], [], [], 0)[0]:
|
||||
watcher.changed()
|
||||
self.page.drain()
|
||||
self.reconcile()
|
||||
|
||||
|
||||
def detach():
|
||||
try:
|
||||
os.unlink(COMPAT["state_path"]("live.pid"))
|
||||
except OSError:
|
||||
pass
|
||||
with COMPAT["locked"]():
|
||||
state_file = COMPAT["state_path"]("state.json")
|
||||
state = COMPAT["read_json"](state_file)
|
||||
if state.get("live"):
|
||||
state["live"] = False
|
||||
COMPAT["write_json"](state_file, state)
|
||||
|
||||
|
||||
def main():
|
||||
steam_root = sys.argv[1]
|
||||
try:
|
||||
port = int(os.environ.get("BL_CDP_PORT", ""))
|
||||
except ValueError:
|
||||
say("no devtools port for this session; the client's mapping is kept through config.vdf")
|
||||
return 0
|
||||
os.makedirs(COMPAT["COMPAT_DIR"], exist_ok=True)
|
||||
watcher = Watcher([COMPAT["state_path"]("request.json")] + [os.path.join(lib, "steamapps", "libraryfolders.vdf") for lib in (steam_root, COMPAT["LIBRARY"] + "-sd")])
|
||||
helper = Helper(steam_root, port)
|
||||
failures = 0
|
||||
last = None
|
||||
while True:
|
||||
try:
|
||||
helper.attach()
|
||||
failures = 0
|
||||
last = None
|
||||
helper.serve(watcher)
|
||||
except Exception as e:
|
||||
if helper.page is not None:
|
||||
say("lost the client (%s); reattaching" % e)
|
||||
helper.page.ws.close()
|
||||
helper.page = None
|
||||
detach()
|
||||
elif str(e) != last:
|
||||
say("waiting for the client (%s)" % e)
|
||||
last = str(e)
|
||||
failures += 1
|
||||
time.sleep(min(2 * max(failures, 1), 10))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
signal.signal(signal.SIGTERM, lambda *_: sys.exit(0))
|
||||
try:
|
||||
sys.exit(main())
|
||||
finally:
|
||||
detach()
|
||||
+4
-4
@@ -239,13 +239,13 @@ def watch(steam_root, listing):
|
||||
status = last_status
|
||||
if pending and pending != requested and not game_running() and downloads_idle(steam_root):
|
||||
requested = pending
|
||||
print("bannerlator-steam-games: restarting the client once to import %s" % pending, flush=True)
|
||||
print("droiddeck-steam-games: restarting the client once to import %s" % pending, flush=True)
|
||||
try:
|
||||
request_restart(steam_root)
|
||||
except (OSError, subprocess.TimeoutExpired) as error:
|
||||
print("bannerlator-steam-games: restart unavailable: %s" % error, flush=True)
|
||||
print("droiddeck-steam-games: restart unavailable: %s" % error, flush=True)
|
||||
if status != last_status:
|
||||
print("bannerlator-steam-games: " + status, flush=True)
|
||||
print("droiddeck-steam-games: " + status, flush=True)
|
||||
last_status = status
|
||||
time.sleep(30)
|
||||
|
||||
@@ -357,7 +357,7 @@ def route(steam_root, acct, games):
|
||||
routes[str(game["appid"])] = appid
|
||||
continue
|
||||
except OSError as error:
|
||||
print(f"bannerlator-steam-games: import unavailable ({error})")
|
||||
print(f"droiddeck-steam-games: import unavailable ({error})")
|
||||
shortcuts.append(game)
|
||||
save_json(Path(acct) / "config/.droiddeck-routes.json", routes)
|
||||
return shortcuts, routes
|
||||
+7
-3
@@ -6,11 +6,15 @@ cdn=https://client-update.fastly.steamstatic.com
|
||||
steam_channel=${BL_STEAM_CHANNEL:-steamdeck_publicbeta}
|
||||
case "$steam_channel" in
|
||||
publicbeta|steamdeck_publicbeta) ;;
|
||||
*) echo "bannerlator-steam-install: unsupported Steam channel: $steam_channel" >&2; exit 1 ;;
|
||||
*) echo "droiddeck-steam-install: unsupported Steam channel: $steam_channel" >&2; exit 1 ;;
|
||||
esac
|
||||
manifest=steam_client_${steam_channel}_linuxarm64
|
||||
steam_root=${XDG_DATA_HOME:-$HOME/.local/share}/Steam
|
||||
stamp=$steam_root/package/bannerlator-installed
|
||||
stamp=$steam_root/package/droiddeck-installed
|
||||
legacy_stamp=$steam_root/package/bannerlator-installed
|
||||
if [ -f "$legacy_stamp" ] && [ ! -f "$stamp" ]; then
|
||||
mv -f "$legacy_stamp" "$stamp" || true
|
||||
fi
|
||||
[ -x "$steam_root/steamrtarm64/steam" ] && [ -f "$stamp" ] && exit 0
|
||||
|
||||
work=$(mktemp -d)
|
||||
@@ -24,7 +28,7 @@ awk -F'"' '
|
||||
$2 == "sha2" { sha[block] = $4 }
|
||||
END { for (b in file) if (b ~ /_all$/ || b ~ /_linuxarm64_linuxarm64$/) print b, file[b], sha[b] }
|
||||
' "$work/manifest" | sort > "$work/parts"
|
||||
[ -s "$work/parts" ] || { echo "bannerlator-steam-install: no client components in $manifest" >&2; exit 1; }
|
||||
[ -s "$work/parts" ] || { echo "droiddeck-steam-install: no client components in $manifest" >&2; exit 1; }
|
||||
total=$(grep -c . "$work/parts" 2>/dev/null || echo 0)
|
||||
|
||||
mkdir -p "$steam_root/package"
|
||||
+9
-9
@@ -1,12 +1,12 @@
|
||||
#!/bin/bash
|
||||
# Starts the Steam client from inside a session (the desktop's menu entries and the per-game
|
||||
# launchers bannerlator-desktop-games writes):
|
||||
# bannerlator-steam-launch desktop [appid|steam-url] Steam's desktop UI, optionally a game
|
||||
# bannerlator-steam-launch bigpicture [appid|steam-url] Big Picture
|
||||
# launchers droiddeck-desktop-games writes):
|
||||
# droiddeck-steam-launch desktop [appid|steam-url] Steam's desktop UI, optionally a game
|
||||
# droiddeck-steam-launch bigpicture [appid|steam-url] Big Picture
|
||||
#
|
||||
# On a desktop that draws with the GPU (labwc on vulkan or gles2 - the default since the GPU
|
||||
# desktop) the client runs right there: a window on the desktop, through the desktop's Xwayland,
|
||||
# with the same set-up a Steam session gives it (bannerlator-session steam, minus gamescope), and
|
||||
# with the same set-up a Steam session gives it (droiddeck-session steam, minus gamescope), and
|
||||
# its games open in windows of their own. A client already running there gets the request instead
|
||||
# of a second one being started.
|
||||
#
|
||||
@@ -35,24 +35,24 @@ if [ "${BL_DESKTOP:-}" = 1 ] && [ -n "${WLR_RENDERER:-}" ] && [ "$WLR_RENDERER"
|
||||
# One client at a time: the running one takes the request (a second start hands its command
|
||||
# line over and exits). No game asked for = switch it to the UI that was clicked.
|
||||
[ -n "$url" ] || { [ "$ui" = bigpicture ] && url=steam://open/bigpicture || url=steam://open/main; }
|
||||
echo "bannerlator-steam-launch: the client is running on the desktop; handing it $url" | tee -a "$log"
|
||||
echo "droiddeck-steam-launch: the client is running on the desktop; handing it $url" | tee -a "$log"
|
||||
exec "$client" "$url"
|
||||
fi
|
||||
echo "bannerlator-steam-launch: starting the Steam client on the desktop ($ui${url:+, $url}); log: $log"
|
||||
echo "droiddeck-steam-launch: starting the Steam client on the desktop ($ui${url:+, $url}); log: $log"
|
||||
# BL_INSIDE: the session script's Steam start-up without gamescope in front of it. The desktop UI
|
||||
# unless Big Picture was asked for; never Deck mode (its Quick Access Menu needs gamescope).
|
||||
export BL_INSIDE=1 BL_STEAMDECK=0
|
||||
if [ "$ui" = desktop ]; then export BL_STEAM_UI=desktop; else unset BL_STEAM_UI; fi
|
||||
setsid /usr/local/bin/bannerlator-session steam ${url:+"$url"} >>"$log" 2>&1 < /dev/null &
|
||||
setsid /usr/local/bin/droiddeck-session steam ${url:+"$url"} >>"$log" 2>&1 < /dev/null &
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# The software desktop, or outside the desktop: ask the app for a Steam session.
|
||||
dir=${BL_LAUNCH_DIR:-}
|
||||
if [ -z "$dir" ] || [ ! -d "$dir" ]; then
|
||||
echo "bannerlator-steam-launch: not inside a DroidDeck session (BL_LAUNCH_DIR unset)" >&2
|
||||
echo "droiddeck-steam-launch: not inside a DroidDeck session (BL_LAUNCH_DIR unset)" >&2
|
||||
exit 69
|
||||
fi
|
||||
# Written whole, then renamed: the app reads it on close, never half-written.
|
||||
printf 'ui=%s\nurl=%s\n' "$ui" "$url" > "$dir/steam-launch.tmp" && mv -f "$dir/steam-launch.tmp" "$dir/steam-launch"
|
||||
echo "bannerlator-steam-launch: asked the app for Steam ($ui${url:+, $url})"
|
||||
echo "droiddeck-steam-launch: asked the app for Steam ($ui${url:+, $url})"
|
||||
+6
-6
@@ -2,7 +2,7 @@
|
||||
# Registers the card the app installs to (bound at /mnt/droiddeck-sd) as a library folder of the
|
||||
# native Steam client, so they show as installed there instead of being downloaded a second time.
|
||||
#
|
||||
# bannerlator-steam-library <steam root>
|
||||
# droiddeck-steam-library <steam root>
|
||||
#
|
||||
# Ported from WinNative's gamescope runtime (GPL-3.0).
|
||||
import os
|
||||
@@ -61,7 +61,7 @@ def register(steam_root, library, label):
|
||||
os.makedirs(steamapps_dir, exist_ok=True)
|
||||
with open(path, "w", encoding="utf-8") as f:
|
||||
f.write(text)
|
||||
print("bannerlator-steam-library: registered %s with %d game(s)" % (library, len(apps)))
|
||||
print("droiddeck-steam-library: registered %s with %d game(s)" % (library, len(apps)))
|
||||
return len(apps)
|
||||
|
||||
|
||||
@@ -85,7 +85,7 @@ def rename(steam_root, old, new):
|
||||
return
|
||||
with open(path, "w", encoding="utf-8") as f:
|
||||
f.write(old_path.sub(lambda m: m.group(1) + new + m.group(2), text))
|
||||
print("bannerlator-steam-library: moved %s to %s" % (old, new))
|
||||
print("droiddeck-steam-library: moved %s to %s" % (old, new))
|
||||
|
||||
|
||||
def forget(steam_root, library):
|
||||
@@ -115,7 +115,7 @@ def forget(steam_root, library):
|
||||
if text != "\n".join(lines):
|
||||
with open(path, "w", encoding="utf-8") as f:
|
||||
f.write(text)
|
||||
print("bannerlator-steam-library: forgot %s" % library)
|
||||
print("droiddeck-steam-library: forgot %s" % library)
|
||||
|
||||
|
||||
def relabel(steam_root, target, label):
|
||||
@@ -151,7 +151,7 @@ def relabel(steam_root, target, label):
|
||||
if changed:
|
||||
with open(path, "w", encoding="utf-8") as f:
|
||||
f.write("\n".join(out))
|
||||
print("bannerlator-steam-library: labelled %s %r" % (target, label))
|
||||
print("droiddeck-steam-library: labelled %s %r" % (target, label))
|
||||
# A library also carries its own libraryfolder.vdf, and the client takes the label from there
|
||||
# back into the list above - so editing the list alone is undone on the next start. The
|
||||
# client's own library has no such file, which is why that one kept the new name and the card
|
||||
@@ -165,7 +165,7 @@ def relabel(steam_root, target, label):
|
||||
if new != text:
|
||||
with open(marker, "w", encoding="utf-8") as f:
|
||||
f.write(new)
|
||||
print("bannerlator-steam-library: labelled %s in its own marker too" % target)
|
||||
print("droiddeck-steam-library: labelled %s in its own marker too" % target)
|
||||
|
||||
|
||||
def main():
|
||||
+2
-2
@@ -1,7 +1,7 @@
|
||||
#!/bin/bash
|
||||
# `steam` on the desktop. The client writes a menu entry per installed game that runs
|
||||
# `steam steam://rungameid/<id>`, and its own launchers say `steam`. On the desktop that goes
|
||||
# through bannerlator-steam-launch - which runs the client on the desktop itself when it draws with
|
||||
# through droiddeck-steam-launch - which runs the client on the desktop itself when it draws with
|
||||
# the GPU, hands the URL to a client already running there, and asks the app for a Steam session
|
||||
# on a software desktop. Anywhere else it is the client itself.
|
||||
set -u
|
||||
@@ -14,6 +14,6 @@ if [ "${BL_DESKTOP:-}" = 1 ]; then
|
||||
-gamepadui|-bigpicture) ui=bigpicture ;;
|
||||
esac
|
||||
done
|
||||
exec /usr/local/bin/bannerlator-steam-launch "$ui" ${url:+"$url"}
|
||||
exec /usr/local/bin/droiddeck-steam-launch "$ui" ${url:+"$url"}
|
||||
fi
|
||||
exec "${HOME:-/root}/.local/share/Steam/steamrtarm64/steam" "$@"
|
||||
+14
-13
@@ -1,7 +1,7 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Import added games while Steam is closed, preserving user-created shortcuts.
|
||||
|
||||
Usage: bannerlator-steam-shortcuts <steam_root> <added-games.json>
|
||||
Usage: droiddeck-steam-shortcuts <steam_root> <added-games.json>
|
||||
"""
|
||||
import importlib.machinery
|
||||
import importlib.util
|
||||
@@ -163,7 +163,7 @@ def install_art(acct, games):
|
||||
os.replace(dst + ".tmp", dst)
|
||||
copied += 1
|
||||
except OSError as e:
|
||||
print("bannerlator-steam-shortcuts: could not copy art %s (%s)" % (name, e))
|
||||
print("droiddeck-steam-shortcuts: could not copy art %s (%s)" % (name, e))
|
||||
for name in list(manifest):
|
||||
if name not in wanted:
|
||||
try:
|
||||
@@ -173,7 +173,7 @@ def install_art(acct, games):
|
||||
with open(manifest_path, "w", encoding="utf-8") as f:
|
||||
json.dump(wanted, f)
|
||||
if copied:
|
||||
print("bannerlator-steam-shortcuts: %d piece(s) of art placed" % copied)
|
||||
print("droiddeck-steam-shortcuts: %d piece(s) of art placed" % copied)
|
||||
|
||||
|
||||
def main():
|
||||
@@ -185,11 +185,11 @@ def main():
|
||||
with open(listing, encoding="utf-8") as f:
|
||||
games = json.load(f)
|
||||
except (OSError, ValueError) as e:
|
||||
print("bannerlator-steam-shortcuts: no list (%s)" % e)
|
||||
print("droiddeck-steam-shortcuts: no list (%s)" % e)
|
||||
return 0
|
||||
acct = account_dir(steam_root)
|
||||
if not acct:
|
||||
print("bannerlator-steam-shortcuts: no signed-in account yet; nothing written")
|
||||
print("droiddeck-steam-shortcuts: no signed-in account yet; nothing written")
|
||||
return 0
|
||||
config = os.path.join(acct, "config")
|
||||
os.makedirs(config, exist_ok=True)
|
||||
@@ -200,9 +200,9 @@ def main():
|
||||
with open(path, "rb") as f:
|
||||
existing = parse(f.read()).get("shortcuts", {})
|
||||
except (ValueError, IndexError, struct.error) as e:
|
||||
print("bannerlator-steam-shortcuts: could not read the existing file (%s); keeping it unchanged" % e)
|
||||
print("droiddeck-steam-shortcuts: could not read the existing file (%s); keeping it unchanged" % e)
|
||||
return 1
|
||||
helper = os.path.join(os.path.dirname(os.path.abspath(__file__)), "bannerlator-steam-games")
|
||||
helper = os.path.join(os.path.dirname(os.path.abspath(__file__)), "droiddeck-steam-games")
|
||||
loader = importlib.machinery.SourceFileLoader("steam_games", helper)
|
||||
spec = importlib.util.spec_from_loader(loader.name, loader)
|
||||
routing = importlib.util.module_from_spec(spec)
|
||||
@@ -225,25 +225,26 @@ def main():
|
||||
entry["LaunchOptions"] = previous["LaunchOptions"]
|
||||
ours.append(entry)
|
||||
entries = {str(i): v for i, v in enumerate(kept + ours)}
|
||||
tmp = path + ".bannerlator"
|
||||
tmp = path + ".droiddeck"
|
||||
with open(tmp, "wb") as f:
|
||||
f.write(write({"shortcuts": entries}))
|
||||
os.replace(tmp, path)
|
||||
print("bannerlator-steam-shortcuts: %d added game(s) written, %d of the client's own kept" % (len(ours), len(kept)))
|
||||
print("droiddeck-steam-shortcuts: %d added game(s) written, %d of the client's own kept" % (len(ours), len(kept)))
|
||||
install_art(acct, [g for g in games if g.get("exe") and g.get("name")])
|
||||
# Each added game runs under the ARM64 Proton: the compat registrar's own mapping writer.
|
||||
try:
|
||||
# No .py suffix on the registrar, so the loader has to be named.
|
||||
compat_path = "/usr/local/bin/bannerlator-steam-compat"
|
||||
compat_path = "/usr/local/bin/steam-compatibility"
|
||||
spec = importlib.util.spec_from_file_location("compat", compat_path, loader=importlib.machinery.SourceFileLoader("compat", compat_path))
|
||||
compat = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(compat)
|
||||
cfg = os.path.join(steam_root, "config", "config.vdf")
|
||||
if os.path.isfile(cfg) and (ours or routes):
|
||||
compat.register_default(cfg, apps=[str(int(g["appid"]) & 0xFFFFFFFF) for g in games if g.get("exe")] + [str(appid) for appid in set(routes.values())])
|
||||
print("bannerlator-steam-shortcuts: mapped them to %s" % compat.TOOL)
|
||||
compat.register_default(cfg, apps=[str(int(g["appid"]) & 0xFFFFFFFF) for g in games if g.get("exe")] + [str(appid) for appid in set(routes.values())],
|
||||
protect=compat.adopt_extras(os.path.join(steam_root, "compatibilitytools.d")))
|
||||
print("droiddeck-steam-shortcuts: mapped them to %s" % compat.TOOL)
|
||||
except Exception as e: # noqa: BLE001 - the games still show; the client falls back to the default tool
|
||||
print("bannerlator-steam-shortcuts: compat mapping skipped (%s)" % e)
|
||||
print("droiddeck-steam-shortcuts: compat mapping skipped (%s)" % e)
|
||||
return 0
|
||||
|
||||
|
||||
File renamed without changes.
+1112
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user