merge: refresh PRoot removal

This commit is contained in:
Kurt Himebauch committed 2026-12-05 16:30:33 -05:00
commit d949407c5c
406 files changed
+41180 -3048

No files matched your search

+13 -5
View File
@@ -9,7 +9,7 @@ export MOZ_ENABLE_WAYLAND=1 MOZ_USE_XINPUT2=1
export SHELL=/bin/bash
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
export MOZ_SHM_NO_SEALS=1
export MOZ_SHM_NO_SEALS=1 MOZ_CRASHREPORTER_DISABLE=1
export QTWEBENGINE_DISABLE_SANDBOX=1
export KWIN_COMPOSE=Q QT_QUICK_BACKEND=software LIBGL_ALWAYS_SOFTWARE=1 GALLIUM_DRIVER=llvmpipe
export KWIN_USE_OVERLAYS=0
@@ -142,11 +142,10 @@ Exec=konsole -e /usr/local/bin/droiddeck-steam-x64
Icon=steam
Categories=System;
ENTRY
python3 /usr/local/bin/droiddeck-pad-defaults 2>&1 | sed 's/^/[pads] /'
( while sleep 30; do python3 /usr/local/bin/droiddeck-pad-defaults 2>&1 | sed 's/^/[pads] /'; done ) &
python3 /usr/local/bin/droiddeck-pad-defaults --every 30 &
python3 /usr/local/bin/droiddeck-desktop-gpu 2>&1 | sed 's/^/[gpu] /'
/usr/local/bin/droiddeck-desktop-window-rules 2>&1 | sed 's/^/[rules] /'
( python3 /usr/local/bin/droiddeck-library-perms 2>&1 | sed 's/^/[perms] /' ) &
python3 /usr/local/bin/droiddeck-library-perms 2>&1 &
mkdir -p /usr/local/share/applications
cat > /usr/local/share/applications/droiddeck-ime.desktop <<'ENTRY'
[Desktop Entry]
@@ -175,6 +174,15 @@ fi
if command -v flatpak >/dev/null 2>&1 && [ ! -d /var/lib/pacman ]; then
FLATPAK_BWRAP=/usr/local/bin/droiddeck-bwrap flatpak remote-add --user --if-not-exists flathub https://dl.flathub.org/repo/flathub.flatpakrepo >/dev/null 2>&1 &
fi
# Android counts the desktop's programs against an app's limit of 32. Off unless the user turns them
# back on in Autostart: Discover's update notifier (the packages follow DroidDeck's releases, and it
# keeps PackageKit running as root), GeoClue's demo agent (nothing asks for a location) and the
# global-menu proxy (the panel has no global menu).
mkdir -p "$HOME/.config/autostart"
for entry in org.kde.discover.notifier geoclue-demo-agent gmenudbusmenuproxy; do
[ -e "$HOME/.config/autostart/$entry.desktop" ] ||
printf '[Desktop Entry]\nType=Application\nName=%s\nHidden=true\n' "$entry" > "$HOME/.config/autostart/$entry.desktop"
done
skel_done=$HOME/.local/share/droiddeck/skel-copied
if [ -d /etc/skel ] && [ ! -e "$skel_done" ]; then
cp -rn /etc/skel/. "$HOME/" 2>/dev/null
@@ -234,7 +242,7 @@ mkdir -p /run/droiddeck
rm -f "$return_gaming"
echo "== droiddeck-desktop: Plasma on $WAYLAND_DISPLAY"
as_user=
if [ "${DD_DESKTOP_USER:-}" = 1 ] && [ -n "${DDNATV_ROOT:-}" ]; then
if [ "${DD_DESKTOP_USER:-}" = 1 ]; then
as_user=/usr/local/bin/droiddeck-user
echo "== droiddeck-desktop: Plasma runs as an ordinary user"
fi
@@ -9,3 +9,11 @@ pref("datareporting.policy.dataSubmissionEnabled", false);
pref("browser.aboutwelcome.enabled", false);
pref("browser.startup.homepage", "about:blank");
pref("layout.css.devPixelsPerPx", "1.25");
// Android counts each of Firefox's processes against the app's limit of 32: one web content process
// per two tabs' worth of sites rather than one per site, none started ahead, and extensions and
// about: pages in the processes that already exist.
pref("fission.autostart", false);
pref("dom.ipc.processCount", 2);
pref("dom.ipc.processPrelaunch.enabled", false);
pref("browser.tabs.remote.separatePrivilegedContentProcess", false);
pref("extensions.webextensions.remote", false);
@@ -9,42 +9,35 @@ if [ -x /usr/local/bin/droiddeck-fex ]; then
3|62) exec /usr/local/bin/droiddeck-fex run --mode on -- "$image" "$@" ;;
esac
fi
if [ -n "${DDNATV_ROOT:-}" ]; then
image=$(realpath -- "$image") || exit 127
cache=${XDG_CACHE_HOME:-${HOME:-/root}/.cache}/droiddeck-appimage
mkdir -p "$cache" || exit 1
exec 9>"$cache/.lock"
flock 9 || exit 1
state() { printf '%s\n%s' "$1" "$(TZ=UTC0 stat -Lc '%s %y' -- "$1" 2>/dev/null)"; }
for dir in "$cache"/*/; do
dir=${dir%/}
[ ! -L "$dir" ] && [ -f "$dir/source" ] || continue
[ "$(cat "$dir/source")" = "$(state "$(head -n 1 "$dir/source")")" ] && continue
(flock -n 7 && rm -rf -- "${dir:?}") 7<"$dir/source"
done
find "$cache" -mindepth 1 -maxdepth 1 -name '.unpack.*' -mmin +60 -exec rm -rf -- {} + 2>/dev/null
source=$(state "$image")
unpacked=$cache/$(printf '%s' "$source" | md5sum | cut -c1-16)
if [ "$(cat "$unpacked/source" 2>/dev/null)" != "$source" ] || [ ! -e "$unpacked/squashfs-root/AppRun" ]; then
echo "== appimage: unpacking $image"
work=$(mktemp -d "$cache/.unpack.XXXXXX") || exit 1
if ! (cd "$work" && /usr/local/bin/droiddeck-fex extract "$image") || [ ! -e "$work/squashfs-root/AppRun" ]; then
rm -rf -- "${work:?}"
echo "droiddeck-appimage-exec: could not unpack $image" >&2
exit 1
fi
printf '%s\n' "$source" > "$work/source"
rm -rf -- "${unpacked:?}"
mv -- "$work" "$unpacked" || exit 1
image=$(realpath -- "$image") || exit 127
cache=${XDG_CACHE_HOME:-${HOME:-/root}/.cache}/droiddeck-appimage
mkdir -p "$cache" || exit 1
exec 9>"$cache/.lock"
flock 9 || exit 1
state() { printf '%s\n%s' "$1" "$(TZ=UTC0 stat -Lc '%s %y' -- "$1" 2>/dev/null)"; }
for dir in "$cache"/*/; do
dir=${dir%/}
[ ! -L "$dir" ] && [ -f "$dir/source" ] || continue
[ "$(cat "$dir/source")" = "$(state "$(head -n 1 "$dir/source")")" ] && continue
(flock -n 7 && rm -rf -- "${dir:?}") 7<"$dir/source"
done
find "$cache" -mindepth 1 -maxdepth 1 -name '.unpack.*' -mmin +60 -exec rm -rf -- {} + 2>/dev/null
source=$(state "$image")
unpacked=$cache/$(printf '%s' "$source" | md5sum | cut -c1-16)
if [ "$(cat "$unpacked/source" 2>/dev/null)" != "$source" ] || [ ! -e "$unpacked/squashfs-root/AppRun" ]; then
echo "== appimage: unpacking $image"
work=$(mktemp -d "$cache/.unpack.XXXXXX") || exit 1
if ! (cd "$work" && /usr/local/bin/droiddeck-fex extract "$image") || [ ! -e "$work/squashfs-root/AppRun" ]; then
rm -rf -- "${work:?}"
echo "droiddeck-appimage-exec: could not unpack $image" >&2
exit 1
fi
exec 8<"$unpacked/source"
flock -s 8 || exit 1
exec 9>&-
export APPIMAGE=$image APPDIR=$unpacked/squashfs-root ARGV0=$image OWD=$PWD
exec "$APPDIR/AppRun" "$@"
printf '%s\n' "$source" > "$work/source"
rm -rf -- "${unpacked:?}"
mv -- "$work" "$unpacked" || exit 1
fi
if [ -x /usr/local/lib/droiddeck/uruntime ]; then
export TARGET_APPIMAGE=$image
exec /usr/local/lib/droiddeck/uruntime "$@"
fi
exec "$image" "$@"
exec 8<"$unpacked/source"
flock -s 8 || exit 1
exec 9>&-
export APPIMAGE=$image APPDIR=$unpacked/squashfs-root ARGV0=$image OWD=$PWD
exec "$APPDIR/AppRun" "$@"
@@ -1,7 +1,15 @@
#!/bin/bash
[ -n "${DD_ANDROID_CLIPBOARD:-}" ] && [ -n "${DISPLAY:-}" ] || exit 0
/usr/local/bin/droiddeck-clipboard "$DD_ANDROID_CLIPBOARD" &
child=$!
trap 'kill "$child" 2>/dev/null' EXIT
[ -n "${DISPLAY:-}" ] || exit 0
children=()
if [ -n "${DD_ANDROID_CLIPBOARD:-}" ]; then
/usr/local/bin/droiddeck-clipboard "$DD_ANDROID_CLIPBOARD" &
children+=("$!")
fi
if [ -n "${DD_LAUNCH_DIR:-}" ] && [ -x /usr/local/bin/droiddeck-text-input ]; then
/usr/local/bin/droiddeck-text-input "$DD_LAUNCH_DIR/text-input.sock" &
children+=("$!")
fi
[ "${#children[@]}" -gt 0 ] || exit 0
trap 'kill "${children[@]}" 2>/dev/null' EXIT
trap 'exit 0' TERM INT
wait "$child"
wait "${children[@]}"
@@ -664,7 +664,7 @@ def data_dir(env):
return DATA_DIR
def guest_environment(fex, env):
def guest_environment(fex, env, keep_compat=False):
result = dict(env)
data = data_dir(env)
for directory in (CONFIG_DIR, data, CACHE_DIR):
@@ -672,7 +672,7 @@ def guest_environment(fex, env):
result["FEX_APP_CONFIG_LOCATION"] = CONFIG_DIR + "/"
result["FEX_APP_DATA_LOCATION"] = data + "/"
result["FEX_APP_CACHE_LOCATION"] = CACHE_DIR + "/"
if result.get("STEAM_COMPAT_DATA_PATH"):
if result.get("STEAM_COMPAT_DATA_PATH") and not keep_compat:
short = data if data != DATA_DIR else "/tmp/fex"
os.makedirs(short, exist_ok=True)
result["STEAM_COMPAT_DATA_PATH"] = short
@@ -750,9 +750,12 @@ def vulkan_thunk_loads(fex, folder):
def required_runtime(program):
text = read_text(os.path.join(os.path.dirname(program), "toolmanifest.vdf")) or ""
match = re.search(r'"require_tool_appid"\s+"(\d+)"', text)
return match.group(1) if match and match.group(1) in RUNTIMES else SNIPER_APPID
folder = os.path.dirname(program)
for name in ("toolmanifest.vdf.droiddeck-orig", "toolmanifest.vdf"):
match = re.search(r'"require_tool_appid"\s+"(\d+)"', read_text(os.path.join(folder, name)) or "")
if match and match.group(1) in RUNTIMES:
return match.group(1)
return SNIPER_APPID
def resolve(program, env):
@@ -761,7 +764,7 @@ def resolve(program, env):
return shutil.which(program, path=env.get("PATH")) or program
def launch(command, env, mode, decide=None):
def launch(command, env, mode, decide=None, keep_compat=False):
program = resolve(command[0], env)
use = mode == "on" or (mode == "auto" and needs_fex(decide or program))
if not use:
@@ -769,7 +772,7 @@ def launch(command, env, mode, decide=None):
fex = prepare(required_runtime(program))
if fex is None:
return 126
guest = guest_environment(fex, env)
guest = guest_environment(fex, env, keep_compat)
x86_64 = elf_arch(program) != "i386"
thunks = "on" if "FEX_THUNKCONFIG" in guest else "off"
folder = decide if decide and os.path.isdir(decide) else os.path.dirname(program)
@@ -781,7 +784,7 @@ def launch(command, env, mode, decide=None):
return os.execve(fex["bin"], [fex["bin"], program] + command[1:], guest)
def game_environment(env, command):
def game_environment(env, command, proton=None):
try:
game_env = runpy.run_path(os.path.join(BIN_DIR, "droiddeck-game-env"))
env = game_env["game_gpu"](env)
@@ -800,7 +803,14 @@ def game_environment(env, command):
config = json.load(source)
except FileNotFoundError:
config = {"version": 1}
return game_env["apply_config"](env, config, str(app), fixes)
env = game_env["apply_config"](env, config, str(app), fixes)
if proton and len(proton) > 2 and proton[1] == "waitforexitandrun":
logged = game_env["apply_game_debug_logs"](env, config)
if logged is not env:
say("game debug logs enabled for this launch")
env = game_env["game_logs"](proton, logged, str(app))
game_env["GAME_DEBUG"]["cap_proton_log"](env)
return env
except FileNotFoundError:
return env
except Exception as error:
@@ -889,11 +899,10 @@ def extract(image):
x86 = elf_arch(image) in X86.values()
if os.access(URUNTIME, os.X_OK):
with open(image, "rb") as source:
native = bool(os.environ.get("DDNATV_ROOT"))
target = "/proc/self/fd/%d" % source.fileno() if native else image
target = "/proc/self/fd/%d" % source.fileno()
run = subprocess.run([URUNTIME, "--appimage-extract"], stdout=subprocess.DEVNULL, stderr=subprocess.PIPE,
env=dict(os.environ, TARGET_APPIMAGE=target),
pass_fds=(source.fileno(),) if native else ())
pass_fds=(source.fileno(),))
errors = run.stderr.decode("utf-8", "replace")
sys.stderr.write(errors)
status = run.returncode
@@ -963,7 +972,7 @@ def parse_run(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")
say("usage: droiddeck-fex steam VERB CMD... | proton PROTON VERB CMD... | run [--mode auto|on|off] [--for PATH] [--] CMD... | needs PATH | extract IMAGE | prepare | update | status")
return 2
action, args = argv[0], list(argv[1:])
if action == "steam":
@@ -975,6 +984,10 @@ def main(argv):
if not command:
return 2
return launch(command, game_environment(dict(os.environ), command), os.environ.get("DROIDDECK_FEX", "auto"))
if action == "proton":
if len(args) < 2:
return 2
return launch(args, game_environment(dict(os.environ), args[2:] or args, args), "on", keep_compat=True)
if action == "run":
try:
mode, decide, command = parse_run(args)
@@ -996,6 +1009,10 @@ def main(argv):
return extract(args[0])
if action == "prepare":
return 0 if prepare() else 1
if action == "update":
with locked():
update_own_fex()
return 0
if action == "status":
with locked():
status = describe(fex_install(), runtime_platform(), graphics_platform())
@@ -29,10 +29,14 @@ fex_install() {
return 1
fi
(cd "$tmp/root" && find . ! -type d) > "$tmp/files"
for d in usr/local/share/fex-emu/GuestThunks usr/local/share/fex-emu/GuestThunks_32 usr/local/lib/fex-emu/HostThunks usr/local/lib/fex-emu/HostThunks_32; do
[ -d "$tmp/root/$d" ] && [ -d "$dst$d" ] || continue
(cd "$dst" && find "$d" ! -type d) | while IFS= read -r f; do grep -qxF "./$f" "$tmp/files" || echo "$f"; done
done > "$tmp/stale"
{
for d in usr/local/share/fex-emu/GuestThunks usr/local/share/fex-emu/GuestThunks_32 usr/local/lib/fex-emu/HostThunks usr/local/lib/fex-emu/HostThunks_32; do
[ -d "$tmp/root/$d" ] && [ -d "$dst$d" ] || continue
(cd "$dst" && find "$d" ! -type d) | while IFS= read -r f; do grep -qxF "./$f" "$tmp/files" || echo "$f"; done
done
f=usr/local/share/fex-emu/.droiddeck-patches
if [ -e "$dst$f" ] && ! grep -qxF "./$f" "$tmp/files"; then echo "$f"; fi
} > "$tmp/stale"
mkdir "$tmp/old"
while IFS= read -r f; do
f=${f#./}
@@ -69,7 +69,8 @@ def apply_game_debug_logs(env, config=None, debug_dir=None):
"PROTON_CRASH_REPORT_DIR": debug_dir,
"DXVK_LOG_PATH": debug_dir,
"DXVK_LOG_LEVEL": "debug",
"VKD3D_DEBUG": "info",
"VKD3D_DEBUG": "warn",
"VKD3D_SHADER_DEBUG": "warn",
"WINEDEBUG": game_debug_channels(env.get("WINEDEBUG"), env.get("PROTON_LOG")),
})
return result
@@ -13,9 +13,10 @@ import subprocess
import sys
import tempfile
from pathlib import Path
import xml.etree.ElementTree as ElementTree
GAME_PREFIX = "DROIDDECK_GAME_"
GAME_SPLIT_KEYS = ("TU_DEBUG", "MESA_NO_ERROR")
GAME_SPLIT_KEYS = ("TU_DEBUG", "MESA_NO_ERROR", "DROIDDECK_GAME_FRAME_ACQUIRE")
CHROMIUM_FILES = {"chrome-sandbox", "chrome_100_percent.pak", "v8_context_snapshot.bin"}
SYNC_KEYS = ("DD_SYNC", "DD_SYNC_FALLBACK", "DD_FSYNC_FIRST", "DD_SYNC_MIN_NOFILE", "PROTON_NO_ESYNC", "PROTON_NO_FSYNC", "PROTON_NO_NTSYNC", "WINEESYNC")
SEED_REDISTS = "/usr/local/bin/droiddeck-seed-redists"
@@ -67,6 +68,30 @@ DOTNET_FEX = {
"FEX_X87REDUCEDPRECISION": "0",
}
STABILITY_FEX = dict(DOTNET_FEX, FEX_MULTIBLOCK="0")
# Microsoft's original Xbox releases for PC run its emulator (Emu.exe). The switches turn on fixes in the builds of
# DroidDeck-Bionic's Wine, FEX and VKD3D-Proton made for it, each off by default: Wine delivers the Windows 11 special
# APCs the emulator interrupts its CPU threads with; FEX keeps the x87 state across those interrupts, checks for one in
# a loop that branches back into its own block, and maps an image without a lock order that deadlocks; Wine gives the
# boot video's types a display aperture and reports a 0 timer resolution (DXVK's vblank wait otherwise spins a core);
# VKD3D-Proton presents frames DXVK drew through D3D11On12 and maps the packed 4:2:2 video formats. FEX keeps
# DOTNET_FEX (the emulator's menu is .NET) without vector and memcpy TSO and with reduced x87 precision: on an
# Adreno 750 the emulator's menus ran at ~58 fps instead of ~35.
XBOX_BACK_COMPAT_IDENTITY = "xbox360backwardcompatibil"
XBOX_BACK_COMPAT_ENV = dict(
DOTNET_FEX,
FEX_VECTORTSOENABLED="0",
FEX_MEMCPYSETTSOENABLED="0",
FEX_X87REDUCEDPRECISION="1",
WINE_SPECIAL_APC_INTERRUPT="1",
FEX_SYNCX87CONTEXT="1",
FEX_LOOPSUSPENDCHECK="1",
FEX_SAFEIMAGEMAP="1",
WINE_MF_DISPLAY_APERTURE="1",
WINE_PRECISE_SLEEP="1",
VKD3D_INTEROP_PRESENT="1",
VKD3D_PACKED_422="1",
)
PSPC_SDK_FILES = {"install_pspc_sdk_runtime.bat", "pspcsdkruntimeinstaller.msi", "pspcsdkruntimemanager.msi"}
# Setup loader offset-table IDs, as innoextract's known_setup_loader_versions lists them. Loaders
# from 5.1.5 keep the table in a resource; older ones also put "Inno" at file offset 0x30.
INNO_LOADER_IDS = (b"rDlPtS", b"nS5W7dT\x83\xaa\x1b\x0fj")
@@ -149,6 +174,40 @@ def game_files(exe):
return names
def unreal_binary_files(exe):
project = os.path.splitext(os.path.basename(exe))[0]
try:
with os.scandir(os.path.join(os.path.dirname(exe), project, "Binaries", "Win64")) as folder:
return {entry.name.lower() for entry in folder}
except OSError:
return set()
def xbox_identity(exe):
"""The identity name in the MicrosoftGame.config of the Xbox package the executable is in, or ""."""
folder = os.path.dirname(exe)
for _ in range(4):
# The Xbox store accepts the file name in any case (XboxManifest.read).
name = "MicrosoftGame.config"
if not os.path.isfile(os.path.join(folder, name)):
try:
name = next((entry for entry in sorted(os.listdir(folder)) if entry.lower() == "microsoftgame.config"), name)
except OSError:
pass
try:
with open(os.path.join(folder, name), "rb") as source:
root = ElementTree.fromstring(source.read(1 << 20))
except (OSError, ElementTree.ParseError):
root = None
if root is not None:
return next((node.get("Name", "") for node in root.iter() if node.tag.rsplit("}", 1)[-1] == "Identity"), "")
parent = os.path.dirname(folder)
if parent == folder:
break
folder = parent
return ""
class Game:
def __init__(self, exe, args, app_id=""):
@@ -158,6 +217,7 @@ class Game:
self.app_id = app_id
self.stem = os.path.splitext(os.path.basename(exe))[0].lower()
self.files = game_files(exe)
self.xbox_back_compat = os.path.isabs(exe) and xbox_identity(exe).lower().startswith(XBOX_BACK_COMPAT_IDENTITY)
def has_arg(self, name):
return any(a == name or a.startswith(name + "=") for a in self.args)
@@ -177,10 +237,16 @@ def is_godot(game):
@fix
def dotnet_memory_ordering(game):
if "coreclr.dll" in game.files:
if "coreclr.dll" in game.files and not game.xbox_back_compat:
return DOTNET_FEX, [], ".NET runtime: FEX with full TSO"
@fix
def xbox_back_compat(game):
if game.xbox_back_compat:
return XBOX_BACK_COMPAT_ENV, [], "Original Xbox game: emulator fixes on, FEX with load/store TSO and reduced x87 precision"
@fix
def unity_memory_ordering(game):
if {"unityplayer.so", "gameassembly.so", "unityplayer.dll"} & game.files:
@@ -249,6 +315,12 @@ def arkham_city_x87(game):
return {"FEX_X87REDUCEDPRECISION": "0"}, [], "Batman: Arkham City: FEX with full x87 precision"
@fix
def playstation_pc_sdk_x87(game):
if PSPC_SDK_FILES & (game.files | unreal_binary_files(game.exe)):
return {"FEX_X87REDUCEDPRECISION": "0"}, [], "PlayStation PC SDK: FEX with full x87 precision"
@fix
def split_second_x87_fip(game):
if game.app_id == "297860" or game.stem == "splitsecond":
@@ -3,6 +3,7 @@
import json
import os
LAUNCH_DIR_FILE = "/tmp/droiddeck-browser/launch-dir"
STEAM = "/usr/local/bin/droiddeck-steam-shim"
import sys
import time
from pathlib import Path
@@ -17,6 +18,13 @@ def hand_over(url, launch_dir):
os.rename(tmp, req / (rid + ".json"))
def same_file(a, b):
try:
return os.path.samefile(a, b)
except OSError:
return os.path.realpath(a) == os.path.realpath(b)
def where(url):
from urllib.parse import urlsplit
try:
@@ -40,10 +48,11 @@ def main(argv):
if url.startswith(("https://", "http://")) and launch_dir:
hand_over(url, launch_dir)
return 0
here = os.path.dirname(os.path.realpath(sys.argv[0]))
if url.startswith("steam://") and os.access(STEAM, os.X_OK):
os.execv(STEAM, [STEAM, url])
for d in os.environ.get("PATH", "").split(os.pathsep):
candidate = os.path.join(d, "xdg-open")
if os.access(candidate, os.X_OK) and os.path.realpath(candidate) != os.path.realpath(__file__) and os.path.abspath(d) != here:
if os.access(candidate, os.X_OK) and not same_file(candidate, __file__):
os.execv(candidate, [candidate] + argv)
return 1
@@ -1,6 +1,8 @@
#!/usr/bin/python3
import glob
import os
import sys
import time
HOME = os.environ.get("HOME", "/root")
CONFIG = os.environ.get("XDG_CONFIG_HOME", os.path.join(HOME, ".config"))
@@ -1048,8 +1050,19 @@ def switch_emulators():
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"droiddeck-pad-defaults: {step.__name__}: {e}")
def run_all():
for step in (rpcs3, duckstation, pcsx2, armsx2, dolphin, cemu, melonds, ppsspp, retroarch, switch_emulators):
try:
step()
except Exception as e:
print(f"droiddeck-pad-defaults: {step.__name__}: {e}", flush=True)
# --every SECONDS: again at that interval, for emulators set up while the desktop runs. One process
# for the whole desktop session rather than a shell loop starting a new one each time.
sys.stdout.reconfigure(line_buffering=True)
run_all()
if len(sys.argv) == 3 and sys.argv[1] == "--every":
while True:
time.sleep(float(sys.argv[2]))
run_all()
@@ -13,6 +13,12 @@ fi
export HOME=${HOME:-/root}
mode=${1:-desktop}
shift || true
# Steam and its helpers share one session bus per session; an existing desktop bus is inherited.
if [ "$mode" = steam ] && [ -z "${DBUS_SESSION_BUS_ADDRESS:-}" ]; then
exec dbus-run-session -- "$0" "$mode" "$@"
fi
step() { echo "== STEP $(date -u +%H:%M:%S.%3N) $*"; }
# Starts a long-lived program in its own Android process, which Android does not count against
# the session's child processes (docs/phantom-processes.md); a normal background job otherwise.
@@ -63,9 +69,16 @@ dd_job() {
# window's app by walking its process's parents) or its utility processes (the client only accepts
# its transport from its own children).
if [ "${DD_SPAWN_DAEMONS:-1}" = 1 ] && [ -n "${DD_SPAWN:-}" ]; then
export DD_HANDOFF=${DD_HANDOFF-xdg-desktop-portal:xdg-permission-store:xdg-desktop-portal-gtk:at-spi-bus-launcher:at-spi2-registryd:plasma_waitforname:bash+dd-job:droiddeck-log-writer:gamescope:gamescopereaper:droiddeck-session+steam:Xwayland:dbus-launch:droiddeck-agent:droiddeck-launcher-cores:droiddeck-pace-cores:droiddeck-documents:droiddeck-steam-games+watch:droiddeck-steam-compat:dbus-daemon+--nofork:proton:pipewire:wireplumber:PluginLoader:PluginLoader.real:xprop+-spy:gnudd:steamwebhelper+--type=renderer:wine:wine-preloader:wine64:wine64-preloader:wineserver}
export DD_HANDOFF=${DD_HANDOFF-xdg-desktop-portal:xdg-permission-store:xdg-desktop-portal-gtk:at-spi-bus-launcher:at-spi2-registryd:plasma_waitforname:bash+dd-job:droiddeck-log-writer:gamescope:gamescopereaper:droiddeck-session+steam:Xwayland:dbus-launch:droiddeck-agent:droiddeck-launcher-cores:droiddeck-pace-cores:droiddeck-documents:droiddeck-steam-games+watch:droiddeck-steam-compat:dbus-daemon+--nofork:proton:pipewire:wireplumber:PluginLoader:PluginLoader.real:xprop+-spy:gnudd:steamwebhelper+--type=renderer:wine:wine-preloader:wine64:wine64-preloader:wineserver:droiddeck-login1:droiddeck-snapd:droiddeck-polkitd:droiddeck-root+/usr/libexec/packagekitd:droiddeck-desktop-clipboard:droiddeck-ime:droiddeck-pad-defaults+--every:droiddeck-library-perms:droiddeck-clipboard:dbus-run-session:startplasma-wayland:plasma_session:kwin_wayland_wrapper:kwin_wayland:kded6:ksmserver:kglobalacceld:plasmashell:krunner:org_kde_powerdevil:xembedsniproxy:kaccess:xsettingsd:kdeconnectd:kunifiedpush-distributor:kactivitymanagerd:xdg-desktop-portal-kde:dconf-service:polkit-kde-authentication-agent-1:plasma-welcome:kioworker}
# The programs these start for the user (an app from the panel, a file opened in Dolphin)
export DD_HANDOFF_LAUNCHERS=${DD_HANDOFF_LAUNCHERS-plasmashell:krunner:dolphin}
# Each process's first parent, so that a process can reap the zombies it adopts as a subreaper, and
# the programs that reap them even while they leave SIGCHLD alone (hook/signals.c)
rm -f /run/droiddeck-parents.* 2>/dev/null
export DD_PARENTS=/run/droiddeck-parents.$$
export DD_REAP_ADOPTED=${DD_REAP_ADOPTED-plasmashell:plasma_session:kwin_wayland:kwin_wayland_wrapper:kaccess:ksmserver:kded6:krunner:dolphin:dbus-daemon:startplasma-wayland:gamescope:wine:wine64:wine-preloader:wine64-preloader:wineserver:PluginLoader:PluginLoader.real}
else
unset DD_HANDOFF
unset DD_HANDOFF DD_HANDOFF_LAUNCHERS DD_PARENTS DD_REAP_ADOPTED
fi
steam_setup_failed() {
echo "== steam: the Steam client could not be set up (status $1)"
@@ -705,6 +718,13 @@ if [ "${DD_DESKTOP:-}" != 1 ] && [ -n "${DD_ANDROID_CLIPBOARD:-}" ] && [ -x /usr
dd_spawn /usr/local/bin/droiddeck-clipboard "$DD_ANDROID_CLIPBOARD"
fi
ime_text_pid=
if [ "${DD_DESKTOP:-}" != 1 ] && [ -n "${DISPLAY:-}" ] && [ -n "${DD_LAUNCH_DIR:-}" ] \
&& [ -x /usr/local/bin/droiddeck-text-input ]; then
/usr/local/bin/droiddeck-text-input "$DD_LAUNCH_DIR/text-input.sock" &
ime_text_pid=$!
fi
[ "${DD_DESKTOP:-}" = 1 ] || start_agent
case $mode in
@@ -1540,6 +1560,7 @@ case $mode in
decky_exits=0
# The guest has no "deck" user, which Decky otherwise requires at startup.
export UNPRIVILEGED_USER=root
export LIVE_RELOAD=0
while :; do
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 &
@@ -1971,6 +1992,46 @@ case $mode in
fi
fi
rm -f "$HOME/.dd-restart-game" "$HOME/.dd-restarted-for"
unset IBUS_ADDRESS
ime_ibus_pid=
ime_ibus_socket=
stop_steam_ime() {
if [ -n "$ime_ibus_pid" ]; then
kill "$ime_ibus_pid" 2>/dev/null || true
wait "$ime_ibus_pid" 2>/dev/null || true
ime_ibus_pid=
fi
[ -S "$ime_ibus_socket" ] && rm -f "$ime_ibus_socket"
ime_ibus_socket=
unset IBUS_ADDRESS
}
if [ -x /usr/local/bin/droiddeck-steam-ime ] && [ -x /usr/local/lib/droiddeck-ime/ibus-engine-pinyin ] \
&& [ -x /usr/bin/ibus-daemon ] && [ -x /usr/bin/ibus ]; then
ime_ibus_socket="${XDG_RUNTIME_DIR:-/run/droiddeck}/droiddeck-ibus-$$.sock"
export IBUS_ADDRESS="unix:path=$ime_ibus_socket"
/usr/local/bin/droiddeck-steam-ime &
ime_ibus_pid=$!
ime_ready=0
_ime_deadline=$((SECONDS + 5))
while [ "$SECONDS" -lt "$_ime_deadline" ]; do
if env -u LD_LIBRARY_PATH -u LD_PRELOAD -u GSETTINGS_SCHEMA_DIR -u DCONF_PROFILE \
timeout 1 /usr/bin/ibus list-engine --name-only 2>/dev/null | grep -qx 'pinyin'; then
ime_ready=1
break
fi
kill -0 "$ime_ibus_pid" 2>/dev/null || break
nap 0.1
done
unset _ime_deadline
if [ "$ime_ready" = 1 ]; then
echo "== ime: pinyin engine ready at $IBUS_ADDRESS"
else
echo "== ime: the pinyin engine did not start at $IBUS_ADDRESS; Steam starts without Chinese input"
stop_steam_ime
fi
elif [ -x /usr/local/bin/droiddeck-steam-ime ] && [ -x /usr/local/lib/droiddeck-ime/ibus-engine-pinyin ]; then
echo "== ime: the installed Linux runtime does not include IBus; Steam starts without pinyin"
fi
while :; do
rm -f "$HOME/.dd-restart-once" "$HOME/.dd-restart-lost"
if [ -f "$steam_beta" ] && [ "$(cat "$steam_beta" 2>/dev/null)" != "$steam_channel" ]; then
@@ -2086,6 +2147,12 @@ case $mode in
kill "$games_watcher" 2>/dev/null || true
wait "$games_watcher" 2>/dev/null || true
fi
stop_steam_ime
if [ -n "${ime_text_pid:-}" ]; then
kill "$ime_text_pid" 2>/dev/null || true
wait "$ime_text_pid" 2>/dev/null || true
ime_text_pid=
fi
if [ -n "${DD_DESKTOP:-}" ]; then
if [ -n "${decky_supervisor:-}" ]; then
kill "$decky_supervisor" 2>/dev/null || true
+7
View File
@@ -0,0 +1,7 @@
#!/bin/bash
[ -n "${IBUS_ADDRESS:-}" ] || exit 0
unset LD_PRELOAD LD_LIBRARY_PATH GSETTINGS_SCHEMA_DIR
export LD_LIBRARY_PATH=/usr/local/lib/droiddeck-ime
export DCONF_PROFILE=/usr/local/share/droiddeck/ibus.profile
exec /usr/bin/ibus-daemon --address "$IBUS_ADDRESS" --panel disable --config default \
--emoji-extension disable --cache none
@@ -162,7 +162,7 @@ def windows_path(unix):
def bionic_tool(proton):
if not proton or not os.environ.get("DDNATV_ROOT"):
if not proton:
return None
tool = Path(proton).parent
return str(tool / "proton") if (tool / "bionic" / "launch.sh").is_file() else None
+510
View File
@@ -0,0 +1,510 @@
#!/usr/bin/python3
"""Deliver committed Android IME text to the focused X11 client."""
import ctypes
import ctypes.util
import errno
import os
import select
import signal
import socket
import stat
import struct
import sys
MAX_TEXT = 65536
CANCELLABLE = 1 << 31
CLIENT_TIMEOUT = 2.0
PROBE_TIMEOUT = 0.5
FOCUS_PROPERTY = b'GAMESCOPE_KEYBOARD_FOCUS_DISPLAY'
ANY_PROPERTY_TYPE = 0
PROPERTY_WORDS = 1024
PR_SET_PDEATHSIG = 1
UNICODE_KEYSYM_FLAG = 0x01000000
X11_SPECIAL_KEYSYMS = {
'\r': 0xff0d, # XK_Return
'\n': 0xff0d, # XK_Return
'\b': 0xff08, # XK_BackSpace
'\u007f': 0xffff, # XK_Delete
'\t': 0xff09, # XK_Tab
}
_STOP = False
class XModifierKeymap(ctypes.Structure):
_fields_ = [('max_keypermod', ctypes.c_int),
('modifiermap', ctypes.POINTER(ctypes.c_ubyte))]
class _DisplayState:
"""Keep mappings stable until shutdown because clients may decode key events later."""
__slots__ = ('handle', 'codes', 'owned')
def __init__(self, handle):
self.handle = handle
self.codes = {} # keysym -> keycode, stable for the session
self.owned = {} # keycode -> (width, original row) for shutdown restore
class XBridge:
def __init__(self):
self.lib = ctypes.CDLL(ctypes.util.find_library('X11') or 'libX11.so.6')
self.xtst = ctypes.CDLL(ctypes.util.find_library('Xtst') or 'libXtst.so.6')
self._open_displays = {}
self._declare()
def _declare(self):
lib = self.lib
lib.XOpenDisplay.argtypes = [ctypes.c_char_p]
lib.XOpenDisplay.restype = ctypes.c_void_p
lib.XCloseDisplay.argtypes = [ctypes.c_void_p]
lib.XCloseDisplay.restype = ctypes.c_int
lib.XDefaultRootWindow.argtypes = [ctypes.c_void_p]
lib.XDefaultRootWindow.restype = ctypes.c_ulong
lib.XInternAtom.argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_int]
lib.XInternAtom.restype = ctypes.c_ulong
lib.XGetWindowProperty.argtypes = [
ctypes.c_void_p, ctypes.c_ulong, ctypes.c_ulong, ctypes.c_long, ctypes.c_long,
ctypes.c_int, ctypes.c_ulong, ctypes.POINTER(ctypes.c_ulong),
ctypes.POINTER(ctypes.c_int), ctypes.POINTER(ctypes.c_ulong),
ctypes.POINTER(ctypes.c_ulong), ctypes.POINTER(ctypes.c_void_p)]
lib.XGetWindowProperty.restype = ctypes.c_int
lib.XFree.argtypes = [ctypes.c_void_p]
lib.XFree.restype = ctypes.c_int
lib.XDisplayKeycodes.argtypes = [ctypes.c_void_p, ctypes.POINTER(ctypes.c_int),
ctypes.POINTER(ctypes.c_int)]
lib.XDisplayKeycodes.restype = ctypes.c_int
lib.XGetKeyboardMapping.argtypes = [ctypes.c_void_p, ctypes.c_ubyte, ctypes.c_int,
ctypes.POINTER(ctypes.c_int)]
lib.XGetKeyboardMapping.restype = ctypes.POINTER(ctypes.c_ulong)
lib.XChangeKeyboardMapping.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_int,
ctypes.POINTER(ctypes.c_ulong), ctypes.c_int]
lib.XChangeKeyboardMapping.restype = ctypes.c_int
lib.XSync.argtypes = [ctypes.c_void_p, ctypes.c_int]
lib.XSync.restype = ctypes.c_int
lib.XQueryKeymap.argtypes = [ctypes.c_void_p, ctypes.c_void_p]
lib.XQueryKeymap.restype = ctypes.c_int
lib.XGetModifierMapping.argtypes = [ctypes.c_void_p]
lib.XGetModifierMapping.restype = ctypes.POINTER(XModifierKeymap)
lib.XFreeModifiermap.argtypes = [ctypes.POINTER(XModifierKeymap)]
lib.XFreeModifiermap.restype = ctypes.c_int
self.xtst.XTestFakeKeyEvent.argtypes = [ctypes.c_void_p, ctypes.c_uint, ctypes.c_int,
ctypes.c_ulong]
self.xtst.XTestFakeKeyEvent.restype = ctypes.c_int
def state(self, name):
existing = self._open_displays.get(name)
if existing is not None:
return existing
handle = self.lib.XOpenDisplay(name.encode())
if not handle:
return None
state = _DisplayState(handle)
self._open_displays[name] = state
return state
def display(self, name):
state = self.state(name)
return state.handle if state else None
def close(self):
for state in self._open_displays.values():
for keycode, (width, original) in state.owned.items():
row = (ctypes.c_ulong * width)(*original)
self.lib.XChangeKeyboardMapping(state.handle, keycode, width, row, 1)
self.lib.XSync(state.handle, 0)
self.lib.XCloseDisplay(state.handle)
self._open_displays.clear()
def target_display(self):
main = os.environ.get('DISPLAY', '').strip()
if not main:
return None
game = os.environ.get('STEAM_GAME_DISPLAY_0', '').strip()
if not game or game == main:
return main
main_display = self.display(main)
if not main_display:
return None
focused = self._focused_display(main_display)
if focused == game:
return game
if focused == main:
return main
return None
def _focused_display(self, display):
root = self.lib.XDefaultRootWindow(display)
atom = self.lib.XInternAtom(display, FOCUS_PROPERTY, 0)
if not atom:
return None
actual_type = ctypes.c_ulong(0)
actual_format = ctypes.c_int(0)
items = ctypes.c_ulong(0)
remaining = ctypes.c_ulong(0)
data = ctypes.c_void_p()
status = self.lib.XGetWindowProperty(
display, root, atom, 0, PROPERTY_WORDS, 0, ANY_PROPERTY_TYPE,
ctypes.byref(actual_type), ctypes.byref(actual_format), ctypes.byref(items),
ctypes.byref(remaining), ctypes.byref(data))
if status != 0 or not data or not items.value:
if data:
self.lib.XFree(data)
return None
try:
raw = _property_bytes(data, actual_format.value, items.value)
finally:
self.lib.XFree(data)
if raw is None:
return None
raw = raw.split(b'\0', 1)[0]
if not raw:
return None
try:
return raw.decode('ascii')
except UnicodeDecodeError:
return None
def keymap(self, display):
lowest = ctypes.c_int(0)
highest = ctypes.c_int(0)
self.lib.XDisplayKeycodes(display, ctypes.byref(lowest), ctypes.byref(highest))
if lowest.value < 0 or highest.value < lowest.value:
return None
count = highest.value - lowest.value + 1
width = ctypes.c_int(0)
symbols = self.lib.XGetKeyboardMapping(display, lowest.value, count, ctypes.byref(width))
if not symbols:
return None
if width.value <= 0:
self.lib.XFree(ctypes.cast(symbols, ctypes.c_void_p))
return None
rows = [[symbols[index * width.value + level] for level in range(width.value)]
for index in range(count)]
self.lib.XFree(ctypes.cast(symbols, ctypes.c_void_p))
return lowest.value, width.value, rows
def held_keys(self, display):
state = ctypes.create_string_buffer(32)
if not self.lib.XQueryKeymap(display, ctypes.cast(state, ctypes.c_void_p)):
return set()
raw = state.raw
return {keycode for keycode in range(len(raw) * 8)
if raw[keycode >> 3] >> (keycode & 7) & 1}
def modifier_keys(self, display):
mapping = self.lib.XGetModifierMapping(display)
if not mapping:
return set()
try:
width = mapping.contents.max_keypermod
keys = mapping.contents.modifiermap
return {keys[index] for index in range(8 * width) if keys[index]}
finally:
self.lib.XFreeModifiermap(mapping)
def empty_rows(self, display, reserved):
keymap = self.keymap(display)
if keymap is None:
return []
lowest, width, rows = keymap
held = self.held_keys(display)
modifiers = self.modifier_keys(display)
available = []
for index in range(len(rows) - 1, -1, -1):
keycode = lowest + index
if keycode < 8 or keycode > 255 or keycode in held or keycode in modifiers:
continue
if keycode in reserved:
continue
row = rows[index]
if any(row):
continue
available.append((keycode, width, tuple(row)))
return available
def type_text(self, state, text, cancelled=None):
"""Reserve all required mappings before injecting any part of a frame."""
handle = state.handle
needed = []
seen = set()
for character in text:
keysym = _character_keysym(character)
if keysym not in seen:
seen.add(keysym)
needed.append(keysym)
missing = [keysym for keysym in needed if keysym not in state.codes]
if missing:
available = self.empty_rows(handle, set(state.codes.values()))
if len(available) < len(missing):
_log_capacity_exhausted()
return False
for keysym, (keycode, width, original) in zip(missing, available):
row = (ctypes.c_ulong * width)(*[keysym] * width)
# XChangeKeyboardMapping queues the request and returns 0.
self.lib.XChangeKeyboardMapping(handle, keycode, width, row, 1)
state.codes[keysym] = keycode
state.owned[keycode] = (width, original)
self.lib.XSync(handle, 0)
for character in text:
if _STOP:
return False
if cancelled is not None and cancelled():
return False
keycode = state.codes[_character_keysym(character)]
if not self._tap(handle, keycode):
return False
return True
def _tap(self, handle, keycode):
pressed = False
try:
if not self.xtst.XTestFakeKeyEvent(handle, keycode, 1, 0):
return False
pressed = True
self.lib.XSync(handle, 0)
if not self.xtst.XTestFakeKeyEvent(handle, keycode, 0, 0):
return False
pressed = False
self.lib.XSync(handle, 0)
finally:
if pressed:
self.xtst.XTestFakeKeyEvent(handle, keycode, 0, 0)
self.lib.XSync(handle, 0)
return True
def _character_keysym(character):
keysym = X11_SPECIAL_KEYSYMS.get(character)
if keysym is not None:
return keysym
codepoint = ord(character)
return codepoint if codepoint < 256 else UNICODE_KEYSYM_FLAG | codepoint
def _log_capacity_exhausted():
try:
sys.stderr.write('droiddeck-text-input: not enough empty keycodes for this frame\n')
sys.stderr.flush()
except OSError:
pass
def _property_bytes(data, actual_format, items):
if actual_format == 8:
return ctypes.string_at(data, items)
if actual_format == 32:
# Xlib exposes format-32 property items as native longs, including on 64-bit systems.
words = ctypes.cast(data, ctypes.POINTER(ctypes.c_ulong))
return b''.join(struct.pack('<I', words[index] & 0xffffffff)
for index in range(items))
return None
def _recv_exact(connection, count):
chunks = []
remaining = count
while remaining > 0:
try:
chunk = connection.recv(remaining)
except OSError:
return None
if not chunk:
return None
chunks.append(chunk)
remaining -= len(chunk)
return b''.join(chunks)
def read_request(connection):
header = _recv_exact(connection, 4)
if header is None:
return None
raw = struct.unpack('>I', header)[0]
cancellable = bool(raw & CANCELLABLE)
length = raw & ~CANCELLABLE
if length < 1 or length > MAX_TEXT:
return None
body = _recv_exact(connection, length)
if body is None:
return None
if b'\0' in body:
return None
try:
return body.decode('utf-8'), cancellable
except UnicodeDecodeError:
return None
def answer(connection, accepted):
try:
connection.sendall(b'\x01' if accepted else b'\x00')
connection.shutdown(socket.SHUT_WR)
except OSError:
return
# Drain unread bytes so close() does not reset the connection after the ACK.
try:
connection.settimeout(0.2)
while connection.recv(4096):
pass
except OSError:
pass
def _cancellation_probe(connection):
"""Return a predicate that is true once the peer has cancelled a flagged frame.
After the full frame has been read, any readable event (POLLIN/POLLHUP/POLLERR)
means extra data, half-close or reset - all of which are cancellation for a
cancellable client.
"""
poller = select.poll()
poller.register(connection, select.POLLIN)
return lambda: bool(poller.poll(0))
def deliver(bridge, text, cancelled=None):
if cancelled is not None and cancelled():
return False
target = bridge.target_display()
if target is None:
return False
state = bridge.state(target)
if state is None:
return False
return bridge.type_text(state, text, cancelled)
def serve_connection(connection, bridge):
connection.settimeout(CLIENT_TIMEOUT)
request = read_request(connection)
accepted = False
if request is not None:
text, cancellable = request
cancelled = _cancellation_probe(connection) if cancellable else None
try:
accepted = deliver(bridge, text, cancelled)
except Exception:
accepted = False
answer(connection, accepted)
def _identity(path):
try:
info = os.stat(path)
except OSError:
return None
return info.st_dev, info.st_ino
def _release(path, owned):
if owned is None:
return
try:
info = os.lstat(path)
except OSError:
return
if stat.S_ISSOCK(info.st_mode) and (info.st_dev, info.st_ino) == owned:
try:
os.unlink(path)
except OSError:
pass
def serve(path, bridge):
if not _remove_stale(path):
print("droiddeck-text-input: refusing to replace %s" % path, file=sys.stderr)
return 1
server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
owned = None
try:
server.bind(path)
os.chmod(path, 0o600)
server.listen(8)
server.setblocking(False)
owned = _identity(path)
while not _STOP:
try:
ready, _, _ = select.select([server], [], [], 0.25)
except OSError:
break
if not ready:
continue
try:
connection, _ = server.accept()
except OSError:
if _STOP:
break
continue
try:
serve_connection(connection, bridge)
finally:
connection.close()
finally:
server.close()
_release(path, owned)
return 0
def _remove_stale(path):
try:
info = os.lstat(path)
except FileNotFoundError:
return True
except OSError:
return False
if not stat.S_ISSOCK(info.st_mode):
return False
probe = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
try:
probe.settimeout(PROBE_TIMEOUT)
probe.connect(path)
except OSError as error:
if error.errno == errno.ENOENT:
return True
if error.errno != errno.ECONNREFUSED:
return False
else:
return False
finally:
probe.close()
_release(path, (info.st_dev, info.st_ino))
return True
def _stop(signum, frame):
global _STOP
_STOP = True
def _adopt_parent_death():
parent = os.getppid()
try:
libc = ctypes.CDLL(None, use_errno=True)
libc.prctl.argtypes = [ctypes.c_int, ctypes.c_ulong, ctypes.c_ulong, ctypes.c_ulong,
ctypes.c_ulong]
libc.prctl.restype = ctypes.c_int
libc.prctl(PR_SET_PDEATHSIG, signal.SIGTERM, 0, 0, 0)
except (OSError, AttributeError):
return True
return os.getppid() == parent and parent > 1
def main(argv):
if len(argv) != 2 or not argv[1]:
return 2
if not _adopt_parent_death():
return 0
os.umask(0o077)
for name in ('SIGTERM', 'SIGINT', 'SIGHUP'):
signal.signal(getattr(signal, name), _stop)
bridge = XBridge()
try:
return serve(argv[1], bridge)
finally:
bridge.close()
if __name__ == '__main__':
sys.exit(main(sys.argv))
@@ -28,6 +28,19 @@ CLASSES = {
'Windows.Storage.Streams.DataWriter'),
}
CLASS_KEY = 'Software\\Microsoft\\WindowsRuntime\\ActivatableClassId\\'
# Microsoft's original Xbox releases for PC install GameInputRedist.msi. The emulator needs the GameInput it installs
# (Wine's builtin one lacks the interface it asks for), but through the GameInputService class it registers that
# GameInput starts a service needing Windows notification calls Wine lacks, and the emulator then stops with "Gaming
# Services must be installed". Without the class it runs the redistributable's GameInput in process.
BACK_COMPAT_IDENTITY = 'xbox360backwardcompatibil'
# droiddeck-game-env gives these games the emulator's switches and faster FEX settings. Their install actions run
# without the switches and with FEX's full memory ordering and x87 precision: under the faster settings
# GameInputRedist.msi's 32-bit msiexec spun a core and never finished.
EMULATOR_SWITCHES = ('WINE_SPECIAL_APC_INTERRUPT', 'WINE_MF_DISPLAY_APERTURE', 'WINE_PRECISE_SLEEP', 'FEX_SYNCX87CONTEXT',
'FEX_LOOPSUSPENDCHECK', 'FEX_SAFEIMAGEMAP', 'VKD3D_INTEROP_PRESENT', 'VKD3D_PACKED_422')
INSTALLER_FEX = {'FEX_TSOENABLED': '1', 'FEX_VECTORTSOENABLED': '1', 'FEX_MEMCPYSETTSOENABLED': '1',
'FEX_HALFBARRIERTSOENABLED': '1', 'FEX_X87REDUCEDPRECISION': '0'}
GAMEINPUT_SERVICE = 'Software\\Classes\\CLSID\\{B773D0F8-01F8-41E7-9F23-6871DA0AACFF}'
VIEW_DRIVES = 'xwvutsrqponmlkjihgfe'
@@ -145,8 +158,21 @@ def game_config(exe):
return None
for folder in list(path.parents)[:4]:
config = folder / 'MicrosoftGame.config'
if config.is_file():
return config
if not config.is_file():
# The Xbox store accepts the file name in any case (XboxManifest.read).
try:
config = next((entry for entry in sorted(folder.iterdir())
if entry.name.lower() == 'microsoftgame.config' and entry.is_file()), None)
except OSError:
config = None
if config is None:
continue
# As in droiddeck-game-env, a manifest that does not parse gives way to one in a parent folder.
try:
ElementTree.fromstring(config.read_bytes())
except (OSError, ElementTree.ParseError):
continue
return config
return None
@@ -186,6 +212,40 @@ def windows_arguments(text):
return arguments
def back_compat(config):
try:
root = ElementTree.fromstring(config.read_bytes())
except (OSError, ElementTree.ParseError):
return False
return any(node.tag.rsplit('}', 1)[-1] == 'Identity' and node.get('Name', '').lower().startswith(BACK_COMPAT_IDENTITY)
for node in root.iter())
def remove_gameinput_service(proton, prefix, env, installed=False):
# Just after an install action Wine may not have written system.reg yet; reg.exe sees its registry either way.
if not installed:
try:
registry = (prefix / 'system.reg').read_text(encoding='utf-8', errors='replace')
except OSError:
return
if '[%s]' % GAMEINPUT_SERVICE.replace('\\', '\\\\').lower() not in registry.lower():
return
try:
code = subprocess.run([proton, 'run', 'reg.exe', 'delete', 'HKLM\\' + GAMEINPUT_SERVICE, '/f'],
stdout=sys.stderr, env=env, timeout=90).returncode
except subprocess.TimeoutExpired:
print('droiddeck-xbox: GameInput service class could not be removed (reg.exe timed out); launching with it',
file=sys.stderr)
return
except OSError as e:
print('droiddeck-xbox: GameInput service class could not be removed (%s); launching with it' % (e.strerror or e),
file=sys.stderr)
return
# reg.exe fails when the key is absent, which after an install action only means the action registered no class.
if code != 0 and not installed:
print('droiddeck-xbox: GameInput service class could not be removed; launching with it', file=sys.stderr)
def install_actions(config):
try:
root = ElementTree.fromstring(config.read_bytes())
@@ -218,6 +278,10 @@ def run_install_actions(proton, prefix, exe, env):
if config is None:
return
done = prefix / 'drive_c' / 'ProgramData' / 'DroidDeck' / 'install-actions'
original_xbox = back_compat(config)
if original_xbox:
env = dict({k: v for k, v in env.items() if k not in EMULATOR_SWITCHES}, **INSTALLER_FEX)
installed = False
for name, target, arguments in install_actions(config):
try:
content = hashlib.sha256()
@@ -243,11 +307,14 @@ def run_install_actions(proton, prefix, exe, env):
if code != 0:
print('droiddeck-xbox: install action %s did not finish; launching without it' % name, file=sys.stderr)
continue
installed = True
try:
done.mkdir(parents=True, exist_ok=True)
marker.touch()
except OSError as error:
print('droiddeck-xbox: install action %s finished but could not be recorded (%s)' % (name, error), file=sys.stderr)
if original_xbox:
remove_gameinput_service(proton, prefix, env, installed)
def view_drive(prefix, exe):
@@ -318,6 +318,74 @@ dd_vacdiag() {
}
"""
DD_ANTICHEAT_SETUP = """
dd_anticheat_runtime() {
local current=$1 name=$2 bridge=$3 library
if [ -n "$current" ] && [ -n "$(find -L "$current" -iname "$bridge" -print -quit 2>/dev/null)" ]; then
printf '%s' "$current"; return 0
fi
while IFS= read -r library; do
[ -n "$(find "$library/steamapps/common/$name" -iname "$bridge" -print -quit 2>/dev/null)" ] || continue
printf '%s' "$library/steamapps/common/$name"; return 0
done < <(printf '%s\\n' "$DD_AC_ROOT" /mnt/droiddeck-sd; sed -n 's/^[[:space:]]*"path"[[:space:]]*"\\(.*\\)"[[:space:]]*$/\\1/p' "$DD_AC_ROOT/steamapps/libraryfolders.vdf" 2>/dev/null)
return 1
}
dd_x86_64_proton() {
[ -d "$1/files/lib/wine/x86_64-unix" ] && [ ! -d "$1/files/bin-arm64" ]
}
dd_anticheat() {
case ${verb:-} in waitforexitandrun | run) ;; *) return 0 ;; esac
case ${DROIDDECK_ANTICHEAT:-auto} in off | 0 | false) return 0 ;; esac
local game=${STEAM_COMPAT_INSTALL_PATH:-} found markers eac battleye tool runtime=
[ -d "$game" ] || return 0
markers=$(find "$game" -maxdepth 5 \\( -ipath '*/easyanticheat/settings.json' -o -iname 'easyanticheat_x64.so' \\
-o -iname 'beclient_x64.so' -o -iname 'beservice_x64.exe' \\) -print 2>/dev/null)
eac=$(printf '%s\\n' "$markers" | grep -i easyanticheat | head -n 1)
battleye=$(printf '%s\\n' "$markers" | grep -iv easyanticheat | grep . | head -n 1)
found=${eac:-$battleye}
[ -n "$found" ] || return 0
case ${DD_AC_TOOL:-DroidDeck-Proton} in
DroidDeck-Proton*) ;;
*)
echo "droiddeck-proton: anti-cheat files in ${found#$game/}; ${DD_AC_TOOL} was chosen for this game, so it runs as chosen" >&2
return 0
;;
esac
/usr/local/bin/droiddeck-fex update || true
if ! grep -qx fixed-guest-memory-above-host-address-limit /usr/local/share/fex-emu/.droiddeck-patches 2>/dev/null; then
echo "droiddeck-proton: anti-cheat files in ${found#$game/}; the installed FEX build cannot run anti-cheat, so this launch stays on ARM64" >&2
return 0
fi
DD_AC_ROOT=${STEAM_COMPAT_CLIENT_INSTALL_PATH:-${XDG_DATA_HOME:-$HOME/.local/share}/Steam}
tool=$(cd "$DD_AC_ROOT/compatibilitytools.d" 2>/dev/null && for d in DroidDeck-Proton*; do
[ -x "$d/proton" ] && dd_x86_64_proton "$d" && printf '%s/%s\\n' "$PWD" "$d"
done | sort -V | tail -n 1)
if [ -z "$tool" ]; then
echo "droiddeck-proton: anti-cheat files in ${found#$game/}; no x86-64 DroidDeck-Proton is installed, so this launch stays on ARM64" >&2
return 0
fi
if [ -n "$eac" ] && runtime=$(dd_anticheat_runtime "${PROTON_EAC_RUNTIME:-}" "Proton EasyAntiCheat Runtime" easyanticheat_x64.so); then
export PROTON_EAC_RUNTIME="$runtime"
found=$eac
elif [ -n "$battleye" ] && runtime=$(dd_anticheat_runtime "${PROTON_BATTLEYE_RUNTIME:-}" "Proton BattlEye Runtime" beclient_x64.so); then
export PROTON_BATTLEYE_RUNTIME="$runtime"
found=$battleye
else
runtime=
fi
if [ -z "$runtime" ]; then
echo "droiddeck-proton: anti-cheat files in ${found#$game/}; its Proton runtime is not installed, so this launch stays on ARM64" >&2
return 0
fi
dd_game_cpus
declare -F dd_components >/dev/null && dd_components "$tool"
echo "droiddeck-proton: anti-cheat files in ${found#$game/}; running ${tool##*/} under FEX" >&2
exec ${DD_TASKSET:-} /usr/local/bin/droiddeck-fex proton "$tool/proton" "$verb" "$@"
}
"""
DD_DRIVER_QUERY_SKIP = """
case "$verb:${1##*/}:${STEAM_COMPAT_DATA_PATH%/}" in
run:d3ddriverquery64.exe:*/compatdata/0 | run:d3ddriverquery.exe:*/compatdata/0)
@@ -437,6 +505,7 @@ for name in %s; do
[ -n "$depot" ] && break
done
if [ -n "$depot" ]; then
dd_anticheat "$@"
dd_components "$depot"
dd_directaudio "$depot" "$@"
dd_game_cpus
@@ -457,7 +526,7 @@ LAUNCHER_TEMPLATE = LAUNCHER_SH
def launcher_sh(sources=SOURCES):
return (LAUNCHER_TEMPLATE % " ".join('"%s"' % n for n in sources)).replace(
"verb=$1; shift", "verb=$1; shift\n" + DD_DRIVER_QUERY_SKIP + DD_DESKTOP_GPU_SETUP + DD_DIRECTAUDIO_SETUP + DD_GAME_CPUS_SETUP + DD_IDTECH3_SETUP
+ DD_VACDIAG_SETUP + DD_COMPONENTS_SETUP + DD_LIBPATH_SETUP + DD_STORE_SETUP, 1)
+ DD_VACDIAG_SETUP + DD_COMPONENTS_SETUP + DD_LIBPATH_SETUP + DD_STORE_SETUP + DD_ANTICHEAT_SETUP, 1)
LAUNCHER_SH = launcher_sh()
@@ -485,6 +554,11 @@ for fake in /usr/local/lib/libfakeinput.so /usr/local/lib/libddsession.so; do
esac
fi
done
if dd_x86_64_proton "$here"; then
dd_game_cpus
exec ${DD_TASKSET:-} /usr/local/bin/droiddeck-fex proton "$here/%s" "$verb" "$@"
fi
DD_AC_TOOL=$(basename "$(cd "$here" && pwd -P)") dd_anticheat "$@"
dd_components "$here"
dd_directaudio "$here" "$@"
dd_game_cpus
@@ -499,9 +573,9 @@ dd_run ${DD_TASKSET:-} /usr/local/bin/droiddeck-game-env "$DD_STORE_PROTON" "$ve
def extra_wrapper_sh(entry_point):
return (EXTRA_WRAPPER_SH % entry_point).replace(
return (EXTRA_WRAPPER_SH % (entry_point, entry_point)).replace(
'here=$(dirname "$0")',
'here=$(dirname "$0")\n' + DD_DRIVER_QUERY_SKIP + DD_DESKTOP_GPU_SETUP + DD_DIRECTAUDIO_SETUP + DD_GAME_CPUS_SETUP
'here=$(dirname "$0")\n' + DD_ANTICHEAT_SETUP + DD_DRIVER_QUERY_SKIP + DD_DESKTOP_GPU_SETUP + DD_DIRECTAUDIO_SETUP + DD_GAME_CPUS_SETUP
+ DD_IDTECH3_SETUP + DD_VACDIAG_SETUP + DD_COMPONENTS_SETUP + DD_LIBPATH_SETUP + DD_STORE_SETUP, 1)
@@ -1301,10 +1375,18 @@ def tool_catalog(steam_root, extras=None):
continue
extras[first_key(os.path.join(tool_dir, "compatibilitytool.vdf"), ["compatibilitytools", "compat_tools"]) or entry] = entry
for name, entry in sorted(extras.items()):
catalog.append(tool_entry(name, display_name(entry), os.path.join(tools, entry), False))
tool = tool_entry(name, display_name(entry), os.path.join(tools, entry), False)
if x86_64_layout(os.path.join(tools, entry)):
tool["x86_64"] = True
catalog.append(tool)
return catalog
def x86_64_layout(path):
return (os.path.isdir(os.path.join(path, "files", "lib", "wine", "x86_64-unix")) and
not os.path.isdir(os.path.join(path, "files", "bin-arm64")))
def built_from(name, catalog, runnable=None):
depot = VALVE_DEPOTS.get(name)
tools = [t["name"] for t in catalog if depot and t["valve"] and t["dir"] == depot and
@@ -1443,7 +1525,7 @@ ARCH_WORDS = re.compile(r"(?i)aarch64|arm64|x86_64|x86-64|amd64")
def own_builds(tools):
return [t for t in tools if isinstance(t, dict) and not t.get("valve") and
isinstance(t.get("dir"), str) and t["dir"].startswith(OWN_PROTON) and t.get("name")]
isinstance(t.get("dir"), str) and t["dir"].startswith(OWN_PROTON) and t.get("name") and not t.get("x86_64")]
def build_key(name):
@@ -1481,7 +1563,8 @@ def choose_default(steam_default, state, request, catalog, adopt_steam=True, app
wanted = requested_tool(request, catalog)
state["applied"] = seq
if wanted:
if wanted != state.get("default"):
if wanted != state.get("default") or (state.get("source") not in ("app", "steam") and any(
t["name"] == wanted and t.get("x86_64") for t in catalog)):
state.update(default=wanted, seq=now or now_ms(), source="app")
else:
print("steam-compatibility: the app asked for %s, which is not installed; kept %s" % (
@@ -1678,7 +1761,11 @@ def register_default(config_path, apps=(), protect=(), default=None, catalog=Non
read_json(state_path("request.json", directory)), catalog)
else:
default = state.get("default") if state.get("default") in names else TOOL
if settle and newest and default == TOOL and state.get("source") not in ("app", "steam"):
automatic = state.get("source") not in ("app", "steam")
if settle and automatic and default in {t["name"] for t in catalog if t.get("x86_64")}:
default = newest or TOOL
state.update(default=default, seq=now_ms(), source="update")
elif settle and newest and default == TOOL and automatic:
default = newest
state.update(default=newest, seq=now_ms(), source="update")
state.pop("own_proton", None)
+2 -1
View File
@@ -957,8 +957,9 @@ __attribute__((visibility("hidden"))) void dd_vdec_closed(int fd) {
__attribute__((visibility("hidden"))) int dd_vdec_poll(struct pollfd *fds, nfds_t n, int timeout_ms,
int (*real)(struct pollfd *, nfds_t, int), int *ret) {
if (n != 1 || vd_find(fds[0].fd) == NULL) return 0;
if (n != 1 || __atomic_load_n(&vd_open_count, __ATOMIC_ACQUIRE) == 0) return 0;
struct vdec *v = vd_find(fds[0].fd);
if (v == NULL) return 0;
pthread_mutex_lock(&vd_lock);
short ready = (v->n_cap_done ? POLLIN | POLLRDNORM : 0) | (v->n_out_done ? POLLOUT | POLLWRNORM : 0);
pthread_mutex_unlock(&vd_lock);
+31
View File
@@ -5,6 +5,7 @@
#include <pthread.h>
#include <sched.h>
#include <signal.h>
#include <stdarg.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
@@ -18,6 +19,9 @@
#include <unistd.h>
#ifndef PR_SET_SYSCALL_USER_DISPATCH
#define PR_SET_SYSCALL_USER_DISPATCH 59
#endif
#ifndef MADV_PAGEOUT
#define MADV_PAGEOUT 21
#endif
@@ -538,13 +542,40 @@ static int zr_start(void) {
return 0;
}
static __thread volatile unsigned char *zr_dispatch __attribute__((tls_model("initial-exec")));
int prctl(int option, ...) {
va_list ap;
va_start(ap, option);
unsigned long arg2 = va_arg(ap, unsigned long);
unsigned long arg3 = va_arg(ap, unsigned long);
unsigned long arg4 = va_arg(ap, unsigned long);
unsigned long arg5 = va_arg(ap, unsigned long);
va_end(ap);
volatile unsigned char *dispatch = zr_dispatch;
unsigned char selector = dispatch != NULL ? *dispatch : 0;
if (selector) *dispatch = 0;
long result = zr_sys(SYS_prctl, option, arg2, arg3, arg4, arg5);
if (selector) *dispatch = selector;
if ((unsigned long)result > -4096UL) {
errno = (int)-result;
return -1;
}
if (option == PR_SET_SYSCALL_USER_DISPATCH) zr_dispatch = arg2 ? (volatile unsigned char *)arg5 : NULL;
return (int)result;
}
static void zr_handler(int sig, siginfo_t *info, void *context) {
(void)sig;
(void)context;
if (info == NULL || info->si_code != SI_USER) return;
volatile unsigned char *dispatch = zr_dispatch;
unsigned char selector = dispatch != NULL ? *dispatch : 0;
if (selector) *dispatch = 0;
int saved = errno;
if (__atomic_fetch_add(&zr_requests, 1, __ATOMIC_ACQ_REL) == 0 && !zr_start()) zr_drain(0);
errno = saved;
if (selector) *dispatch = selector;
}
static void zr_child(void) {