chore: merge main to resolve conflicts with the API 36 target

This commit is contained in:
xXJsonDeruloXx committed 2026-10-18 16:09:55 -04:00
commit 4a93663d14
793 files changed
+103885 -10000

No files matched your search

+17 -6
View File
@@ -26,7 +26,7 @@ for arch in x86_64 i386; do
fi
done
done
for target in x86_64/faultreport i386/faultreport x86_64/thunkaudit; do
for target in x86_64/faultreport i386/faultreport; do
arch=${target%/*} name=${target#*/}
case $arch in
x86_64) bits=-m64 ;;
@@ -41,13 +41,24 @@ for target in x86_64/faultreport i386/faultreport x86_64/thunkaudit; do
exit 1
fi
done
lib=$out/x86_64/libwebkitinput.so
gcc -m64 -shared -fPIC -O2 -Wall -Wextra -nostdlib -fno-stack-protector -fno-builtin -fvisibility=hidden \
-o "$lib" tools/linuxfs/fex/webkitinput.c
strip --strip-unneeded "$lib"
if objdump -p "$lib" | grep -q NEEDED || [ "$(nm -D --undefined-only "$lib" | awk '{print $1 $2}' | LC_ALL=C sort | tr '\n' ' ')" != "wdlsym wg_object_get_data wg_object_set wg_object_set_data wg_type_check_instance_is_a wgtk_container_forall wgtk_container_get_type wgtk_key_snooper_install wgtk_widget_get_toplevel wwebkit_user_script_new wwebkit_user_script_unref wwebkit_web_view_get_type wwebkit_web_view_get_uri wwebkit_web_view_run_javascript " ]; then
echo "$lib must need nothing but weak GLib, GTK and WebKit calls" >&2
exit 1
fi
stub=$(mktemp -d)
gcc -m64 -shared -nostdlib -Wl,-soname,/usr/lib/x86_64-linux-gnu/libvulkan.so.1 -o "$stub/libvulkan.so.1" -x c /dev/null
gcc -m64 -shared -nostdlib -Wl,-z,nodelete -Wl,--no-as-needed \
-o "$out/x86_64/libvulkan-thunk.so" -x c /dev/null -x none "$stub/libvulkan.so.1"
lib=$out/x86_64/libvulkan-thunk.so
gcc -m64 -shared -fPIC -O2 -Wall -Wextra -fvisibility=hidden -Wl,-soname,libvulkan.so.1 -Wl,-z,nodelete -Wl,--no-as-needed \
-o "$lib" tools/linuxfs/fex/vulkanpin.c "$stub/libvulkan.so.1" -ldl
rm -rf "$stub"
if ! objdump -p "$out/x86_64/libvulkan-thunk.so" | grep -q 'NEEDED *\/usr/lib/x86_64-linux-gnu/libvulkan\.so\.1$' \
|| ! objdump -p "$out/x86_64/libvulkan-thunk.so" | grep -q 'FLAGS_1 *0x0*8$'; then
echo "$out/x86_64/libvulkan-thunk.so must be nodelete and need only the Vulkan thunk" >&2
strip --strip-unneeded "$lib"
newest=$(objdump -T "$lib" | grep -o 'GLIBC_2\.[0-9]*' | sort -u -t. -k2,2n | tail -1)
if ! objdump -p "$lib" | grep -q 'NEEDED *\/usr/lib/x86_64-linux-gnu/libvulkan\.so\.1$' \
|| ! objdump -p "$lib" | grep -q 'FLAGS_1 *0x0*8$' || [ "${newest#GLIBC_2.}" -gt 31 ]; then
echo "$lib must be nodelete, need the Vulkan thunk and run on glibc 2.31" >&2
exit 1
fi
+9
View File
@@ -27,6 +27,15 @@ export BL_DESKTOP=1
ln -sf /usr/local/bin/droiddeck-steam-launch /usr/local/bin/steamdeck-steam 2>/dev/null
ln -sf /usr/local/bin/droiddeck-steam-shim /usr/local/bin/steam 2>/dev/null
python3 /usr/local/bin/droiddeck-desktop-games 2>&1 | sed 's/^/[games] /'
cat > /usr/share/applications/droiddeck-steam-x64.desktop <<'ENTRY'
[Desktop Entry]
Type=Application
Name=Steam x86-64 (FEX, experimental)
Comment=Valve's x86-64 Linux client under FEX, in its own home with its own login
Exec=qterminal -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-desktop-gpu 2>&1 | sed 's/^/[gpu] /'
-40
View File
@@ -1,40 +0,0 @@
#if !defined(__x86_64__)
#error thunkaudit is built for x86_64 guests only
#endif
#define LA_SER_ORIG 0x01
static const char vulkan_thunk[] = "/usr/lib/x86_64-linux-gnu/libvulkan.so.1";
static const char vulkan_pin[] = "/usr/lib/x86_64-linux-gnu/droiddeck/libvulkan-thunk.so";
static int same(const char *a, const char *b)
{
while (*a && *a == *b) {
a++;
b++;
}
return *a == *b;
}
static const char *base_name(const char *path)
{
const char *name = path;
for (; *path; path++)
if (*path == '/')
name = path + 1;
return name;
}
__attribute__((visibility("default"))) unsigned int la_version(unsigned int version)
{
return version;
}
__attribute__((visibility("default"))) char *la_objsearch(const char *name, unsigned long *cookie, unsigned int flag)
{
const char *file = base_name(name);
(void)cookie;
if (flag == LA_SER_ORIG && !same(name, vulkan_thunk) && (same(file, "libvulkan.so.1") || same(file, "libvulkan.so")))
return (char *)vulkan_pin;
return (char *)name;
}
+88
View File
@@ -0,0 +1,88 @@
#include <dlfcn.h>
#include <stddef.h>
#include <string.h>
#ifndef VULKAN_THUNK
#define VULKAN_THUNK "/usr/lib/x86_64-linux-gnu/libvulkan.so.1"
#endif
#define VK_INCOMPLETE 5
#define VK_ERROR_INITIALIZATION_FAILED (-3)
#define EXTENSIONS 128
typedef int VkResult;
typedef void (*Function)(void);
typedef struct {
char extensionName[256];
unsigned int specVersion;
} VkExtensionProperties;
typedef VkResult (*Enumerate)(const char *, unsigned int *, VkExtensionProperties *);
typedef Function (*ProcAddr)(void *, const char *);
/* The driver cannot enumerate devices for an instance with VK_KHR_display, and gamescope's WSI layer aborts on that. */
static const char *const hidden_extensions[] = {
"VK_KHR_display",
"VK_KHR_get_display_properties2",
"VK_EXT_direct_mode_display",
"VK_EXT_acquire_xlib_display",
"VK_EXT_acquire_drm_display",
"VK_EXT_display_surface_counter",
};
static void *thunk(const char *name)
{
void *library = dlopen(VULKAN_THUNK, RTLD_NOW | RTLD_NOLOAD);
void *found = library ? dlsym(library, name) : NULL;
if (library)
dlclose(library);
return found;
}
static int hidden(const char *name)
{
for (size_t i = 0; i < sizeof(hidden_extensions) / sizeof(hidden_extensions[0]); i++)
if (!strcmp(name, hidden_extensions[i]))
return 1;
return 0;
}
__attribute__((visibility("default"))) VkResult vkEnumerateInstanceExtensionProperties(const char *layer, unsigned int *count,
VkExtensionProperties *properties)
{
static Enumerate real;
VkExtensionProperties all[EXTENSIONS];
unsigned int total = EXTENSIONS, kept = 0, room = properties ? *count : 0;
VkResult result;
if (!real)
real = (Enumerate)thunk("vkEnumerateInstanceExtensionProperties");
if (!real)
return VK_ERROR_INITIALIZATION_FAILED;
result = real(layer, &total, all);
if (result < 0)
return result;
for (unsigned int i = 0; i < total; i++) {
if (hidden(all[i].extensionName))
continue;
if (properties && kept < room)
memcpy(&properties[kept], &all[i], sizeof(all[i]));
kept++;
}
if (!properties) {
*count = kept;
return result;
}
*count = kept < room ? kept : room;
return kept > room ? VK_INCOMPLETE : result;
}
__attribute__((visibility("default"))) Function vkGetInstanceProcAddr(void *instance, const char *name)
{
static ProcAddr real;
if (!strcmp(name, "vkGetInstanceProcAddr"))
return (Function)vkGetInstanceProcAddr;
if (!strcmp(name, "vkEnumerateInstanceExtensionProperties"))
return (Function)vkEnumerateInstanceExtensionProperties;
if (!real)
real = (ProcAddr)thunk("vkGetInstanceProcAddr");
return real ? real(instance, name) : NULL;
}
+198
View File
@@ -0,0 +1,198 @@
#if !defined(__x86_64__)
#error webkitinput is built for x86_64 guests only
#endif
typedef struct _WebKitSettings WebKitSettings;
typedef struct _WebKitUserContentManager WebKitUserContentManager;
typedef struct _WebKitUserScript WebKitUserScript;
extern void g_object_set(void *object, const char *first_property, ...) __attribute__((weak));
extern void *g_object_get_data(void *object, const char *key) __attribute__((weak));
extern void g_object_set_data(void *object, const char *key, void *data) __attribute__((weak));
extern void *dlsym(void *handle, const char *symbol) __attribute__((weak));
extern unsigned gtk_key_snooper_install(int (*snooper)(void *, void *, void *), void *data) __attribute__((weak));
extern void *gtk_widget_get_toplevel(void *widget) __attribute__((weak));
extern void gtk_container_forall(void *container, void (*callback)(void *, void *), void *data) __attribute__((weak));
extern unsigned long gtk_container_get_type(void) __attribute__((weak));
extern unsigned long webkit_web_view_get_type(void) __attribute__((weak));
extern int g_type_check_instance_is_a(void *instance, unsigned long type) __attribute__((weak));
extern const char *webkit_web_view_get_uri(void *view) __attribute__((weak));
extern void webkit_web_view_run_javascript(void *view, const char *script, void *cancellable, void *callback,
void *data) __attribute__((weak));
extern WebKitUserScript *webkit_user_script_new(const char *source, int frames, int time,
const char *const *allow, const char *const *block) __attribute__((weak));
extern void webkit_user_script_unref(WebKitUserScript *script) __attribute__((weak));
static const char NAV_SCRIPT[] =
"(()=>{let open=-1e9,arrowAt=-1e9,ringed=null,ringOutline='',ringOffset='',settleTimer=0,settling=false,redirecting=false;"
"const shown=()=>[...document.querySelectorAll('[role=dialog],[role=alertdialog],[aria-modal=true],[role=menu]')]"
".some(e=>e.getClientRects().length);"
"const hidden=e=>{const r=e.getBoundingClientRect();if(!r.width||!r.height)return true;"
"for(let n=e;n&&n.nodeType===1;n=n.parentElement){const s=getComputedStyle(n);"
"if(s.visibility==='hidden'||+s.opacity<0.1)return true;}return false;};"
"const windowButton=e=>/^(Minimize|Maximize|Restore|Close) window$/.test(e.getAttribute('aria-label')||'');"
"const editing=e=>!!e&&e.nodeType===1&&(e.isContentEditable||"
"e.matches('input:not([type=checkbox]):not([type=radio]):not([type=button]):not([type=submit]),textarea,select'));"
"const mainNav=()=>[...document.querySelectorAll('nav')].filter(n=>n.querySelectorAll('a[href]').length>1&&!hidden(n))"
".sort((a,b)=>a.getBoundingClientRect().y-b.getBoundingClientRect().y)[0];"
"const first=nav=>{const below=nav?nav.getBoundingClientRect().bottom:0,all=[];"
"for(const e of document.querySelectorAll('a[href],button,input,[role=button],[tabindex]')){"
"if(e.tabIndex<0||(nav&&nav.contains(e)))continue;const r=e.getBoundingClientRect();"
"if(r.top<below||r.bottom>innerHeight||windowButton(e)||hidden(e))continue;all.push({e,r});}"
"const big=all.filter(c=>c.r.width*c.r.height>=12000),list=big.length?big:all;"
"const key=c=>Math.round(c.r.top/8)*1e5+c.r.left;"
"list.sort((a,b)=>key(a)-key(b));return list.length?list[0].e:null;};"
"const big=e=>{const r=e.getBoundingClientRect();return r.width*r.height>=12000;};"
"const toward=(from,key,nav,small)=>{const r=from.getBoundingClientRect(),cx=r.left+r.width/2,cy=r.top+r.height/2;let best=null,score=1e9;"
"for(const c of document.querySelectorAll('a[href],button,[role=button],[tabindex]')){if(c===from||c.tabIndex<0||(nav&&nav.contains(c))||from.contains(c)||c.contains(from))continue;"
"const q=c.getBoundingClientRect();if(!small&&q.width*q.height<12000)continue;const qx=q.left+q.width/2,qy=q.top+q.height/2;let along,across;"
"if(key==='ArrowDown'){along=q.top-r.bottom;across=qx-cx;}else if(key==='ArrowUp'){along=r.top-q.bottom;across=qx-cx;}"
"else if(key==='ArrowRight'){along=q.left-r.right;across=qy-cy;}else{along=r.left-q.right;across=qy-cy;}"
"if(along<-4)continue;const d=Math.max(along,0)+2*Math.abs(across);if(d<score&&!windowButton(c)&&!hidden(c)){score=d;best=c;}}return best;};"
"const settle=()=>{const a=document.activeElement;if(editing(a)||shown())return;const nav=mainNav(),list=[];"
"for(const c of document.querySelectorAll('a[href],button,[role=button],[tabindex]')){if(c.tabIndex<0||(nav&&nav.contains(c)))continue;"
"const r=c.getBoundingClientRect();if(r.width*r.height>=12000&&r.top>=0&&r.left>=0&&r.bottom<=innerHeight&&r.right<=innerWidth)list.push({c,r});}"
"const key=x=>Math.round(x.r.top/8)*1e5+x.r.left;list.sort((x,y)=>key(x)-key(y));"
"for(const {c,r} of list){const hit=document.elementFromPoint(r.left+r.width/2,r.top+8);"
"if(hit&&(hit===c||c.contains(hit))&&!hidden(c)){arrowAt=performance.now();c.focus({preventScroll:true});return;}}};"
"const arm=()=>{clearTimeout(settleTimer);settleTimer=setTimeout(()=>{settling=false;settle();},200);};"
"addEventListener('scroll',()=>{if(settling)arm();},true);"
"const unring=()=>{if(ringed){ringed.style.outline=ringOutline;ringed.style.outlineOffset=ringOffset;ringed=null;}};"
"addEventListener('keydown',e=>{const k=e.key||'';if(k.startsWith('Arrow')){arrowAt=e.timeStamp;const a=document.activeElement;"
"if(!editing(a)&&!shown()){const nav=mainNav();"
"if(!a||a===document.body||hidden(a)||(k==='ArrowDown'&&nav&&nav.contains(a))){const f=first(nav);"
"if(f){e.preventDefault();e.stopImmediatePropagation();f.focus();f.scrollIntoView({block:'nearest'});}}"
"else if(big(a)&&!e.ctrlKey&&!e.altKey){let t=toward(a,k,nav);"
"if(!t&&(k==='ArrowUp'||k==='ArrowDown'))t=toward(a,k,nav,true);"
"if(t){e.preventDefault();e.stopImmediatePropagation();t.focus({preventScroll:true});t.scrollIntoView({block:'nearest',inline:'nearest'});}}}}"
"if(k==='Escape')open=shown()?e.timeStamp:-1e9;"
"if(e.code==='F13'){e.preventDefault();e.stopImmediatePropagation();settling=true;arm();}},true);"
"addEventListener('keydown',e=>{if(e.key!=='BrowserBack')return;e.preventDefault();e.stopImmediatePropagation();"
"const a=document.activeElement;if(editing(a)){a.blur();return;}"
"if(e.timeStamp-open>500)history.back();},true);"
"window.droiddeckTab=step=>{"
"const nav=mainNav();if(!nav)return;"
"const tabs=[...nav.querySelectorAll('a[href]')].filter(a=>!hidden(a)),part=p=>p.split('/')[1]||'';"
"const at=tabs.findIndex(a=>part(new URL(a.href).pathname)===part(location.pathname));"
"const to=tabs[Math.min(tabs.length-1,Math.max(0,at+step))];"
"if(at>=0&&to!==tabs[at]){to.click();to.blur();}};"
"const redirect=n=>{redirecting=true;try{n.focus();}finally{redirecting=false;}};"
"addEventListener('focusout',unring,true);"
"addEventListener('focusin',e=>{const t=e.target;if(!(t instanceof Element)||e.timeStamp-arrowAt>1000)return;"
"const back=e.relatedTarget instanceof Element&&e.relatedTarget.focus?e.relatedTarget:null;"
"if(!redirecting&&windowButton(t)){if(back)redirect(back);return;}"
"if(!redirecting&&hidden(t)){let a=t.parentElement;"
"while(a&&!(a.matches('a[href],button,[role=button],[tabindex]')&&!hidden(a)))a=a.parentElement;"
"if(a)redirect(a);else if(back)redirect(back);return;}"
"unring();ringed=(t.matches('input,textarea')&&t.closest('label'))||t;"
"ringOutline=ringed.style.outline;ringOffset=ringed.style.outlineOffset;"
"ringed.style.outline='3px solid #fff';ringed.style.outlineOffset='2px';},true);})();";
typedef struct {
int type;
void *window;
signed char send_event;
unsigned time;
unsigned state;
unsigned keyval;
} KeyEvent;
static void *launcher_view;
static void find_launcher_view(void *widget, void *data)
{
(void)data;
if (launcher_view)
return;
if (g_type_check_instance_is_a(widget, webkit_web_view_get_type())) {
const char *uri = webkit_web_view_get_uri(widget);
const char *prefix = "tauri:";
while (uri && *prefix && *uri == *prefix) {
uri++;
prefix++;
}
if (uri && !*prefix)
launcher_view = widget;
} else if (g_type_check_instance_is_a(widget, gtk_container_get_type())) {
gtk_container_forall(widget, find_launcher_view, 0);
}
}
static int switch_tab(void *grab, void *event_data, void *data)
{
KeyEvent *event = event_data;
(void)data;
if (!grab || event->type != 8 || !(event->state & 4) || (event->keyval != 0xff55 && event->keyval != 0xff56))
return 0;
launcher_view = 0;
find_launcher_view(gtk_widget_get_toplevel(grab), 0);
if (!launcher_view)
return 0;
webkit_web_view_run_javascript(launcher_view, event->keyval == 0xff56 ? "window.droiddeckTab&&droiddeckTab(1)"
: "window.droiddeckTab&&droiddeckTab(-1)",
0, 0, 0);
return 1;
}
static void watch_tab_keys(void)
{
static int watching;
if (watching || !gtk_key_snooper_install || !gtk_widget_get_toplevel || !gtk_container_forall ||
!gtk_container_get_type || !webkit_web_view_get_type || !g_type_check_instance_is_a ||
!webkit_web_view_get_uri || !webkit_web_view_run_javascript)
return;
watching = 1;
gtk_key_snooper_install(switch_tab, 0);
}
static void set(WebKitSettings *settings, const char *setter, const char *property, int value)
{
static int setting;
if (setting) {
void (*next)(WebKitSettings *, int) = dlsym ? (void (*)(WebKitSettings *, int))dlsym((void *)-1l, setter) : 0;
if (next)
next(settings, value);
return;
}
if (!g_object_set)
return;
setting = 1;
g_object_set(settings, property, value, "enable-smooth-scrolling", 0, "enable-spatial-navigation", 1, (const char *)0);
setting = 0;
}
#define SETTER(name, property) \
__attribute__((visibility("default"))) void webkit_settings_set_##name(WebKitSettings *settings, int value) \
{ \
set(settings, "webkit_settings_set_" #name, property, value); \
}
SETTER(enable_javascript, "enable-javascript")
SETTER(enable_developer_extras, "enable-developer-extras")
SETTER(enable_webgl, "enable-webgl")
SETTER(enable_webaudio, "enable-webaudio")
SETTER(enable_page_cache, "enable-page-cache")
SETTER(javascript_can_access_clipboard, "javascript-can-access-clipboard")
SETTER(javascript_can_open_windows_automatically, "javascript-can-open-windows-automatically")
SETTER(enable_back_forward_navigation_gestures, "enable-back-forward-navigation-gestures")
__attribute__((visibility("default"))) void webkit_user_content_manager_add_script(WebKitUserContentManager *manager,
WebKitUserScript *script)
{
static void (*next)(WebKitUserContentManager *, WebKitUserScript *);
if (!next && dlsym)
next = (void (*)(WebKitUserContentManager *, WebKitUserScript *))dlsym((void *)-1l, "webkit_user_content_manager_add_script");
if (!next)
return;
watch_tab_keys();
if (g_object_get_data && g_object_set_data && webkit_user_script_new && webkit_user_script_unref &&
!g_object_get_data(manager, "droiddeck-nav")) {
g_object_set_data(manager, "droiddeck-nav", (void *)1);
WebKitUserScript *nav = webkit_user_script_new(NAV_SCRIPT, 1, 0, 0, 0);
if (nav) {
next(manager, nav);
webkit_user_script_unref(nav);
}
}
next(manager, script);
}
@@ -21,6 +21,7 @@ Requests: ping, exec, focus, cdp, quit. Each answer is {"ok": true, ...} or
import base64
import json
import math
import re
import os
import selectors
import signal
@@ -177,6 +178,11 @@ class X:
return list(struct.unpack("<%dI" % n, data))
return data
def cardinals(self, window, name, values):
self.s.sendall(struct.pack("<BBHIIIB3xI", 18, 0, 6 + len(values), window,
self.atom(name), self.atom("CARDINAL"), 32, len(values))
+ struct.pack("<%dI" % len(values), *values))
def windows(x):
"""Top-level windows that are mapped or carry an app id: what gamescope picks focus from."""
@@ -249,6 +255,67 @@ def focus_snapshot():
return snap
STEAM_APP_CLASS = re.compile(r"steam_app_(\d+)$")
def tag_game_windows(snap):
if os.environ.get("BL_STEAM_CLIENT_ARCH") != "x86_64":
return False
tagged = False
for display, wins in snap.get("displays", {}).items():
if display == os.environ.get("DISPLAY"):
continue
for win in wins:
match = STEAM_APP_CLASS.match(win.get("class") or "")
if not match or win.get("appId") or win.get("map") != "viewable" or win.get("overrideRedirect"):
continue
try:
done = subprocess.run(["xprop", "-display", display, "-id", str(win["window"]), "-f", "STEAM_GAME", "32c",
"-set", "STEAM_GAME", match.group(1)],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=5).returncode == 0
except (OSError, subprocess.TimeoutExpired):
done = False
log("game window %s on %s tagged STEAM_GAME=%s: %s" % (win["window"], display, match.group(1), "ok" if done else "failed"))
tagged = tagged or done
return tagged
def vr_scene_app(path=Path('/run/droiddeck/droiddeck-steamvr/scene-focus.json'), proc=Path('/proc')):
"""Only a live SteamVR scene with its dashboard hidden may claim game focus."""
try:
state = json.loads(path.read_text())
server, scene = int(state['serverPid']), int(state['scenePid'])
if server <= 0 or scene <= 0 or state['dashboard'] is not False:
return None
if (proc / str(server) / 'comm').read_text().strip() != 'vrserver':
return None
for entry in (proc / str(scene) / 'environ').read_bytes().split(b'\0'):
if entry.startswith(b'SteamAppId='):
app = int(entry.split(b'=', 1)[1])
return app if 0 < app < 2**32 else None
except (OSError, ValueError, TypeError, KeyError):
pass
return None
class VrSceneFocus:
def __init__(self):
self.original = None
self.written = None
def order(self, current, focusable, app):
if app is None or app not in focusable:
restore = self.original if self.written == current else None
self.original = self.written = None
return restore
if current and current[0] == app:
return None
if self.original is None:
self.original = list(current)
self.written = [app] + [item for item in current if item != app]
return self.written
class FocusWatcher(threading.Thread):
"""Rewrites focus.json when gamescope's focus properties change, and every few seconds when
the windows do (a window can change without any root property moving)."""
@@ -259,19 +326,35 @@ class FocusWatcher(threading.Thread):
self.changed = threading.Event()
self.last = None
self.seq = 0
self.vr_focus = VrSceneFocus()
def run(self):
threading.Thread(target=self.listen, daemon=True, name="focus-events").start()
last_app, last_snapshot = None, 0
while True:
self.changed.wait(timeout=5)
notified = self.changed.wait(timeout=0.5)
self.changed.clear()
app = vr_scene_app()
if not notified and app == last_app and time.monotonic() - last_snapshot < 5:
continue
last_app, last_snapshot = app, time.monotonic()
time.sleep(0.2)
try:
snap = focus_snapshot()
order = self.vr_focus.order(snap.get('baselayerAppIds', []), snap.get('focusableApps', []), app)
if order is not None:
x = X(os.environ['DISPLAY'])
try:
x.cardinals(x.root, 'GAMESCOPECTRL_BASELAYER_APPID', order)
finally:
x.close()
except (OSError, AgentError) as e:
log("focus snapshot failed: %s" % e)
time.sleep(2)
continue
if tag_game_windows(snap):
self.changed.set()
continue
body = {k: v for k, v in snap.items() if k != "t"}
if body == self.last:
continue
@@ -477,6 +560,80 @@ def steam_selection(agent_dir, timeout=5):
return {"appId": int(value)}
def steam_shortcut_app_id(game_id):
"""Return the 32-bit app id in Steam's shortcut CGameID form, or None for other ids.
DroidDeck's shortcut IDs are `(appid << 32) | 0x02000000`. The URL still needs that full
CGameID for RunGame; the app-details API separately needs the unsigned 32-bit app id.
"""
if not isinstance(game_id, str) or not game_id.isascii() or not game_id.isdigit():
return None
try:
game_id_value = int(game_id)
except ValueError:
return None
if str(game_id_value) != game_id or not 0 < game_id_value <= 0xFFFFFFFFFFFFFFFF:
return None
if game_id_value <= 0xFFFFFFFF or game_id_value & 0xFFFFFFFF != 0x02000000:
return None
app_id = game_id_value >> 32
return app_id if 0 < app_id <= 0xFFFFFFFF else None
def wait_for_steam_shortcut_overview(agent_dir, game_id, timeout=45):
"""Wait until Steam can map a shortcut CGameID to its 32-bit app overview."""
app_id = steam_shortcut_app_id(game_id)
if app_id is None:
return {"supported": False, "ready": False}
timeout = request_timeout({"timeout": timeout}, 45)
deadline = time.monotonic() + timeout
expression = """(() => {
const store = globalThis.appStore;
if (typeof store?.GetAppOverviewByGameID !== 'function') return null;
const overview = store.GetAppOverviewByGameID(%s);
return overview == null ? null : String(overview.appid);
})()""" % json.dumps(game_id)
while True:
remaining = deadline - time.monotonic()
if remaining <= 0:
break
try:
result = cdp_eval(agent_dir, expression, await_promise=False,
timeout=min(5, max(0.25, remaining)))
if result.get("value") == str(app_id):
return {"supported": True, "ready": True, "appId": app_id}
except AgentError as error:
if error.code not in ("NO_DEVTOOLS", "DEVTOOLS_UNREACHABLE", "NO_TARGET", "TIMEOUT"):
raise
time.sleep(min(0.25, max(0, deadline - time.monotonic())))
raise AgentError("STEAM_OVERVIEW_TIMEOUT", "Steam did not load shortcut app overview %d" % app_id)
def steam_shortcut_state(agent_dir, game_id, timeout=6):
if steam_shortcut_app_id(game_id) is None:
return "not-shortcut"
timeout = request_timeout({"timeout": timeout}, 6)
deadline = time.monotonic() + timeout
expression = """(() => {
const store = globalThis.appStore;
if (typeof store?.GetAppOverviewByGameID !== 'function' || !store.m_bIsInitialized) return 'loading';
if (store.GetAppOverviewByGameID(%s) != null) return 'ready';
return store.allApps.some(app => app.app_type == 1073741824) ? 'missing' : 'loading';
})()""" % json.dumps(game_id)
state = "loading"
while True:
try:
state = cdp_eval(agent_dir, expression, await_promise=False,
timeout=min(5, max(0.25, deadline - time.monotonic()))).get("value") or "loading"
except AgentError as error:
if error.code not in ("NO_DEVTOOLS", "DEVTOOLS_UNREACHABLE", "NO_TARGET", "TIMEOUT"):
raise
state = "loading"
if state == "ready" or time.monotonic() >= deadline:
return state
time.sleep(min(0.5, max(0, deadline - time.monotonic())))
def game_pids(app_id):
"""Our processes started for this Steam app (Steam sets SteamAppId / SteamGameId in their
@@ -740,6 +897,43 @@ def main(argv):
if not base:
print("BL_LAUNCH_DIR is not set", file=sys.stderr)
return 2
if argv and argv[0] == "--wait-steam-shortcut-overview":
if len(argv) not in (2, 3):
print("usage: droiddeck-agent --wait-steam-shortcut-overview <cgameid> [timeout-seconds]", file=sys.stderr)
return 2
timeout = argv[2] if len(argv) == 3 else 45
try:
prepared = wait_for_steam_shortcut_overview(Path(base) / "agent", argv[1], timeout)
except (AgentError, OSError, ValueError) as error:
print("droiddeck-agent: shortcut overview was not ready: %s" % error, file=sys.stderr)
return 1
if not prepared["supported"]:
print("droiddeck-agent: id is not a DroidDeck shortcut CGameID")
return 3
print("droiddeck-agent: Steam overview is ready for shortcut app %d" % prepared["appId"])
return 0
if argv and argv[0] == "--steam-asleep":
expression = """(() => {
const store = globalThis.SuspendResumeStore;
return store ? (store.m_bSuspending ? 'yes' : 'no') : 'unknown';
})()"""
try:
state = cdp_eval(Path(base) / "agent", expression, await_promise=False, timeout=3).get("value") or "unknown"
except (AgentError, OSError, ValueError):
state = "unknown"
print(state)
return {"yes": 0, "no": 5}.get(state, 1)
if argv and argv[0] == "--steam-shortcut-state":
if len(argv) not in (2, 3):
print("usage: droiddeck-agent --steam-shortcut-state <cgameid> [timeout-seconds]", file=sys.stderr)
return 2
try:
state = steam_shortcut_state(Path(base) / "agent", argv[1], argv[2] if len(argv) == 3 else 6)
except (AgentError, OSError, ValueError) as error:
print("droiddeck-agent: could not ask the client about the shortcut: %s" % error, file=sys.stderr)
return 1
print(state)
return {"ready": 0, "missing": 4, "not-shortcut": 3}.get(state, 1)
serve(Path(base) / "agent", focus="--no-focus" not in argv)
return 0
@@ -4,8 +4,10 @@ import re
import sys
HOME = os.environ.get("HOME", "/root")
STEAM_ROOT = sys.argv[1] if len(sys.argv) > 1 else os.path.join(HOME, ".local/share/Steam")
LIBRARIES = ((STEAM_ROOT, "Steam Games"), ("/mnt/droiddeck-sd", "SD Games"))
X64 = os.environ.get("BL_STEAM_CLIENT_ARCH") == "x86_64"
CLIENT_HOME = (os.environ.get("BL_X64_HOME") or os.path.join(HOME, ".droiddeck-x64")) if X64 else HOME
STEAM_ROOT = sys.argv[1] if len(sys.argv) > 1 else os.path.join(CLIENT_HOME, ".local/share/Steam")
LIBRARIES = ((STEAM_ROOT, "Steam Games"), ("/mnt/droiddeck-sd/x86-64" if X64 else "/mnt/droiddeck-sd", "SD Games"))
NOT_GAMES = {228980, 1070560, 1391110, 1493710, 1628350, 3127680, 4183110, 4185400, 4427310, 4628740}
APPS_DIR = os.path.join(HOME, ".local/share/applications")
PREFIX = "droiddeck-game-"
File diff suppressed because it is too large. Load diff
+4
View File
@@ -0,0 +1,4 @@
#!/bin/sh
[ -n "${LD_PRELOAD:-}" ] && export DROIDDECK_STEAM_PRELOAD="$LD_PRELOAD"
unset LD_PRELOAD LD_LIBRARY_PATH
exec /usr/bin/python3 -I /usr/local/bin/droiddeck-epic run
+152 -23
View File
@@ -28,15 +28,25 @@ 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"}
SLR4_APPID = "4183110"
INSTALL_DIRS = {FEX_APPID: "FEX-Emu", SNIPER_APPID: "SteamLinuxRuntime_sniper", SLR4_APPID: "SteamLinuxRuntime_4"}
MARKER = ".droiddeck-fex"
LAYOUT = 1
ROOTFS_LAYOUT = 1
ARCH_DIRS = ("x86_64-linux-gnu", "i386-linux-gnu")
INTERPRETERS = ("ld-linux-x86-64.so.2", "ld-linux.so.2")
PROVIDED = frozenset((
"ld-linux-x86-64.so.2", "ld-linux.so.2", "libc.so.6", "libm.so.6", "libmvec.so.1", "libpthread.so.0", "libdl.so.2",
"librt.so.1", "libutil.so.1", "libresolv.so.2", "libanl.so.1", "libBrokenLocale.so.1", "libnsl.so.1",
"libnss_compat.so.2", "libnss_dns.so.2", "libnss_files.so.2", "libnss_hesiod.so.2", "libthread_db.so.1",
"libmemusage.so", "libpcprofile.so", "libc_malloc_debug.so.0", "gconv", "libstdc++.so.6", "libgcc_s.so.1",
))
GLIBC_BUILD = re.compile(r"^(?:ld|lib[A-Za-z_]+)-2\.[0-9]+\.so$|^libSegFault\.so$")
GUEST_LIBDIRS = (("x86_64", "lib/x86_64-linux-gnu"), ("i386", "lib/i386-linux-gnu"))
PRELOAD_NAMES = ("libblsession.so", "libfakeinput.so")
FAULT_REPORT = "libfaultreport.so"
THUNK_AUDIT = "libthunkaudit.so"
THUNK_AUDIT_GUEST = "/usr/lib/x86_64-linux-gnu/droiddeck/" + THUNK_AUDIT
VULKAN_PIN = "libvulkan-thunk.so"
VULKAN_PIN_DIR = "lib/x86_64-linux-gnu/droiddeck/vulkan"
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]")
@@ -164,15 +174,15 @@ 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)
def runtime_platform(appid=SNIPER_APPID, prefix="sniper_platform_"):
runtime = app_dir(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 = [os.path.join(runtime, entry) for entry in entries if entry.startswith(prefix)]
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)
@@ -234,6 +244,75 @@ def materialize(platform):
return True
def graphics_platform():
return runtime_platform(SLR4_APPID, "steamrt4_platform_")
def provides_newer(base, provider):
for name, prefix in RUNTIME_LIBRARIES:
ours = {v for v in version_names(os.path.join(base, "files/lib/x86_64-linux-gnu", name)) if v.startswith(prefix)}
theirs = {v for v in version_names(os.path.join(provider, "files/lib/x86_64-linux-gnu", name)) if v.startswith(prefix)}
if not ours or not theirs or not ours < theirs:
return False
return True
def mirror(source, provider, name, target):
if provider and name in PROVIDED and os.path.lexists(os.path.join(provider, name)):
os.symlink(os.path.realpath(os.path.join(provider, name)), os.path.join(target, name))
return
path = os.path.join(source, name)
link = os.readlink(path) if os.path.islink(path) else None
if link and GLIBC_BUILD.match(os.path.basename(link)):
if name not in INTERPRETERS:
return
link = os.path.join(os.path.dirname(link), name)
if provider and GLIBC_BUILD.match(name):
return
if link and not link.startswith("/"):
os.symlink(link, os.path.join(target, name))
else:
os.symlink(os.path.realpath(path), os.path.join(target, name))
def build_rootfs(base, provider):
"""The runtime with glibc and libstdc++ taken from a newer one, which FEX's GL and Vulkan thunks are built against."""
base_files, provider_files = os.path.join(base, "files"), os.path.join(provider, "files")
rootfs = os.path.join(STATE, "rootfs")
stamp = "%d\n%s\n%s%s\n%s" % (ROOTFS_LAYOUT, os.path.realpath(base), read_text(os.path.join(base_files, MARKER)) or "",
os.path.realpath(provider), read_text(os.path.join(provider_files, MARKER)) or "")
if read_text(os.path.join(rootfs, MARKER)) == stamp:
return False
for entry in os.listdir(STATE):
if entry.startswith("rootfs."):
shutil.rmtree(os.path.join(STATE, entry), ignore_errors=True)
tmp = "%s.%d.tmp" % (rootfs, os.getpid())
os.makedirs(tmp)
for entry in os.listdir(base_files):
if entry not in ("lib", "lib64", "usr", MARKER):
os.symlink(os.path.realpath(os.path.join(base_files, entry)), os.path.join(tmp, entry))
os.symlink(".", os.path.join(tmp, "usr"))
for top in ("lib", "lib64"):
source = os.path.join(base_files, top)
os.makedirs(os.path.join(tmp, top))
for entry in os.listdir(source) if os.path.isdir(source) else ():
path = os.path.join(source, entry)
if entry in ARCH_DIRS and os.path.isdir(path) and not os.path.islink(path):
provided = os.path.join(provider_files, top, entry)
os.makedirs(os.path.join(tmp, top, entry))
for name in set(os.listdir(path)) | {name for name in PROVIDED if os.path.lexists(os.path.join(provided, name))}:
mirror(path, provided, name, os.path.join(tmp, top, entry))
else:
mirror(source, None, entry, os.path.join(tmp, top))
write_if_changed(os.path.join(tmp, MARKER), stamp)
old = "%s.%d.old" % (rootfs, os.getpid())
if os.path.lexists(rootfs):
os.rename(rootfs, old)
os.rename(tmp, rootfs)
shutil.rmtree(old, ignore_errors=True)
return True
def host_preloads():
listed = read_text(HOST_PRELOAD) or ""
return [name for name in PRELOAD_NAMES if name in listed]
@@ -247,10 +326,14 @@ def install_preloads(root):
if os.path.isfile(source):
copy_if_changed(source, os.path.join(root, libdir, "droiddeck", name))
shipped.setdefault(name, set()).add(arch)
for name in (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))
pin = os.path.join(PRELOADS, "x86_64", VULKAN_PIN)
if os.path.isfile(pin):
copy_if_changed(pin, os.path.join(root, VULKAN_PIN_DIR, "libvulkan.so.1"))
alias = os.path.join(root, VULKAN_PIN_DIR, "libvulkan.so")
if not os.path.islink(alias) or os.readlink(alias) != "libvulkan.so.1":
if os.path.lexists(alias):
os.unlink(alias)
os.symlink("libvulkan.so.1", alias)
wanted = [name for name in host_preloads() if name in shipped]
if len(shipped.get(FAULT_REPORT, ())) == len(GUEST_LIBDIRS):
wanted.append(FAULT_REPORT)
@@ -270,14 +353,16 @@ def write_config(fex, root):
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"
if elf_arch(os.path.join(link, "steamclient.so")) == want:
continue
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)
tmp = "%s.%d.tmp" % (link, os.getpid())
os.symlink(directory, tmp)
os.replace(tmp, link)
break
@@ -308,7 +393,7 @@ def request_install():
return []
def describe(fex, platform):
def describe(fex, platform, graphics=None):
return {
"fex": fex["bin"] if fex else None,
"server": fex["server"] if fex else None,
@@ -317,6 +402,7 @@ def describe(fex, 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),
"graphics": graphics,
}
@@ -346,13 +432,27 @@ def prepare():
if materialize(platform):
say("prepared %s as the x86 runtime" % os.path.basename(platform))
install_preloads(root)
provider = graphics_platform()
if provider and materialize(provider):
say("prepared %s for the x86 runtime's C and C++ libraries" % os.path.basename(provider))
if not provider:
say("Steam Linux Runtime 4.0 (Steam app %s) is not installed yet; x86 games may not find their graphics drivers"
% SLR4_APPID)
elif not provides_newer(platform, provider):
say("%s has no newer C and C++ libraries than %s" % (os.path.basename(provider), os.path.basename(platform)))
provider = None
else:
if build_rootfs(platform, provider):
say("built the x86 runtime from %s with the C and C++ libraries of %s"
% (os.path.basename(platform), os.path.basename(provider)))
root = os.path.join(STATE, "rootfs")
write_config(fex, root)
fex["rootfs"] = root
try:
link_steam_sdk()
except OSError:
pass
status = describe(fex, platform)
status = describe(fex, platform, provider)
write_if_changed(STATUS_FILE, json.dumps(status, indent=2) + "\n")
with contextlib.suppress(OSError):
os.unlink(WANTED)
@@ -422,8 +522,16 @@ 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 + "/"
# Valve's FEX-Emu binds its server socket under $STEAM_COMPAT_DATA_PATH/fex-emu whatever FEX_APP_DATA_LOCATION or
# FEX_SERVERSOCKETPATH say, and sun_path is 108 bytes: compatdata under the app's data folder is too long.
if result.get("STEAM_COMPAT_DATA_PATH"):
short = data if data != DATA_DIR else "/tmp/fex"
os.makedirs(short, exist_ok=True)
result["STEAM_COMPAT_DATA_PATH"] = short
result.setdefault("FEX_SILENTLOG", "0")
result.setdefault("FEX_OUTPUTLOG", "stderr")
# Mono's incremental Boehm collector corrupts its heap under FEX, so Unity games crash at their first collections.
result.setdefault("GC_DISABLE_INCREMENTAL", "1")
if fex["portable"]:
result["FEX_PORTABLE"] = "1"
else:
@@ -439,7 +547,7 @@ def guest_environment(fex, env):
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]
if part and "arm64" 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)
@@ -477,6 +585,7 @@ def vulkan_thunk_loads(fex, folder):
needed = version_names(os.path.join(fex["guest_thunks"], VULKAN_THUNK))
if not needed:
return False
needed |= version_names(os.path.join(PRELOADS, "x86_64", VULKAN_PIN))
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)
@@ -503,9 +612,10 @@ def launch(command, env, mode, decide=None):
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)
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)) \
if thunks == "on" and x86_64 and os.path.isfile(os.path.join(PRELOADS, "x86_64", VULKAN_PIN)) \
and vulkan_thunk_loads(fex, folder):
guest["LD_AUDIT"] = ":".join([THUNK_AUDIT_GUEST] + split_paths(guest.get("LD_AUDIT")))
# Any LD_AUDIT module makes Mono's garbage collector crash under FEX, so the Vulkan thunk is pinned by search path.
guest["LD_LIBRARY_PATH"] = ":".join(["/usr/" + VULKAN_PIN_DIR] + split_paths(guest.get("LD_LIBRARY_PATH")))
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)
@@ -557,19 +667,38 @@ def extracted():
def want_fex():
with locked():
status = describe(fex_install(), runtime_platform())
status = describe(fex_install(), runtime_platform(), graphics_platform())
if not status["ready"]:
request_install()
write_if_changed(STATUS_FILE, json.dumps(status, indent=2) + "\n")
XATTR_ONLY_NOISE = re.compile(r"^(proot (error|warning)|Failed to exec memfd|Further error messages of this type are suppressed)")
def only_xattrs_failed(errors):
seen = False
for line in errors.splitlines():
if "write_xattr" in line:
seen = True
elif re.search(r"fail|could not|cannot|error", line, re.I) and not XATTR_ONLY_NOISE.match(line):
return False
return seen
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))
run = subprocess.run([URUNTIME, "--appimage-extract"], stdout=subprocess.DEVNULL, stderr=subprocess.PIPE,
env=dict(os.environ, TARGET_APPIMAGE=image))
errors = run.stderr.decode("utf-8", "replace")
sys.stderr.write(errors)
status = run.returncode
if status == 2 and only_xattrs_failed(errors) and extracted() and os.path.lexists("squashfs-root/AppRun"):
say("uruntime could not keep the image's extended attributes; the files are unpacked")
status = 0
if status == 0 and extracted():
if x86:
want_fex()
@@ -586,7 +715,7 @@ def extract(image):
unsquashfs = shutil.which("unsquashfs")
if unsquashfs:
clear_extracted()
status = subprocess.call([unsquashfs, "-q", "-n", "-o", str(appimage_offset(image)), "-d", "squashfs-root", image],
status = subprocess.call([unsquashfs, "-q", "-n", "-no-xattrs", "-o", str(appimage_offset(image)), "-d", "squashfs-root", image],
stdout=subprocess.DEVNULL)
if status == 0:
if x86:
@@ -654,7 +783,7 @@ def main(argv):
return 0 if prepare() else 1
if action == "status":
with locked():
status = describe(fex_install(), runtime_platform())
status = describe(fex_install(), runtime_platform(), graphics_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
@@ -181,6 +181,27 @@ def uninstall(app_id):
return rc
def prune():
inst = installation()
try:
unused = inst.list_unused_refs(None, None)
except GLib.Error as err:
emit(e="error", message=err.message)
return 1
if unused:
t, state = transaction(inst)
for r in unused:
t.add_uninstall(r.format_ref())
if run(t, state, report_done=False):
return 1
try:
inst.prune_local_repo(None)
except GLib.Error as err:
emit(e="warning", message=err.message)
emit(e="done", removed=len(unused))
return 0
def updatable(inst):
try:
return inst.list_installed_refs_for_update(None)
@@ -216,7 +237,7 @@ def updates():
def main():
if len(sys.argv) < 2:
sys.stderr.write(__doc__ or "usage: droiddeck-flatpak install|install-bundle|uninstall|update|updates [app-id|file]\n")
sys.stderr.write(__doc__ or "usage: droiddeck-flatpak install|install-bundle|uninstall|update|updates|prune [app-id|file]\n")
return 2
cmd, args = sys.argv[1], sys.argv[2:]
if cmd in ("install", "install-bundle", "update"):
@@ -231,7 +252,9 @@ def main():
return update(args[0] if args else None)
if cmd == "updates":
return updates()
sys.stderr.write("usage: droiddeck-flatpak install|install-bundle|uninstall|update|updates [app-id|file]\n")
if cmd == "prune":
return prune()
sys.stderr.write("usage: droiddeck-flatpak install|install-bundle|uninstall|update|updates|prune [app-id|file]\n")
return 2
@@ -25,8 +25,15 @@ WORK=/var/cache/droiddeck-flatpak
CONF=$WORK/pacman.conf
mkdir -p "$WORK/pkg" "$WORK/db" || fail "cannot create $WORK"
{ for m in https://ca.us.mirror.archlinuxarm.org https://fl.us.mirror.archlinuxarm.org \
https://de3.mirror.archlinuxarm.org https://nl.mirror.archlinuxarm.org; do
OVERSEAS="https://ca.us.mirror.archlinuxarm.org https://fl.us.mirror.archlinuxarm.org https://de3.mirror.archlinuxarm.org https://nl.mirror.archlinuxarm.org"
MAINLAND=""
for m in https://mirrors.tuna.tsinghua.edu.cn/archlinuxarm https://mirrors.ustc.edu.cn/archlinuxarm \
https://mirrors.bfsu.edu.cn/archlinuxarm https://mirrors.sjtug.sjtu.edu.cn/archlinuxarm; do
if curl -fsS -r 0-0 --connect-timeout 4 --max-time 8 -o /dev/null "$m/aarch64/core/core.db" 2>/dev/null; then
MAINLAND="$MAINLAND $m"
fi
done
{ for m in $MAINLAND $OVERSEAS; do
echo "Server = $m/\$arch/\$repo"; done
grep '^Server' /etc/pacman.d/mirrorlist 2>/dev/null; } > "$WORK/mirrorlist"
sed -e 's/^DownloadUser/#DownloadUser/' \
@@ -7,7 +7,7 @@ import subprocess
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")
SYNC_KEYS = ("BL_SYNC", "BL_SYNC_FALLBACK", "BL_FSYNC_FIRST", "BL_SYNC_MIN_NOFILE", "PROTON_NO_ESYNC", "PROTON_NO_FSYNC", "PROTON_NO_NTSYNC", "WINEESYNC")
SEED_REDISTS = "/usr/local/bin/droiddeck-seed-redists"
PACK_KEYS = ("WINESERVER", "BL_SYNC_PACK", "WINEESYNC", "PROTON_NO_ESYNC", "PROTON_NO_FSYNC")
@@ -98,6 +98,14 @@ def godot_sentry(game):
return {"WINEDLLOVERRIDES": ";".join(n + "=d" for n in sentry)}, [], "Godot: Sentry crash handler off"
@fix
def arkham_city_x87(game):
"""Batman: Arkham City (BatmanAC.exe, also started through BmLauncher.exe beside it) leans on x87
and stops with Unreal's "Fatal error!" right after start when FEX reduces its precision."""
if "batmanac.exe" in game.files:
return {"FEX_X87REDUCEDPRECISION": "0"}, [], "Batman: Arkham City: FEX with full x87 precision"
def skip_red_launcher(command):
"""Cyberpunk 2077's prelauncher opens REDlauncher, a Qt WebEngine window that hands over to the
game half a minute later and then stays up beside it, well over a core busy for as long as the
@@ -243,36 +251,6 @@ def force_ssbs(command, env):
return env
def umu_capable(proton):
"""Whether this Proton's script has umu's launch without Steam: GE-Proton, Proton-CachyOS and
DroidDeck-Proton run umu.exe in place of steam.exe when UMU_ID is set; Valve's Proton does not."""
try:
with open(proton, encoding="utf-8", errors="replace") as source:
text = source.read()
except OSError:
return False
return "UMU_ID" in text and "umu.exe" in text
def start_without_steam(command, env, app_id):
"""DROIDDECK_NO_STEAM=1 (a game's Start without Steam): launch the game without Proton's
steam.exe, for games that close right away because of what it sets up. A Proton with umu's
launch gets UMU_ID - Proton still sets up the prefix, and a Steam game keeps its protonfixes
under its own id; any other Proton runs the game straight in the prefix (runinprefix)."""
if env.get("DROIDDECK_NO_STEAM", "").lower() not in ("1", "on", "true", "yes"):
return command, env
if len(command) < 3 or command[1] != "waitforexitandrun":
return command, env
if umu_capable(command[0]):
if not env.get("UMU_ID"):
steam_game = app_id is not None and int(app_id) < 2**31
env = dict(env, UMU_ID=app_id if steam_game else "0")
print("droiddeck-game-env: starting without Steam (umu.exe in place of steam.exe, UMU_ID=%s)" % env["UMU_ID"], file=sys.stderr)
return command, env
print("droiddeck-game-env: starting without Steam (this Proton has no umu launch: runinprefix)", file=sys.stderr)
return [command[0], "runinprefix"] + command[2:], env
EVALUATOR_SCRIPT = re.compile(r"(?:^|[\\/])evaluatorscript_[0-9]+\.vdf$", re.IGNORECASE)
@@ -283,7 +261,7 @@ def mark_install_scripts(command, env):
ones stop with an error."""
if not any(arg.lower().replace("\\", "/").endswith("iscriptevaluator.exe") for arg in command):
return
root = env.get("STEAM_COMPAT_CLIENT_INSTALL_PATH") or str(Path.home() / ".local/share/Steam")
root = env.get("BL_X64_STEAM_ROOT") or env.get("STEAM_COMPAT_CLIENT_INSTALL_PATH") or str(Path.home() / ".local/share/Steam")
scripts = [str(Path(root) / arg.replace("\\", "/")) for arg in command if EVALUATOR_SCRIPT.search(arg)]
scripts = [path for path in scripts if os.path.isfile(path)]
if not scripts:
@@ -300,6 +278,7 @@ def main():
if not command:
return 2
env = os.environ.copy()
mic_enabled = env.get("BL_MIC_ENABLED")
mark_install_scripts(command, env)
app_id = game_id(env)
if app_id:
@@ -328,8 +307,9 @@ def main():
env = apply_config(env, {"version": 1}, app_id, fixes)
except (OSError, ValueError, TypeError, AttributeError):
print("droiddeck-game-env: invalid configuration; using inherited environment", file=sys.stderr)
if mic_enabled == "0":
env["BANNER_AUDIO_DIRECT_MIC"] = "0"
env = force_ssbs(command, env)
command, env = start_without_steam(command, env, app_id)
sync = load_sync()
launch, launch_env = select_sync(command, env, sync)
if launch[0] != command[0]:
@@ -5,10 +5,14 @@ Android owns device power. Suspend here pauses the guest through SessionService;
the app's Resume action thaws it and completes PrepareForSleep(false). Steam
must see this service before startup or it can stay black after its idle timer.
"""
import importlib.machinery
import importlib.util
import os
from pathlib import Path
import re
import subprocess
import sys
import threading
import uuid
import gi
@@ -22,6 +26,8 @@ INTERFACE = NAME + ".Manager"
UPOWER = "org.freedesktop.UPower"
UPOWER_ROOT = "/org/freedesktop/UPower"
NATIVE_PREPARE_MS = 1500
AGENT = Path(__file__).resolve().with_name("droiddeck-agent")
ASLEEP_WAIT = 6
INTROSPECTION = """
<node>
<interface name="org.freedesktop.login1.Manager">
@@ -78,6 +84,7 @@ class LoginManager:
if name == "CanSuspend":
reply.return_value(GLib.Variant("(s)", ("yes",)))
elif name in ("Suspend", "SuspendWithFlags"):
print("== login1: %s.%s asked by %s" % (interface.rsplit(".", 1)[-1], name, sender), flush=True)
if self.pending:
reply.return_dbus_error(NAME + ".OperationInProgress", "The session is already pausing")
return
@@ -147,7 +154,7 @@ class LoginManager:
if file.get_basename() == self.wake.name or (other and other.get_basename() == self.wake.name):
if self.wake.exists():
self.wake.unlink(missing_ok=True)
self.resume(force=True)
self.woken()
if file.get_basename() == self.state.name or (other and other.get_basename() == self.state.name):
self.check_state()
@@ -169,6 +176,19 @@ class LoginManager:
self.resume()
return False
def woken(self):
if self.pending is not None:
self.resume(force=True)
return
threading.Thread(target=lambda: GLib.idle_add(self.replay_unless_awake, steam_asleep()), daemon=True).start()
def replay_unless_awake(self, asleep):
if asleep is False and self.pending is None:
print("== login1: Steam is awake; no sleep/wake replay", flush=True)
return False
self.resume(force=True)
return False
def resume(self, force=False):
if self.pending is None:
if force:
@@ -193,6 +213,24 @@ class LoginManager:
self.notify(False)
def steam_asleep():
try:
code = subprocess.run([str(AGENT), "--steam-asleep"], stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL, timeout=ASLEEP_WAIT).returncode
except (OSError, subprocess.SubprocessError):
return None
return {0: True, 5: False}.get(code)
def load_netmanager():
path = Path(__file__).resolve().with_name("droiddeck-netmanager")
loader = importlib.machinery.SourceFileLoader("droiddeck_netmanager", str(path))
spec = importlib.util.spec_from_loader(loader.name, loader)
module = importlib.util.module_from_spec(spec)
loader.exec_module(module)
return module
def main():
directory = os.environ.get("BL_LAUNCH_DIR")
if not directory or not Path(directory).is_dir():
@@ -218,6 +256,8 @@ def main():
owners = [Gio.bus_own_name(Gio.BusType.SYSTEM, name, Gio.BusNameOwnerFlags.NONE, connected, acquired, lost)
for name in (NAME, UPOWER)]
if "--with-netmanager" in sys.argv[1:]:
owners.append(load_netmanager().own(loop))
try:
loop.run()
finally:
@@ -408,8 +408,7 @@ class NetworkManager:
self.bus.emit_signal(None, path, OBJECT_MANAGER, signal, body)
def main():
loop = GLib.MainLoop()
def own(loop):
state = {}
def acquired(bus, name):
@@ -419,7 +418,12 @@ def main():
print("== netmanager: the system bus is gone", file=sys.stderr)
loop.quit()
Gio.bus_own_name(Gio.BusType.SYSTEM, NAME, Gio.BusNameOwnerFlags.NONE, acquired, None, lost)
return Gio.bus_own_name(Gio.BusType.SYSTEM, NAME, Gio.BusNameOwnerFlags.NONE, acquired, None, lost)
def main():
loop = GLib.MainLoop()
own(loop)
loop.run()
@@ -13,7 +13,7 @@ RELEASES = "https://api.github.com/repos/%s/releases"
SOURCES = {
"ge": ("GloriousEggroll/proton-ge-custom", re.compile(r"aarch64\.tar\.(gz|xz)$")),
"cachyos": ("CachyOS/proton-cachyos", re.compile(r"arm64\.tar\.(gz|xz)$")),
"droiddeck": ("The412Banner/DroidDeck-Proton", re.compile(r"aarch64\.tar\.(gz|xz)$")),
"droiddeck": ("Droid-Deck/DroidDeck-Proton", re.compile(r"aarch64\.tar\.(gz|xz)$")),
}
USER_AGENT = "droiddeck-proton-extra"
NEED_BYTES = 4 * 1024 * 1024 * 1024
@@ -2,6 +2,7 @@
"""Runs a Windows program with the Proton the Steam client has chosen for it.
droiddeck-proton-run [--window] PROGRAM [ARGS...]
droiddeck-proton-run --app ID [--dir FOLDER] [--options TEXT] [PROGRAM [ARGS...]]
The program belongs to an installed Steam game when it sits in one's folder, to a prefix when it
sits in one's drive_c, or to a non-Steam shortcut that names it; any other program gets a prefix of
@@ -10,11 +11,15 @@ config.vdf picks the tool, else the client's default for all other titles ("0").
started as the client starts it - its toolmanifest's command line, the waitforexitandrun verb and
the STEAM_COMPAT_* environment - so its wrapper applies the game's settings, components and audio.
--window keeps the program in the desktop's own window, drawn with WineD3D.
--app starts one game without the Steam client (its Start without Steam): a Steam game's default
Windows launch option from appinfo.vdf when no program is given, else the program in that
shortcut's own prefix, started in --dir with the shortcut's launch options (--options).
"""
import json
import os
import re
import runpy
import shlex
import struct
import sys
import zlib
@@ -249,6 +254,81 @@ def locate(program, root):
os.path.dirname(program), root, "own")
def split_words(text):
try:
return shlex.split(text or "")
except ValueError:
return (text or "").split()
def split_options(text):
"""A shortcut's launch options: NAME=value words before %command% go to the environment, the words
after it - or all of them, without %command% - are the program's arguments."""
words = split_words(text)
if "%command%" not in words:
return {}, words
at = words.index("%command%")
env = {}
for word in words[:at]:
name, equals, value = word.partition("=")
if equals and re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", name):
env[name] = value
return env, words[at + 1:]
def find_file(base, relative):
"""base/relative, matching each part without regard to case as Windows does."""
path = base
for part in [p for p in relative.replace("\\", "/").split("/") if p and p != "."]:
exact = os.path.join(path, part)
if part == ".." or os.path.exists(exact):
path = exact
continue
try:
match = next((name for name in sorted(os.listdir(path)) if name.lower() == part.lower()), None)
except OSError:
return None
if match is None:
return None
path = os.path.join(path, match)
return os.path.normpath(path)
def steam_install(appid, root):
for library in libraries(root):
found = re.search(r'"installdir"\s+"([^"]+)"',
read_text(os.path.join(library, "steamapps", "appmanifest_%s.acf" % appid)) or "")
if found:
return library, os.path.join(library, "steamapps", "common", found.group(1))
return None, None
def steam_launch(appid, root):
"""(target, program, arguments) for a Steam game's default Windows launch option, or None."""
library, install = steam_install(appid, root)
if not install or not os.path.isdir(install):
return None
entry = compat()["appinfo_entries"](os.path.join(root, "appcache", "appinfo.vdf")).get(str(appid), {})
options = [option for option in entry.get("launch_options", ())
if not option["betakey"] and (not option["oslist"] or "windows" in option["oslist"])]
options.sort(key=lambda option: (option["type"] not in ("", "default", "none"),
int(option["key"]) if option["key"].isdigit() else 0))
for option in options:
program = find_file(install, option["executable"])
if not program or not os.path.isfile(program):
continue
start = find_file(install, option["workingdir"]) if option["workingdir"] else None
target = Target(appid, os.path.join(library, "steamapps", "compatdata", str(appid)), install, library, "steam",
start if start and os.path.isdir(start) else os.path.dirname(program))
return target, program, split_words(option["arguments"])
return None
def shortcut_target(appid, program, start, root):
return Target(appid, os.path.join(root, "steamapps", "compatdata", str(appid)), os.path.dirname(program), root,
"shortcut", start if start and os.path.isdir(start) else None)
def steam_launches(target, program, root):
"""Whether a launch option of the Steam game starts [program]: then Steam should start it."""
if target.kind != "steam":
@@ -292,24 +372,52 @@ def arguments(program, args):
def main(argv):
window = False
app, start, options = None, None, ""
while argv and argv[0].startswith("--"):
option = argv.pop(0)
if option == "--window":
window = True
elif option in ("--app", "--dir", "--options") and argv:
value = argv.pop(0)
if option == "--app":
app = value
elif option == "--dir":
start = value
else:
options = value
elif option == "--":
break
else:
say("unknown option %s" % option)
return 2
if not argv:
if app is not None and not (app.isdigit() and 0 < int(app) < 2 ** 32):
say("%s is not an app id" % app)
return 2
if not argv and app is None:
say("usage: droiddeck-proton-run [--window] PROGRAM [ARGS...]")
return 2
program = os.path.abspath(argv[0])
if not os.path.isfile(program):
say("%s does not exist" % program)
return 2
root = os.environ.get("STEAM_COMPAT_CLIENT_INSTALL_PATH") or STEAM_ROOT
target = locate(program, root)
extra, args = split_options(options)
if not argv:
if int(app) >= STEAM_APP_LIMIT:
say("shortcut %s needs its program" % app)
return 2
found = steam_launch(app, root)
if found is None:
say("Steam game %s is not installed, or has no Windows launch option" % app)
return 2
target, program, own = found
args = own + args
else:
program = os.path.abspath(argv[0])
if not os.path.isfile(program):
say("%s does not exist" % program)
return 2
args = args + argv[1:]
if app is not None and int(app) >= STEAM_APP_LIMIT:
target = shortcut_target(app, program, start, root)
else:
target = locate(program, root)
available = tools(root)
name, why = choose_tool(target.appid, mapping(root), available)
if name is None:
@@ -318,13 +426,15 @@ def main(argv):
folder, command = available[name]
os.makedirs(target.compatdata, exist_ok=True)
env = environment(os.environ, target, folder, root, window)
say("%s with %s (%s), %s prefix %s" % (program, name, why, target.kind, target.compatdata))
env.update(extra)
say("%s with %s (%s), %s prefix %s%s" % (program, name, why, target.kind, target.compatdata,
", without the Steam client" if app is not None else ""))
try:
os.chdir(target.start)
except OSError:
os.chdir(os.path.dirname(program))
entry = os.path.join(folder, command)
os.execve(entry, [entry, VERB] + arguments(program, argv[1:]), env)
os.execve(entry, [entry, VERB] + arguments(program, args), env)
if __name__ == "__main__":
@@ -6,9 +6,11 @@ LIBRARIES=${DROIDDECK_LIBRARIES-/mnt/droiddeck /mnt/droiddeck-sd}
redist="$steam_root/steamapps/common/Steamworks Shared/_CommonRedist"
read_scripts() { xargs -0 -r awk -v want="${1:-redists}" '
FNR == 1 { depth = 0; pending = "" }
/^[[:space:]]*\{/ { depth++; name[depth] = pending; key[depth] = ""; vulkan[depth] = 0; pending = ""; next }
FNR == 1 { depth = 0; pending = ""; appid = "" }
/^[[:space:]]*\{/ { depth++; name[depth] = pending; key[depth] = ""; vulkan[depth] = 0; proc[depth] = 0; pending = ""; next }
/^[[:space:]]*\}/ {
if (depth > 0 && key[depth] == "" && proc[depth] && appid != "" && name[depth] != "" && vulkan[depth] == (want == "vulkan"))
printf "HKEY_LOCAL_MACHINE\\\\Software\\\\Valve\\\\Steam\\\\Apps\\\\%s\t%s\n", appid, name[depth]
if (depth > 0 && key[depth] != "" && name[depth] != "" && vulkan[depth] == (want == "vulkan"))
printf "%s\t%s\n", key[depth], name[depth]
if (depth > 0) depth--
@@ -16,8 +18,10 @@ read_scripts() { xargs -0 -r awk -v want="${1:-redists}" '
}
{
n = split($0, part, "\"")
if (n >= 5 && tolower(part[2]) == "appid" && part[4] ~ /^[0-9]+$/) { appid = part[4]; next }
if (n >= 5 && tolower(part[2]) == "hasrunkey") { key[depth] = part[4]; next }
if (n >= 5 && tolower(part[2]) ~ /^process [0-9]+$/) {
proc[depth] = 1
program = tolower(part[4])
sub(/.*[\\\/]/, "", program)
if (program ~ /vulkan/) vulkan[depth] = 1
@@ -139,6 +143,51 @@ unseed() {
return 1
}
# The ledger lines whose values the registry still holds, in both views where we wrote both. A Proton
# update replaces its default_pfx system.reg but not our ledger beside it, and new prefixes copy both.
present() { awk -F'\t' '
NR == FNR {
path = $1
if (path != "vcrt") {
sub(/^HKEY_LOCAL_MACHINE\\\\/, "", path)
if (path == $1)
next
}
n++
line[n] = $0
need[n] = 0
if (path == "vcrt") {
for (a = split("x86 x64 arm64", arch, " "); a > 0; a--) {
runtime = "microsoft\\\\visualstudio\\\\14.0\\\\vc\\\\runtimes\\\\" arch[a]
key[n, ++need[n]] = "[software\\\\" runtime "]" SUBSEP "installed"
key[n, ++need[n]] = "[software\\\\wow6432node\\\\" runtime "]" SUBSEP "installed"
}
} else {
both = substr(path, 1, 10) == "Software\\\\"
path = tolower(path)
key[n, ++need[n]] = "[" path "]" SUBSEP tolower($2)
if (both)
key[n, ++need[n]] = "[software\\\\wow6432node\\\\" substr(path, 11) "]" SUBSEP tolower($2)
}
for (j = 1; j <= need[n]; j++) wanted[key[n, j]] = 1
next
}
/^\[/ { section = tolower(substr($0, 1, index($0, "]"))) }
/^"/ {
value = substr($0, 2)
value = tolower(substr(value, 1, index(value, "\"=") - 1))
if ((section SUBSEP value) in wanted)
seen[section SUBSEP value] = 1
}
END {
for (i = 1; i <= n; i++) {
ok = 1
for (j = 1; j <= need[i]; j++) if (!(key[i, j] in seen)) ok = 0
if (ok) print line[i]
}
}
' - "$1"; }
for reg in "$steam_root"/steamapps/common/Proton*/files/share/default_pfx*/system.reg \
/mnt/droiddeck-sd/steamapps/common/Proton*/files/share/default_pfx*/system.reg \
/root/Games/*/steamapps/common/Proton*/files/share/default_pfx*/system.reg \
@@ -166,6 +215,17 @@ for reg in "$steam_root"/steamapps/common/Proton*/files/share/default_pfx*/syste
printf '%s\n' "${kept[@]}" >"$seeded"
echo "== took Vulkan runtime markers out of $reg"
fi
if [ ${#had[@]} -gt 0 ]; then
declare -A held=()
while IFS= read -r line; do [[ $line == *$'\t'* ]] && held[$line]=1; done < <(printf '%s\n' "${!had[@]}" | present "$reg")
if [ ${#held[@]} -lt ${#had[@]} ]; then
echo "== $((${#had[@]} - ${#held[@]})) recorded redist markers are gone from $reg"
had=()
for line in "${!held[@]}"; do had[$line]=1; done
printf '%s\n' "${!had[@]}" >"$seeded"
fi
unset held
fi
missing=()
for line in "${want[@]}"; do [ -n "${had[$line]:-}" ] || missing+=("$line"); done
[ ${#missing[@]} -eq 0 ] && continue
@@ -33,9 +33,9 @@ prepare_locale() {
clear_stale_tmp() {
local running names=() n
running=$(pgrep -af 'steamwebhelper|steamrtarm64/steam|--type=|droiddeck-appimage-run|dbus-run-session|dbus-daemon.*--session|dbus-launch|kwin|plasmashell' 2>/dev/null)
running=$(pgrep -af 'steamwebhelper|steamrtarm64/steam|steamrt64/steam|--type=|droiddeck-appimage-run|dbus-run-session|dbus-daemon.*--session|dbus-launch|kwin|plasmashell' 2>/dev/null)
case $running in
*steamwebhelper* | *steamrtarm64/steam*) ;;
*steamwebhelper* | *steamrtarm64/steam* | *steamrt64/steam*) ;;
*) names+=(-o -name 'mangohud.????????' -o -name '.com.valvesoftware.Steam.??????'
-o -name 'steam_chrome_shmem_uid*' -o \( -type d -empty -name 'steam??????' \)) ;;
esac
@@ -56,13 +56,34 @@ clear_stale_tmp() {
}
[ -z "${BL_INSIDE:-}" ] && clear_stale_tmp
steam_update_stuck() {
[ "$1" -lt 60 ] || steam_updates=0
steam_updates=$((steam_updates + 1))
[ "$steam_updates" -ge 3 ]
}
run_gamescope() (
local status_file child_status compositor_status
status_file=$(mktemp "${XDG_RUNTIME_DIR:-/tmp}/droiddeck-steam-exit.XXXXXX") || exit 73
trap 'rm -f "$status_file"' EXIT
# Gamescope can return success when its primary child crashed.
BL_STEAM_EXIT_FILE="$status_file" gamescope "$@"
compositor_status=$?
if read -r child_status < "$status_file" && [[ $child_status =~ ^[0-9]{1,3}$ ]] \
&& [ "$child_status" -gt 0 ] && [ "$child_status" -le 255 ]; then
exit "$child_status"
fi
exit "$compositor_status"
)
collect_steam_logs() {
[ -n "${BL_DEBUG_DIR:-}" ] || return 0
local steam_root=${XDG_DATA_HOME:-$HOME/.local/share}/Steam
[ "${steam_x64:-0}" = 1 ] && steam_root=${BL_X64_HOME:-$HOME/.droiddeck-x64}/.local/share/Steam
mkdir -p "$BL_DEBUG_DIR/steam" 2>/dev/null || return 0
[ -d "$steam_root/logs" ] && find "$steam_root/logs" -maxdepth 1 -type f -size -8192k \
-exec cp {} "$BL_DEBUG_DIR/steam/" \; 2>/dev/null
[ -f "$HOME/.steam/steam/logs/steamwebhelper.log" ] && cp "$HOME/.steam/steam/logs/steamwebhelper.log" "$BL_DEBUG_DIR/steam/" 2>/dev/null
[ "${steam_x64:-0}" = 0 ] && [ -f "$HOME/.steam/steam/logs/steamwebhelper.log" ] && cp "$HOME/.steam/steam/logs/steamwebhelper.log" "$BL_DEBUG_DIR/steam/" 2>/dev/null
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
@@ -197,6 +218,9 @@ if [ -z "${BL_INSIDE:-}" ]; then
echo "== gamescope: games at ${nested}x${height} stretched to the ${width}x${height} output"
fi
fi
if [ "$mode" = steam ]; then
export gamescope_cursor_composite=2
fi
args=(--backend wayland --expose-wayland -f -W "$width" -H "$height" -w "$nested" -h "$height")
[ "$nested" != "$width" ] && args+=(-S stretch) && export BL_STRETCHED=1
if [ "${BL_FPS:-0}" -gt 0 ]; then
@@ -221,6 +245,10 @@ if [ -z "${BL_INSIDE:-}" ]; then
echo "== gamescope: mangoapp on ($(command -v mangoapp), config $MANGOHUD_CONFIGFILE)"
fi
export BL_INSIDE=1
if [ "$mode" = steam ]; then
run_gamescope "${args[@]}" -- "$0" "$mode" "$@"
exit $?
fi
exec gamescope "${args[@]}" -- "$0" "$mode" "$@"
fi
@@ -275,6 +303,24 @@ case $mode in
taskset -cp "$cores" $$ >/dev/null 2>&1 || true
fi
python3 /usr/local/bin/droiddeck-pad-defaults 2>&1 || true
run_program() {
local rc=0 child sig forwarded=0
{ trap - INT QUIT; exec "$@"; } <&0 &
child=$!
for sig in TERM HUP INT; do
trap "kill -$sig $child 2>/dev/null; forwarded=1" "$sig"
done
while :; do
forwarded=0
rc=0
wait "$child" || rc=$?
[ "$forwarded" = 1 ] || break
done
if [ -n "${BL_LAUNCH_DIR:-}" ]; then
printf '%s\n' "$rc" > "$BL_LAUNCH_DIR/run-status.tmp" && mv -f "$BL_LAUNCH_DIR/run-status.tmp" "$BL_LAUNCH_DIR/run-status"
fi
exit "$rc"
}
fex=()
if [ -x /usr/local/bin/droiddeck-fex ]; then
case $(od -An -tu2 -j18 -N2 "$target" 2>/dev/null | tr -d ' ') in
@@ -285,32 +331,67 @@ case $mode in
*.appimage)
export APPIMAGE_EXTRACT_AND_RUN=1
chmod +x "$target" 2>/dev/null
exec "${fex[@]}" "$target" "$@"
run_program "${fex[@]}" "$target" "$@"
;;
*.sh)
if [ -x /usr/local/bin/droiddeck-fex ]; then
exec /usr/local/bin/droiddeck-fex run --for "$target" -- bash "$target" "$@"
run_program /usr/local/bin/droiddeck-fex run --for "$target" -- bash "$target" "$@"
fi
exec bash "$target" "$@"
run_program bash "$target" "$@"
;;
*)
chmod +x "$target" 2>/dev/null
cd "$(dirname "$target")" && exec "${fex[@]}" "$target" "$@"
cd "$(dirname "$target")" && run_program "${fex[@]}" "$target" "$@"
;;
esac
;;
steam)
step "checking the Steam client (first run downloads it, ~1-2 min with nothing on screen)"
droiddeck-steam-install || exit $?
step "Steam client ready"
steam_root=$XDG_DATA_HOME/Steam
steam_x64=0
[ "${BL_STEAM_CLIENT_ARCH:-}" = x86_64 ] && steam_x64=1
steam_cef_gpu=1
if [ "$steam_x64" = 1 ]; then
step "checking the Steam client's arm64 parts (first run downloads them, ~1-2 min)"
# droiddeck-steam-install removes the repair request: read it first so Repair Steam covers both clients.
_bl_x64_repair=0
[ -e "$HOME/.bl-steam-repair" ] && _bl_x64_repair=1
droiddeck-steam-install || exit $?
droiddeck-steam-install --sync steamdeck_publicbeta || step "could not update the arm64 client's parts; the x86-64 client keeps its own web helper"
step "checking the x86-64 Steam client (FEX, experimental; the first run downloads ~2 GB)"
BL_X64_REPAIR=$_bl_x64_repair droiddeck-steam-x64 --prepare || exit $?
step "x86-64 Steam client ready"
steam_root=${BL_X64_HOME:-$HOME/.droiddeck-x64}/.local/share/Steam
steam_client=(droiddeck-steam-x64 --exec)
if [ "${BL_X64_X86_WEBHELPER:-0}" = 1 ] &&
! droiddeck-steam-x64 --webhelper-gpu; then
steam_cef_gpu=0
fi
else
step "checking the Steam client (first run downloads it, ~1-2 min with nothing on screen)"
droiddeck-steam-install || exit $?
step "Steam client ready"
steam_root=$XDG_DATA_HOME/Steam
if [ -f "${BL_X64_HOME:-$HOME/.droiddeck-x64}/.local/share/Steam/local.vdf" ]; then
droiddeck-steam-x64 --sync-login || true
fi
steam_client=("$steam_root/steamrtarm64/steam")
fi
_bl_proton_root=$steam_root
if [ "$steam_x64" = 1 ]; then
_bl_proton_root=$XDG_DATA_HOME/Steam
if ! ls -d "$_bl_proton_root"/compatibilitytools.d/GE-Proton*-aarch64 >/dev/null 2>&1 &&
! grep -q '^ge' "$HOME/.bl-proton-extra" 2>/dev/null; then
echo ge >> "$HOME/.bl-proton-extra"
fi
fi
if [ -s "$HOME/.bl-proton-extra" ]; then
_bl_left=$HOME/.bl-proton-extra.left
: > "$_bl_left"
_bl_got_proton=0
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 droiddeck-proton-extra "$steam_root" $_bl_extra; then
if droiddeck-proton-extra "$_bl_proton_root" $_bl_extra; then
_bl_got_proton=1
step "installed Proton '$_bl_extra'"
else
step "Proton '$_bl_extra' failed; will retry next session"
@@ -318,6 +399,9 @@ case $mode in
fi
done < "$HOME/.bl-proton-extra"
mv -f "$_bl_left" "$HOME/.bl-proton-extra"
if [ "$steam_x64" = 1 ] && [ "$_bl_got_proton" = 1 ]; then
droiddeck-steam-x64 --prepare || true
fi
fi
if [ -s "$HOME/.bl-steam-urls" ]; then
while read -r _bl_url || [ -n "$_bl_url" ]; do
@@ -329,23 +413,6 @@ case $mode in
fi
if [ -n "${BL_CLIENT_CPUS:-}" ]; then
step "client cores: $BL_CLIENT_CPUS"
(
declare -A _bl_pinned=()
for ((_i = 0; _i < 720; _i++)); do
for _d in /proc/[0-9]*; do
IFS= read -r -d '' _c < "$_d/cmdline" 2>/dev/null || continue
case $_c in *steamwebhelper*|*steamrtarm64/steam|*gamescope*) ;; *) continue ;; esac
_t=("$_d"/task/*)
_p=${_d#/proc/}
if [ "${_bl_pinned[$_p]:-}" = "${#_t[@]}" ] && client_single_core_matches "$BL_CLIENT_CPUS" "${_t[@]}"; then
continue
fi
taskset -a -cp "$BL_CLIENT_CPUS" "$_p" >/dev/null 2>&1 || true
_bl_pinned[$_p]=${#_t[@]}
done
nap 5
done
) &
fi
if [ "${BL_ZRAM:-0}" = 1 ]; then
printf 0 > /tmp/.bl-zram
@@ -354,7 +421,9 @@ case $mode in
bl_zram_scan() {
_bl_game=0 _bl_pids=()
for _d in /proc/[0-9]*; do
IFS= read -r -d '' _c 2>/dev/null < "$_d/cmdline" || continue
# Under FEX the program is FEX's first argument.
{ IFS= read -r -d '' _c && case ${_c##*/} in FEX|FEXInterpreter) IFS= read -r -d '' _c ;; esac; } \
2>/dev/null < "$_d/cmdline" || continue
case ${_c##*/} in
reaper) _bl_game=1 ;;
steam|steamwebhelper) _bl_pids+=("${_d#/proc/}") ;;
@@ -403,6 +472,7 @@ case $mode in
/usr/local/bin/droiddeck-launcher-cores "$BL_LAUNCH_DIR/agent/focus.json" 2>&1 &
fi
if [ "$steam_x64" = 0 ]; then
step "registering the app's game library with Steam"
droiddeck-steam-library "$steam_root" || true
step "setting up the ARM64 Proton compatibility tool"
@@ -415,7 +485,22 @@ case $mode in
droiddeck-steam-shortcuts "$steam_root" "$BL_ADDED_GAMES" || true
fi
droiddeck-seed-redists "$steam_root" || true
if [ ! -f "$steam_root/steamapps/appmanifest_4427310.acf" ]; then
else
_bl_x64_tool=$(droiddeck-steam-x64 --default-tool)
if [ -n "$_bl_x64_tool" ]; then
if [ -n "${BL_ADDED_GAMES:-}" ]; then
step "adding the app's own games to the x86-64 client's library"
BL_COMPAT_TOOL=$_bl_x64_tool droiddeck-steam-shortcuts "$steam_root" "$BL_ADDED_GAMES" || true
fi
step "pointing the x86-64 client's Windows titles at $_bl_x64_tool"
BL_COMPAT_TOOL=$_bl_x64_tool steam-compatibility "$steam_root" --x64 || true
fi
if [ -z "${BL_DESKTOP:-}" ] && [ "${BL_STEAM_UI:-}" != desktop ]; then
droiddeck-steam-ui-scale "$steam_root" "${BL_WIDTH:-1280}" "${BL_HEIGHT:-720}" || true
fi
droiddeck-seed-redists "$steam_root" || true
fi
if [ "$steam_x64" = 0 ] && [ ! -f "$steam_root/steamapps/appmanifest_4427310.acf" ]; then
step "asking the client to fetch the ARM64 Proton"
set -- "$@" steam://install/4427310
(
@@ -427,7 +512,7 @@ case $mode in
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
"${steam_client[@]}" -shutdown >/dev/null 2>&1 || true
exit 0
fi
done
@@ -451,7 +536,7 @@ case $mode in
sleep 10
[ -f "$_bl_acf" ] && exit 0
step "signed in: asking the client again for the ARM64 Proton (try $_bl_try of 3)"
"$steam_root/steamrtarm64/steam" steam://install/4427310 >/dev/null 2>&1 || true
"${steam_client[@]}" steam://install/4427310 >/dev/null 2>&1 || true
sleep 50
done
exit 0
@@ -460,116 +545,104 @@ case $mode in
) &
fi
fi
[ -z "${BL_DESKTOP:-}" ] && [ "${BL_STRETCHED:-0}" = 1 ] && (
while :; do
nap 1
cur=$(xprop -root GAMESCOPE_NEW_SCALING_SCALER 2>/dev/null) || continue
case $cur in *" = "*) cur=${cur##* = } ;; *) cur=0 ;; esac
[ "$cur" = 0 ] || continue
xprop -root -f GAMESCOPE_NEW_SCALING_SCALER 32c -set GAMESCOPE_NEW_SCALING_SCALER 4 2>/dev/null \
&& echo "== stretch 16:9 to panel: the client's scaler was Auto, set to Stretch"
done
) &
[ -z "${BL_DESKTOP:-}" ] && [ "${BL_RESTORE_ON_RESUME:-1}" = 1 ] && (
prev=
xprop -spy -root GAMESCOPE_FOCUSED_APP 2>/dev/null | while read -r line; do
app=${line##*= }
case $app in ''|*[!0-9]*) prev=; continue ;; esac
if [ "$prev" = 769 ] && [ "$app" != 769 ]; then
nap 1
bl_xprop_set_all GAMESCOPE_RESTORE_FOCUS_WINDOW 1 \
&& echo "== resume: asked gamescope to restore the game window (app $app)"
fi
prev=$app
done
) &
[ -z "${BL_DESKTOP:-}" ] && (
xprop_value() {
case $1 in *'not found'*|*=) echo "$2"; return ;; esac
local v=${1#*=}
v=${v# }
echo "${v:-$2}"
stretch=0 restore=0
[ "${BL_STRETCHED:-0}" = 1 ] && stretch=1
[ "${BL_RESTORE_ON_RESUME:-1}" = 1 ] && restore=1
atoms=(STEAM_TOUCH_CLICK_MODE GAMESCOPE_FOCUSED_APP)
[ "$stretch" = 1 ] && atoms+=(GAMESCOPE_NEW_SCALING_SCALER)
prop_value() {
case $1 in *'not found'*|*=) pv=$2; return ;; esac
pv=${1#*=}
pv=${pv# }
pv=${pv:-$2}
}
tmode= app=
xprop -spy -root STEAM_TOUCH_CLICK_MODE GAMESCOPE_FOCUSED_APP 2>/dev/null | while read -r line; do
tmode= app= prev=
while read -r line; do
case $line in
STEAM_TOUCH_CLICK_MODE*)
v=$(xprop_value "$line" unset)
[ "$v" = "$tmode" ] && continue
tmode=$v
prop_value "$line" unset
[ "$pv" = "$tmode" ] && continue
tmode=$pv
echo "== touch mode: $tmode (focused app ${app:-?}) at $(date +%T)"
;;
GAMESCOPE_FOCUSED_APP*)
v=$(xprop_value "$line" none)
[ "$v" = "$app" ] && continue
app=$v
echo "== focused app: $app (touch mode ${tmode:-unset}) at $(date +%T)"
prop_value "$line" none
if [ "$pv" != "$app" ]; then
app=$pv
echo "== focused app: $app (touch mode ${tmode:-unset}) at $(date +%T)"
if [ -n "${BL_LAUNCH_DIR:-}" ]; then
printf '%s\n' "$app" > "$BL_LAUNCH_DIR/steam-focused-app.tmp" && mv -f "$BL_LAUNCH_DIR/steam-focused-app.tmp" "$BL_LAUNCH_DIR/steam-focused-app"
fi
fi
[ "$restore" = 1 ] || continue
case $pv in ''|*[!0-9]*) prev=; continue ;; esac
if [ "$prev" = 769 ] && [ "$pv" != 769 ]; then
nap 1
bl_xprop_set_all GAMESCOPE_RESTORE_FOCUS_WINDOW 1 \
&& echo "== resume: asked gamescope to restore the game window (app $pv)"
fi
prev=$pv
;;
GAMESCOPE_NEW_SCALING_SCALER*)
prop_value "$line" 0
[ "$pv" = 0 ] || continue
xprop -root -f GAMESCOPE_NEW_SCALING_SCALER 32c -set GAMESCOPE_NEW_SCALING_SCALER 4 2>/dev/null \
&& echo "== stretch 16:9 to panel: the client's scaler was Auto, set to Stretch"
;;
esac
done
done < <(xprop -spy -root "${atoms[@]}" 2>/dev/null)
) &
(
beat=0
compat_stamp=$HOME/.bl-compat-beat
seed_stamp=$HOME/.bl-seed-beat
rm -f "$compat_stamp" "$seed_stamp"
changed_since() {
local d
for d in "${@:2}"; do
[ "$d" -nt "$1" ] && return 0
done
return 1
}
compat_due() {
[ -e "$compat_stamp" ] && [ "$((beat % 60))" -ne 0 ] || return 0
changed_since "$compat_stamp" "${libraries[@]}" "$steam_root/steamapps/common" "$steam_root/config" \
"$steam_root/compatibilitytools.d"
}
seed_due() {
local reg
[ -e "$seed_stamp" ] && [ "$((beat % 60))" -ne 0 ] || return 0
changed_since "$seed_stamp" "${libraries[@]}" && return 0
for reg in "$steam_root"/steamapps/common/Proton*/files/share/default_pfx*/system.reg \
/mnt/droiddeck-sd/steamapps/common/Proton*/files/share/default_pfx*/system.reg \
/root/Games/*/steamapps/common/Proton*/files/share/default_pfx*/system.reg \
"$steam_root"/compatibilitytools.d/*/files/share/default_pfx*/system.reg \
"$steam_root"/steamapps/compatdata/*/pfx/system.reg \
/mnt/droiddeck-sd/steamapps/compatdata/*/pfx/system.reg \
/root/Games/*/steamapps/compatdata/*/pfx/system.reg; do
[ -f "$reg" ] && [ ! -f "${reg%/*}/.droiddeck-redists" ] && return 0
done
return 1
}
for ((_i = 0; _i < 720; _i++)); do
nap 5
beat=$((beat + 1))
[ "$((beat % 3))" -eq 0 ] || continue
libraries=("$steam_root/steamapps" /mnt/droiddeck/steamapps /mnt/droiddeck-sd/steamapps /root/Games/*/steamapps)
seed=; compat=
seed_due && seed=1
compat_due && compat=1
[ -n "$seed$compat" ] || continue
pgrep -x wineserver >/dev/null 2>&1 && continue
if [ -n "$seed" ]; then
: > "$seed_stamp"
droiddeck-seed-redists "$steam_root" >/dev/null 2>&1 || true
fi
if [ -n "$compat" ]; then
: > "$compat_stamp"
steam-compatibility "$steam_root" >/dev/null 2>&1 || true
fi
steam_hold_launch() {
_bl_launch_ready=
_bl_end=$((SECONDS + 120))
until [ "$(xprop -root GAMESCOPE_FOCUSED_APP 2>/dev/null | sed -n 's/.*= *//p')" = 769 ] || [ "$SECONDS" -ge "$_bl_end" ]; do
sleep 1
done
) &
# With a large library the overview can stay missing for 30+ minutes while Steam already takes the launch URL.
_bl_overview_status=1
_bl_overview_tries=0
while [ "$_bl_overview_tries" -lt 2 ]; do
if /usr/local/bin/droiddeck-agent --wait-steam-shortcut-overview "$1" 45; then
_bl_overview_status=0
else
_bl_overview_status=$?
fi
if [ "$_bl_overview_status" -ne 1 ]; then
break
fi
_bl_overview_tries=$((_bl_overview_tries + 1))
echo "== steam: shortcut overview not ready yet (attempt $_bl_overview_tries of 2)"
sleep 2
done
if [ "$_bl_overview_status" -eq 0 ]; then
echo "== steam: shortcut overview ready; launching the requested game $1"
_bl_launch_ready=1
elif [ "$_bl_overview_status" -eq 3 ]; then
echo "== steam: not a shortcut CGameID; keeping the existing launch path"
sleep 4
_bl_launch_ready=1
else
echo "== steam: shortcut overview not ready after about 90 s; launching the requested game anyway $1"
_bl_launch_ready=1
fi
if [ "$_bl_launch_ready" = 1 ]; then
echo "== steam: interface up; launching the requested game $1"
printf '%s\n' "$1" > "$BL_LAUNCH_DIR/steam-game.tmp" && mv -f "$BL_LAUNCH_DIR/steam-game.tmp" "$BL_LAUNCH_DIR/steam-game"
fi
}
if [ -n "${BL_LAUNCH_DIR:-}" ] && [ -z "${BL_DESKTOP:-}" ]; then
_bl_held=
_bl_uninstall=
_bl_rest=()
for _bl_arg in "$@"; do
case $_bl_arg in
steam://rungameid/*) _bl_held=${_bl_arg#steam://rungameid/} ;;
steam://uninstall/*) _bl_uninstall=${_bl_arg#steam://uninstall/} ;;
*) _bl_rest+=("$_bl_arg") ;;
esac
done
if [ -n "$_bl_held" ]; then
if [ -n "$_bl_uninstall" ]; then
set -- "${_bl_rest[@]}"
(
_bl_end=$((SECONDS + 120))
@@ -577,10 +650,14 @@ case $mode in
sleep 1
done
sleep 4
echo "== steam: interface up; launching the requested game $_bl_held"
printf '%s\n' "$_bl_held" > "$BL_LAUNCH_DIR/steam-game.tmp" && mv -f "$BL_LAUNCH_DIR/steam-game.tmp" "$BL_LAUNCH_DIR/steam-game"
echo "== steam: interface up; asking to uninstall $_bl_uninstall"
printf '%s\n' "$_bl_uninstall" > "$BL_LAUNCH_DIR/steam-uninstall.tmp" && mv -f "$BL_LAUNCH_DIR/steam-uninstall.tmp" "$BL_LAUNCH_DIR/steam-uninstall"
) &
fi
if [ -n "$_bl_held" ]; then
set -- "${_bl_rest[@]}"
steam_hold_launch "$_bl_held" &
fi
fi
if [ -s "$HOME/.bl-autolaunch" ]; then
_bl_app=$(cat "$HOME/.bl-autolaunch")
@@ -616,11 +693,9 @@ BUSCONF
sleep 0.1
done
if [ -S /run/dbus/system_bus_socket ]; then
droiddeck-netmanager &
netmanager=$!
echo "== network: system bus up, NetworkManager stand-in running"
rm -f "$BL_LAUNCH_DIR/steam-sleep-ready"
droiddeck-login1 &
droiddeck-login1 --with-netmanager &
login_manager=$!
for ((_i = 0; _i < 50; _i++)); do
[ -f "$BL_LAUNCH_DIR/steam-sleep-ready" ] && break
@@ -641,6 +716,10 @@ BUSCONF
exit 69
fi
# The UI bridge launches SteamVR, which needs the guest agent's library environment.
_bl_compat_env=(env -u LD_LIBRARY_PATH -u STEAM_RUNTIME)
[ "${LD_LIBRARY_PATH+x}" ] && _bl_compat_env+=("LD_LIBRARY_PATH=$LD_LIBRARY_PATH")
[ "${STEAM_RUNTIME+x}" ] && _bl_compat_env+=("STEAM_RUNTIME=$STEAM_RUNTIME")
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
@@ -691,23 +770,26 @@ BUSCONF
echo "== steam: devtools port $BL_CDP_PORT, guest processes only"
fi
[ -n "${BL_LAUNCH_DIR:-}" ] && mkdir -p "$BL_LAUNCH_DIR/agent" && echo "$BL_CDP_PORT" > "$BL_LAUNCH_DIR/agent/cdp-port"
droiddeck-steam-compat "$steam_root" 2>&1 &
[ "$steam_x64" = 1 ] || "${_bl_compat_env[@]}" droiddeck-steam-compat "$steam_root" 2>&1 &
_bl_ui=(-gamepadui)
[ "${BL_STEAM_UI:-}" = desktop ] && _bl_ui=()
_bl_cef=(-cef-force-gpu -cef-use-gl=angle -cef-use-angle=vulkan)
[ "${steam_cef_gpu:-1}" = 1 ] || _bl_cef=(-cef-disable-gpu)
if [ "${BL_DESKTOP:-}" = 1 ] && [ "${BL_STEAM_UI:-}" = desktop ]; then
_bl_cef=(-cef-disable-gpu)
_bl_ui=(-nobigpicture)
fi
if [ "${BL_STEAM_UI:-}" != desktop ]; then
_bl_ui+=(-steamdeck -steamos3)
export STEAM_GAMESCOPE_NIS_SUPPORTED=1
export STEAM_GAMESCOPE_FANCY_SCALING_SUPPORT=1
echo "== steam: Deck mode on (-steamdeck -steamos3)"
if [ "$steam_x64" = 0 ] || [ "${BL_X64_DECK:-1}" != 0 ]; then
_bl_ui+=(-steamdeck -steamos3)
export STEAM_GAMESCOPE_NIS_SUPPORTED=1
export STEAM_GAMESCOPE_FANCY_SCALING_SUPPORT=1
echo "== steam: Deck mode on (-steamdeck -steamos3)"
fi
fi
export STEAMOS_STEAM_SHUTDOWN_SENTINEL="$HOME/.bl-steam-shutdown"
export STEAMOS_STEAM_REBOOT_SENTINEL="$HOME/.bl-steam-reboot"
if ! pgrep -f 'steamwebhelper|steamrtarm64/steam' >/dev/null 2>&1; then
if ! pgrep -f 'steamwebhelper|steamrtarm64/steam|steamrt64/steam' >/dev/null 2>&1; then
_stale=""
for _f in "$steam_root/.crash" "$steam_root/steam.pid" \
"$steam_root/config/htmlcache/SingletonLock" "$steam_root/config/htmlcache/SingletonCookie" \
@@ -722,28 +804,93 @@ BUSCONF
[ -n "${BL_STEAM_LANGUAGE:-}" ] && _bl_lang=(-language "$BL_STEAM_LANGUAGE")
steam_beta=$steam_root/package/beta
if [ -n "${BL_ADDED_GAMES:-}" ] && [ -f "$BL_ADDED_GAMES" ]; then
droiddeck-steam-games watch "$steam_root" "$BL_ADDED_GAMES" &
if [ "$steam_x64" = 0 ]; then
droiddeck-steam-games watch "$steam_root" "$BL_ADDED_GAMES" &
else
BL_STEAMCLIENT=$XDG_DATA_HOME/Steam/steamrtarm64/steamclient.so \
BL_STEAM_SHUTDOWN="droiddeck-steam-x64 --exec -shutdown" \
droiddeck-steam-games watch "$steam_root" "$BL_ADDED_GAMES" &
fi
games_watcher=$!
fi
if [ "${BL_LOSSLESS_OWNED:-0}" != 1 ]; then
(
owned=$HOME/.config/droiddeck/lossless-owned
for ((_i = 0; _i < 60; _i++)); do
nap 30
[ -e "$owned" ] && exit 0
pgrep -x wineserver >/dev/null 2>&1 && 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" ;;
esac
exit 0
done
) &
fi
echo "== steam args: ${_bl_ui[*]} ${_bl_cdp[*]} ${_bl_lang[*]} -clientbeta $steam_channel -no-cef-sandbox -cef-ozone-platform=x11 ${_bl_cef[*]} $*"
echo "== steam args: ${_bl_ui[*]} ${_bl_cdp[*]} ${_bl_lang[*]} -clientbeta $steam_channel -no-cef-sandbox -cef-ozone-platform=x11 ${_bl_cef[*]} $*$([ "$steam_x64" = 1 ] && echo ' (x86-64 client under FEX)')"
steam_updates=0
rm -f "$HOME/.bl-stop-requested" "$STEAMOS_STEAM_SHUTDOWN_SENTINEL" "$STEAMOS_STEAM_REBOOT_SENTINEL"
steam_other_game_running() {
local line value n open
open=$(cat "$BL_LAUNCH_DIR/epic-open" 2>/dev/null)
case $open in ?|*[!0-9]*) open=${BL_EPIC_APP_ID:-$open} ;; esac
line=$(xprop -root GAMESCOPE_FOCUSABLE_APPS 2>/dev/null) || return 1
case $line in *=*) value=${line#*= } ;; *) return 1 ;; esac
for n in ${value//,/ }; do
[ "$n" = 769 ] || [ "$n" = "$open" ] || return 0
done
return 1
}
steam_restart_for() {
if [ "$(cat "$HOME/.bl-restarted-for" 2>/dev/null)" = "$1" ]; then
echo "== steam: $2, but Steam was already restarted for it; launching it anyway"
return 1
fi
printf '%s\n' "$1" > "$HOME/.bl-restarted-for"
echo "== steam: $2; restarting Steam to launch it"
printf '%s\n' "$1" > "$HOME/.bl-restart-game"
"${steam_client[@]:-$steam_root/steamrtarm64/steam}" -shutdown >/dev/null 2>&1
}
steam_launch_game() {
local state=0 tries
/usr/local/bin/droiddeck-agent --steam-shortcut-state "$1" 6 >/dev/null 2>&1 || state=$?
[ "$state" -eq 0 ] && rm -f "$HOME/.bl-restarted-for"
if [ "$state" -eq 4 ]; then
if steam_other_game_running; then
echo "== steam: the client lost shortcut $1, but a game is running; launching it anyway"
elif steam_restart_for "$1" "the client lost shortcut $1"; then
return
fi
fi
"${steam_client[@]:-$steam_root/steamrtarm64/steam}" "steam://rungameid/$1" >/dev/null 2>&1
[ "$state" -eq 3 ] && return
for tries in 1 2 3 4 5 6 7 8; do
nap 1
state=0
/usr/local/bin/droiddeck-agent --steam-shortcut-state "$1" 1 >/dev/null 2>&1 || state=$?
[ "$state" -eq 4 ] || continue
if steam_other_game_running; then
echo "== steam: the client dropped shortcut $1 while launching it, but a game is running"
else
steam_restart_for "$1" "the client dropped shortcut $1 while launching it"
fi
return 0
done
}
steam_check_exits() {
local ran n state lost=
ran=$(pgrep -a -f 'SteamLaunch AppId=[0-9]' 2>/dev/null | sed -n 's/.* SteamLaunch AppId=\([0-9]*\).*/\1/p')
if [ -n "$ran" ]; then
for n in $ran; do
[ "$n" -ge 2147483648 ] && _bl_ran[$n]=1
done
_bl_exited=
return
fi
[ "${#_bl_ran[@]}" -gt 0 ] || return 0
if [ -z "$_bl_exited" ]; then
_bl_exited=1
return
fi
_bl_exited=
for n in "${!_bl_ran[@]}"; do
state=0
/usr/local/bin/droiddeck-agent --steam-shortcut-state "$(printf '%u' $(((n << 32) | 0x02000000)))" 3 >/dev/null 2>&1 || state=$?
[ "$state" -eq 4 ] && lost="$lost $n"
done
_bl_ran=()
[ -n "$lost" ] || return 0
pgrep -f 'SteamLaunch AppId=[0-9]' >/dev/null 2>&1 && return 0
echo "== steam: the client dropped shortcut(s)$lost when they exited; restarting Steam so it lists them again"
: > "$HOME/.bl-restart-lost"
"${steam_client[@]:-$steam_root/steamrtarm64/steam}" -shutdown >/dev/null 2>&1
}
steam_bring_forward() {
local end=$((SECONDS + 600)) behind=0 line name value focused other n
while [ "$SECONDS" -lt "$end" ]; do
@@ -767,17 +914,95 @@ BUSCONF
return 0
done
}
requests=
if [ -n "${BL_LAUNCH_DIR:-}" ] && [ -d "$BL_LAUNCH_DIR" ]; then
rm -f "$BL_LAUNCH_DIR/steam-stop" "$BL_LAUNCH_DIR/steam-game" "$BL_LAUNCH_DIR/steam-game.tmp"
(
while :; do
requests=1
fi
(
tick=0
beat=0
library_job=
lossless_job=
lossless_left=0
lossless_owned=$HOME/.config/droiddeck/lossless-owned
lossless_asked=$HOME/.bl-lossless-asked
rm -f "$lossless_asked"
[ "${BL_LOSSLESS_OWNED:-0}" != 1 ] && lossless_left=60
declare -A _bl_pinned=()
declare -A _bl_ran=()
_bl_exited=
compat_stamp=$HOME/.bl-compat-beat
seed_stamp=$HOME/.bl-seed-beat
rm -f "$compat_stamp" "$seed_stamp"
changed_since() {
local d
for d in "${@:2}"; do
[ "$d" -nt "$1" ] && return 0
done
return 1
}
compat_due() {
[ -e "$compat_stamp" ] && [ "$((beat % 60))" -ne 0 ] || return 0
changed_since "$compat_stamp" "${libraries[@]}" "$steam_root/steamapps/common" "$steam_root/config" \
"$steam_root/compatibilitytools.d"
}
seed_due() {
local reg
[ -e "$seed_stamp" ] && [ "$((beat % 60))" -ne 0 ] || return 0
changed_since "$seed_stamp" "${libraries[@]}" && return 0
for reg in "$steam_root"/steamapps/common/Proton*/files/share/default_pfx*/system.reg \
/mnt/droiddeck-sd/steamapps/common/Proton*/files/share/default_pfx*/system.reg \
/root/Games/*/steamapps/common/Proton*/files/share/default_pfx*/system.reg \
"$steam_root"/compatibilitytools.d/*/files/share/default_pfx*/system.reg \
"$steam_root"/steamapps/compatdata/*/pfx/system.reg \
/mnt/droiddeck-sd/steamapps/compatdata/*/pfx/system.reg \
/root/Games/*/steamapps/compatdata/*/pfx/system.reg; do
[ -f "$reg" ] && [ ! -f "${reg%/*}/.droiddeck-redists" ] && return 0
done
return 1
}
compat_pending=$HOME/.bl-compat-pending
compat_restarted=$HOME/.bl-compat-restarted
rm -f "$compat_pending"
: > "$compat_restarted"
compat_restarts=0
compat_settled() {
local app m flags r card=/mnt/droiddeck-sd
# The arm64 card library may hold that client's copy of the same title.
[ "$steam_x64" = 1 ] && card=/mnt/droiddeck-sd/x86-64
while read -r app; do
[ -n "$app" ] || continue
m=
for r in "$steam_root" "$card"; do
[ -f "$r/steamapps/appmanifest_$app.acf" ] && { m=$r/steamapps/appmanifest_$app.acf; break; }
done
[ -n "$m" ] || return 1
flags=$(sed -n 's/^[[:space:]]*"StateFlags"[[:space:]]*"\([0-9]*\)".*/\1/p' "$m" | head -n 1)
[ "$flags" = 4 ] || return 1
done < "$compat_pending"
! pgrep -f 'reaper SteamLaunch' >/dev/null 2>&1
}
while :; do
if [ -n "$requests" ]; then
if [ -e "$BL_LAUNCH_DIR/steam-stop" ]; then
rm -f "$BL_LAUNCH_DIR/steam-stop"
: > "$HOME/.bl-stop-requested"
echo "== steam: the app asked for a clean exit"
"$steam_root/steamrtarm64/steam" -shutdown >/dev/null 2>&1 || true
"${steam_client[@]}" -shutdown >/dev/null 2>&1 || true
exit 0
fi
if [ -f "$BL_LAUNCH_DIR/steam-uninstall" ]; then
uninstall_id=$(cat "$BL_LAUNCH_DIR/steam-uninstall" 2>/dev/null)
rm -f "$BL_LAUNCH_DIR/steam-uninstall"
case $uninstall_id in
''|0*|*[!0-9]*|???????????*) echo "== steam: ignored invalid uninstall request" ;;
*)
echo "== steam: opening the uninstall dialog for $uninstall_id"
"${steam_client[@]}" "steam://uninstall/$uninstall_id" >/dev/null 2>&1 &
;;
esac
fi
if [ -f "$BL_LAUNCH_DIR/steam-game" ]; then
game_id=$(cat "$BL_LAUNCH_DIR/steam-game" 2>/dev/null)
rm -f "$BL_LAUNCH_DIR/steam-game"
@@ -789,7 +1014,7 @@ BUSCONF
[ "$game_id_length" -eq 20 ] && [[ "$game_id" < "18446744073709551616" ]];
}; then
echo "== steam: launching requested game $game_id in the running client"
"$steam_root/steamrtarm64/steam" "steam://rungameid/$game_id" >/dev/null 2>&1 &
steam_launch_game "$game_id" &
[ -n "${forward_pid:-}" ] && kill "$forward_pid" 2>/dev/null
steam_bring_forward &
forward_pid=$!
@@ -799,13 +1024,86 @@ BUSCONF
;;
esac
fi
nap 0.5
done
) &
stop_watcher=$!
fi
fi
nap 0.5
tick=$((tick + 1))
[ "$((tick % 10))" -eq 0 ] || continue
beat=$((beat + 1))
steam_check_exits
if [ "$beat" -le 720 ] && [ -n "${BL_CLIENT_CPUS:-}" ]; then
for _d in /proc/[0-9]*; do
{ IFS= read -r -d '' _c && { IFS= read -r -d '' _c1 || _c1=; }; } < "$_d/cmdline" 2>/dev/null || continue
case $_c in FEX|*/FEX|FEXInterpreter|*/FEXInterpreter) _c=$_c1 ;; esac
case $_c in *steamwebhelper*|*steamrtarm64/steam|*steamrt64/steam|*gamescope*) ;; *) continue ;; esac
_t=("$_d"/task/*)
_p=${_d#/proc/}
[ "${_bl_pinned[$_p]:-}" = "${#_t[@]}" ] && client_single_core_matches "$BL_CLIENT_CPUS" "${_t[@]}" && continue
taskset -a -cp "$BL_CLIENT_CPUS" "$_p" >/dev/null 2>&1 || true
_bl_pinned[$_p]=${#_t[@]}
done
fi
if [ "$beat" -le 720 ] && [ "$((beat % 3))" -eq 0 ] && { [ -z "$library_job" ] || ! kill -0 "$library_job" 2>/dev/null; }; then
libraries=("$steam_root/steamapps" /mnt/droiddeck/steamapps /mnt/droiddeck-sd/steamapps /root/Games/*/steamapps)
seed=; compat=
seed_due && seed=1
compat_due && compat=1
if [ -n "$seed$compat" ] && ! pgrep -x wineserver >/dev/null 2>&1; then
[ -n "$seed" ] && : > "$seed_stamp"
[ -n "$compat" ] && : > "$compat_stamp"
(
[ -z "$seed" ] || droiddeck-seed-redists "$steam_root" >/dev/null 2>&1 || true
if [ -n "$compat" ]; then
if [ "$steam_x64" = 1 ]; then
[ -z "${_bl_x64_tool:-}" ] ||
BL_COMPAT_TOOL=$_bl_x64_tool steam-compatibility "$steam_root" --x64 --live >/dev/null 2>&1 || true
droiddeck-steam-x64 --map-direct --live >/dev/null 2>&1 || true
else
steam-compatibility "$steam_root" >/dev/null 2>&1 || true
fi
fi
) &
library_job=$!
fi
fi
if [ "$((beat % 3))" -eq 0 ] && [ -s "$compat_pending" ] && [ "$compat_restarts" -lt 3 ] && compat_settled; then
_bl_new=$(sort -u "$compat_pending" | grep -vxF -f "$compat_restarted" || true)
rm -f "$compat_pending"
if [ -n "$_bl_new" ]; then
compat_restarts=$((compat_restarts + 1))
printf '%s\n' $_bl_new >> "$compat_restarted"
if [ "$steam_x64" = 1 ]; then
step "newly installed title(s) $(echo $_bl_new) set to an ARM64 Proton (Windows builds) or DroidDeck direct (Linux builds): restarting the Steam client once so it takes effect"
else
step "newly installed title(s) $(echo $_bl_new) set to the ARM64 Proton: restarting the Steam client once so it takes effect"
fi
: > "$HOME/.bl-restart-once"
"${steam_client[@]}" -shutdown >/dev/null 2>&1 || true
fi
fi
if [ "$lossless_left" -gt 0 ] && [ "$((beat % 6))" -eq 0 ] && { [ -z "$lossless_job" ] || ! kill -0 "$lossless_job" 2>/dev/null; }; then
lossless_left=$((lossless_left - 1))
if [ -e "$lossless_owned" ] || [ -e "$lossless_asked" ]; then
lossless_left=0
elif ! pgrep -x wineserver >/dev/null 2>&1; then
(
# The probe reaches the x86-64 client through the arm64 client's steamclient.so, as the import watcher does.
if [ "$steam_x64" = 1 ]; then export BL_STEAMCLIENT=$XDG_DATA_HOME/Steam/steamrtarm64/steamclient.so; fi
answer=$(droiddeck-steam-games probe "$steam_root" 993090 2>/dev/null) || exit 0
case $answer in
*'"993090": true'*) mkdir -p "${lossless_owned%/*}" && : > "$lossless_owned" && echo "== Lossless Scaling: owned" ;;
*) echo "== Lossless Scaling: not owned by this account" ;;
esac
: > "$lossless_asked"
) &
lossless_job=$!
fi
fi
done
) &
stop_watcher=$!
rm -f "$HOME/.bl-restart-game" "$HOME/.bl-restarted-for"
while :; do
rm -f "$HOME/.bl-restart-once"
rm -f "$HOME/.bl-restart-once" "$HOME/.bl-restart-lost"
if [ -f "$steam_beta" ] && [ "$(cat "$steam_beta" 2>/dev/null)" != "$steam_channel" ]; then
echo "== steam: client branch on disk was '$(cat "$steam_beta" 2>/dev/null)', set to '$steam_channel' to match -clientbeta"
echo "$steam_channel" > "$steam_beta"
@@ -815,7 +1113,11 @@ BUSCONF
_bl_counted=1
fi
if [ -n "${BL_STEAM_LANGUAGE:-}" ]; then
droiddeck-steam-language "$HOME" "$BL_STEAM_LANGUAGE" || true
if [ "$steam_x64" = 1 ]; then
droiddeck-steam-language "${BL_X64_HOME:-$HOME/.droiddeck-x64}" "$BL_STEAM_LANGUAGE" || true
else
droiddeck-steam-language "$HOME" "$BL_STEAM_LANGUAGE" || true
fi
fi
step "starting the Steam client${BL_STEAM_UI:+ ($BL_STEAM_UI UI)}"
desktop_ui_pid=
@@ -823,21 +1125,33 @@ BUSCONF
/usr/local/bin/droiddeck-steam-desktop-ui &
desktop_ui_pid=$!
fi
"$steam_root/steamrtarm64/steam" "${_bl_ui[@]}" "${_bl_cdp[@]}" "${_bl_lang[@]}" -clientbeta "$steam_channel" \
steam_started=$SECONDS
"${steam_client[@]}" "${_bl_ui[@]}" "${_bl_cdp[@]}" "${_bl_lang[@]}" -clientbeta "$steam_channel" \
-no-cef-sandbox -cef-ozone-platform=x11 "${_bl_cef[@]}" "$@"
rc=$?
steam_ran=$((SECONDS - steam_started))
if [ -n "$desktop_ui_pid" ]; then
kill "$desktop_ui_pid" 2>/dev/null || true
wait "$desktop_ui_pid" 2>/dev/null || true
fi
echo "== steam exited rc=$rc"
if [ -n "${BL_ADDED_GAMES:-}" ] && [ -f "$BL_ADDED_GAMES" ]; then
droiddeck-steam-shortcuts "$steam_root" "$BL_ADDED_GAMES" || true
fi
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
if [ "$steam_x64" = 0 ]; then
droiddeck-steam-shortcuts "$steam_root" "$BL_ADDED_GAMES" || true
elif [ -n "${_bl_x64_tool:-}" ]; then
BL_COMPAT_TOOL=$_bl_x64_tool droiddeck-steam-shortcuts "$steam_root" "$BL_ADDED_GAMES" || true
fi
fi
# The x86-64 client rewrote config.vdf from memory on exit, over the live passes' mapping.
if [ "$steam_x64" = 1 ]; then
[ -z "${_bl_x64_tool:-}" ] ||
BL_COMPAT_TOOL=$_bl_x64_tool steam-compatibility "$steam_root" --x64 >/dev/null 2>&1 || true
droiddeck-steam-x64 --map-direct || true
fi
if [ -f "$HOME/.bl-stop-requested" ]; then
rm -f "$HOME/.bl-stop-requested" "$HOME/.bl-restart-once"
break
@@ -854,14 +1168,32 @@ BUSCONF
set --
continue
fi
if [ -s "$HOME/.bl-restart-game" ]; then
_bl_again=$(cat "$HOME/.bl-restart-game" 2>/dev/null)
rm -f "$HOME/.bl-restart-game"
case $_bl_again in
''|0*|*[!0-9]*) ;;
*)
echo "== steam: starting the client again to launch $_bl_again"
set --
steam_hold_launch "$_bl_again" &
continue
;;
esac
fi
if [ -f "$HOME/.bl-restart-lost" ]; then
rm -f "$HOME/.bl-restart-lost"
echo "== steam: starting the client again so it lists every shortcut"
set --
continue
fi
if [ -f "$HOME/.bl-restart-once" ]; then
echo "== steam: restarting once so the new compatibility layer is in the client's lists"
set --
continue
fi
[ "$rc" -eq 42 ] || break
steam_updates=$((steam_updates + 1))
if [ "$steam_updates" -ge 3 ]; then
if steam_update_stuck "$steam_ran"; then
echo "== steam: asked to restart for an update $steam_updates times and it is not installing; the session stops here rather than loop"
break
fi
@@ -894,6 +1226,9 @@ BUSCONF
[ -n "$_bl_jobs" ] && kill $_bl_jobs 2>/dev/null
reap_orphans
fi
if [ -n "${BL_STEAM_EXIT_FILE:-}" ]; then
printf '%s\n' "$rc" > "$BL_STEAM_EXIT_FILE"
fi
exit "$rc"
;;
*)
@@ -126,6 +126,29 @@ INSTALL_JS = r"""
return "installed";
})()
""".replace("__BINDING__", BINDING)
TOOLS_JS = r"""
(() => {
if (window.__droiddeckTools) return "present";
const installs = SteamClient.Installs, downloads = SteamClient.Downloads;
if (typeof installs?.OpenInstallWizard !== "function" || typeof installs?.RegisterForShowInstallWizard !== "function" ||
typeof installs?.ContinueInstall !== "function" || typeof downloads?.QueueAppUpdate !== "function")
throw new Error("the client's install calls are not ready");
const self = { asked: new Map() };
installs.RegisterForShowInstallWizard((state) => {
const app = Number(state?.currentAppID);
if (state?.eInstallState === 7 && Date.now() - (self.asked.get(app) || 0) < 120000) {
self.asked.delete(app);
installs.ContinueInstall();
}
});
self.install = (app) => { self.asked.set(app, Date.now()); installs.OpenInstallWizard([app], "0"); return true; };
self.update = (app) => { downloads.QueueAppUpdate(app, "0"); return true; };
window.__droiddeckTools = self;
return "installed";
})()
"""
TOOL_CHECK_SECONDS = 60
TOOL_RETRY_SECONDS = 300
SWITCH_BINDING = "droiddeckSwitchToDesktop"
SWITCH_JS = r"""
(() => {
@@ -153,6 +176,82 @@ SWITCH_JS = r"""
})()
""".replace("__BINDING__", SWITCH_BINDING)
SESSION_SELECT = "/usr/bin/steamos-session-select"
VR_BINDING = "droiddeckLaunchSteamVr"
VR_HELPER = "/usr/local/bin/droiddeck-steamvr"
VR_JS = r"""
(() => {
if (window.__droiddeckSteamVr) return "present";
const apps = SteamClient.Apps;
if (!apps || typeof apps.RunGame !== "function") throw new Error("Steam RunGame is not ready");
const run = apps.RunGame;
const self = { running: false, pending: new Map(), lastError: null };
const flush = () => {
if (!self.running) return;
const queued = Array.from(self.pending.values());
self.pending.clear();
for (const item of queued) {
clearTimeout(item.timer);
run.call(item.receiver, item.id, ...item.args);
}
};
if (typeof SteamClient.OpenVR?.RegisterForVRModeChange === "function") {
self.subscription = SteamClient.OpenVR.RegisterForVRModeChange(running => {
self.running = !!running;
flush();
});
}
const wrapped = function (id, ...args) {
const gameid = String(id);
if (typeof window.__BINDING__ !== "function") return run.call(this, id, ...args);
if (gameid === "250820") {
window.__BINDING__(gameid);
return;
}
const overview = window.appStore?.GetAppOverviewByGameID?.(gameid);
const vr = overview?.vr_only === true;
if (vr && self.subscription && /^[1-9][0-9]{0,19}$/.test(gameid)) {
if (self.pending.has(gameid)) return;
self.lastError = null;
const item = { receiver: this, id, args, timer: null };
item.timer = setTimeout(() => {
self.pending.delete(gameid);
self.lastError = "SteamVR did not become ready. Start SteamVR from DroidDeck and try the game again.";
console.error("DroidDeck: " + self.lastError);
}, 600000);
self.pending.set(gameid, item);
try { window.__BINDING__(gameid); }
catch (e) { clearTimeout(item.timer); self.pending.delete(gameid); throw e; }
flush();
return;
}
return run.call(this, id, ...args);
};
apps.RunGame = wrapped;
if (apps.RunGame !== wrapped) throw new Error("Steam RunGame could not be redirected");
if (typeof SteamClient.OpenVR?.StartVR === "function") {
const start = SteamClient.OpenVR.StartVR;
SteamClient.OpenVR.StartVR = function (...args) {
if (typeof window.__BINDING__ === "function") return window.__BINDING__("250820");
return start.apply(this, args);
};
}
window.__droiddeckSteamVr = self;
return "installed";
})()
""".replace("__BINDING__", VR_BINDING)
def launch_steamvr():
"""Keep downloads/startup off the Steam UI bridge's event loop."""
say("SteamVR library launch: using the DroidDeck ARM64 helper")
state = os.path.join(os.environ.get("XDG_RUNTIME_DIR", "/tmp"), "droiddeck-steamvr")
try:
os.makedirs(state, exist_ok=True)
with open(os.path.join(state, "library-launch.log"), "a") as log:
return subprocess.Popen([VR_HELPER, "launch"], stdin=subprocess.DEVNULL,
stdout=log, stderr=subprocess.STDOUT, start_new_session=True)
except OSError as e:
say("SteamVR library launch failed: %s" % e)
class Closed(Exception):
@@ -321,6 +420,9 @@ class Page:
raise RuntimeError((details.get("exception") or {}).get("description") or details.get("text") or "script failed")
return result.get("result", {}).get("value")
def tools(self, call):
return self.evaluate("%s;\nwindow.__droiddeckTools.%s" % (TOOLS_JS, call))
def compat(self, call):
return self.evaluate("%s;\nwindow.__droiddeckCompat.%s" % (INSTALL_JS, call))
@@ -405,6 +507,9 @@ class Helper:
self.known = set()
self.installed = None
self.fex_asked = set()
self.tools_asked = {}
self.tools_checked = None
self.vr_launch = None
def attach(self):
path = shared_context(self.port)
@@ -415,6 +520,8 @@ class Helper:
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.call("Runtime.addBinding", {"name": VR_BINDING})
page.evaluate(VR_JS)
if not self.steamos:
page.call("Runtime.addBinding", {"name": SWITCH_BINDING})
page.evaluate(SWITCH_JS)
@@ -442,29 +549,77 @@ class Helper:
installed = COMPAT["installed_apps"](self.steam_root)
self.installed = installed
picks = COMPAT["valve_picks"](self.steam_root)
apps = sorted(set(installed) | set(picks) | set(state.get("auto", {})), key=COMPAT["app_order"])
prior_auto = state.get("auto", {})
if not isinstance(prior_auto, dict):
prior_auto = {}
# "native" from earlier builds also lists dual-platform games nobody chose to run natively.
prior_native = state.get("native_choices", ())
native_choices = set(prior_native if isinstance(prior_native, (list, tuple, set)) else ())
apps = sorted(set(installed) | set(picks) | set(prior_auto) | native_choices, key=COMPAT["app_order"])
overrides = COMPAT["requested_games"](
COMPAT["game_requests"](), catalog, [t["name"] for t in live])
apps = sorted(set(apps) | set(overrides), 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)
native = COMPAT["native_targets"](self.steam_root, apps)
raw_mapping = COMPAT["read_config_mapping"](
os.path.join(self.steam_root, "config", "config.vdf"))
if raw_mapping is None:
for app in native_choices:
current[app] = ""
for app in set(native) - native_choices:
if not current.get(app):
current.pop(app, None)
else:
for app in set(native) | native_choices:
if app in raw_mapping:
# The client shows an explicit native choice as the tool it inherits, and writes config.vdf late.
if raw_mapping[app] == "" or current.get(app) not in self.known:
current[app] = raw_mapping[app]
elif app in prior_auto or app in native_choices:
current[app] = ""
elif not current.get(app):
current.pop(app, None)
changes, auto = COMPAT["plan_mapping"](
current, installed, [t["name"] for t in live], default,
COMPAT["followers"](state, current), native, picks, overrides)
COMPAT["followers"](state, current), native, picks, overrides,
prior_auto.keys(), native_choices)
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)
page.compat("set(%d, %s)" % (int(app), json.dumps(tool if tool is not None else "")))
say("%s -> %s" % ("default" if app == "0" else "app %s" % app,
tool if tool is not None else "Steam native default"))
state.update(
auto={app: tool for app, tool in auto.items() if tool is not COMPAT["NATIVE_CHOICE"]},
native_choices=sorted(app for app, tool in auto.items() if tool is COMPAT["NATIVE_CHOICE"]),
tools=catalog, live=True)
state.pop("native", None)
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 ensure_tools(self):
"""Proton, FEX and the runtimes FEX needs are fetched as soon as the client is up, never left pending."""
now = time.monotonic()
if self.tools_checked is not None and now - self.tools_checked < TOOL_CHECK_SECONDS:
return
self.tools_checked = now
if COMPAT["game_running"]():
return
for app, action in COMPAT["tool_downloads"](self.steam_root):
if now - self.tools_asked.get(app, -TOOL_RETRY_SECONDS) < TOOL_RETRY_SECONDS:
continue
self.tools_asked[app] = now
try:
self.page.tools("%s(%d)" % (action, int(app)))
say("asked the client to %s %s" % (action, app))
except Exception as e:
say("the client could not %s %s (%s)" % (action, app, e))
if action == "install":
for asked in COMPAT["request_fex"](self.steam_root, self.fex_asked):
say("asked the client to install %s through steam://install" % asked)
def request_waiting(self):
request = COMPAT["read_json"](COMPAT["state_path"]("request.json"))
@@ -476,6 +631,14 @@ class Helper:
events = self.page.drain()
if any(called(e, SWITCH_BINDING) for e in events):
switch_to_desktop()
vr_games = {e.get("params", {}).get("payload") for e in events if called(e, VR_BINDING) and
isinstance(e.get("params", {}).get("payload"), str)}
vr_games = {game for game in vr_games if isinstance(game, str) and game.isascii() and
game.isdecimal() and not game.startswith("0") and len(game) <= 20 and
int(game) <= 0xffffffffffffffff}
if vr_games and (self.vr_launch is None or self.vr_launch.poll() is not None):
say("preparing SteamVR for library app(s): " + ", ".join(sorted(vr_games)))
self.vr_launch = launch_steamvr()
return events
def serve(self, watcher):
@@ -483,6 +646,7 @@ class Helper:
f.write("%d\n" % os.getpid())
say("attached to the client on port %d" % self.port)
self.reconcile()
self.ensure_tools()
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]
@@ -497,6 +661,7 @@ class Helper:
watcher.changed()
self.drain()
self.reconcile()
self.ensure_tools()
def detach():
@@ -5,6 +5,7 @@ import json
import os
from pathlib import Path
import re
import shlex
import subprocess
import sys
import time
@@ -62,6 +63,12 @@ def source_stamp(game):
return None
def store_game(game):
"""Games a store client installed belong to that store: the Steam copy of the same title is
another license with its own files, and an import would let Steam update over the store's."""
return bool(game.get("store"))
def manifest_ids(steamapps, name):
matches = []
for manifest in Path(steamapps).glob("appmanifest_*.acf"):
@@ -113,7 +120,7 @@ def method(obj, slot, result, *args):
def probe(steam_root, ids):
library = C.CDLL(str(Path(steam_root) / "steamrtarm64/steamclient.so"))
library = C.CDLL(os.environ.get("BL_STEAMCLIENT") or str(Path(steam_root) / "steamrtarm64/steamclient.so"))
library.CreateInterface.argtypes = [C.c_char_p, C.c_void_p]
library.CreateInterface.restype = C.c_void_p
client = library.CreateInterface(b"SteamClient020", None)
@@ -167,7 +174,8 @@ def request_restart(steam_root):
"""The client reads manifests and shortcuts only at start, so an import needs one restart;
the session's loop runs the importer between the exit and the next start."""
Path(os.environ.get("HOME", "/root"), ".bl-restart-once").touch()
subprocess.run([str(Path(steam_root) / "steamrtarm64/steam"), "-shutdown"],
command = shlex.split(os.environ.get("BL_STEAM_SHUTDOWN", "")) or [str(Path(steam_root) / "steamrtarm64/steam"), "-shutdown"]
subprocess.run(command,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=30)
@@ -178,7 +186,7 @@ def unimported(steam_root, snapshot, candidates):
def watch(steam_root, listing):
games = read_json(listing, [])
games = [game for game in read_json(listing, []) if not store_game(game) and not game.get("native")]
if os.environ.get("BL_STEAM_OFFLINE") == "1" or not games:
return
candidates, sources = {}, {}
@@ -207,9 +215,10 @@ def watch(steam_root, listing):
elif candidates and (key != probed or now >= next_probe):
probed, next_probe = key, now + 300
try:
probe_env = dict(os.environ, HOME=os.environ["BL_STEAM_IPC_HOME"]) if os.environ.get("BL_STEAM_IPC_HOME") else None
result = subprocess.run([sys.executable, __file__, "probe", steam_root,
*map(str, sorted(set(candidates.values())))],
capture_output=True, text=True, timeout=15)
capture_output=True, text=True, timeout=15, env=probe_env)
if result.returncode != 0:
status = "ownership probe failed: " + (result.stderr.strip()[-300:] or str(result.returncode))
failures += 1
@@ -363,6 +372,22 @@ def seed_install(steam_root, game, appid):
return True
def release(steam_root, game):
"""Undoes an import made before store games were skipped. Only our symlink and manifest go;
the store's folder stays where it is."""
steamapps = Path(steam_root) / "steamapps"
sources = {game.get("folder", ""), legacy_path(game.get("folder", ""))}
for target in sorted((steamapps / "common").glob("DroidDeck-*")):
appid = target.name.removeprefix("DroidDeck-")
if not (appid.isdigit() and target.is_symlink() and os.readlink(target) in sources):
continue
for manifest in (steamapps / f"appmanifest_{appid}.acf", steamapps / PARKED / f"appmanifest_{appid}.acf"):
if manifest.is_file() and ours(manifest, appid):
manifest.unlink()
target.unlink()
print(f"droiddeck-steam-games: {game.get('name', appid)} came from {game['store']}; it is a shortcut again, not Steam app {appid}")
def route(steam_root, acct, games):
snapshot = read_json(Path(acct) / "config" / STATE, {})
if not isinstance(snapshot, dict):
@@ -379,6 +404,16 @@ def route(steam_root, acct, games):
except OSError as error:
print(f"droiddeck-steam-games: set-aside installs not restored ({error})")
for game in games:
if store_game(game):
try:
release(steam_root, game)
except OSError as error:
print(f"droiddeck-steam-games: store import not undone ({error})")
shortcuts.append(game)
continue
if game.get("native"):
shortcuts.append(game)
continue
folder = game.get("folder", "")
appid = candidates.get(folder, candidates.get(legacy_path(folder)))
stamp = source_stamp(game)
@@ -1,6 +1,6 @@
#!/bin/bash
set -eu
cdn=https://client-update.fastly.steamstatic.com
cdn_list="https://client-update.steamstatic.com https://client-update.akamai.steamstatic.com https://client-update.fastly.steamstatic.com"
steam_channel=steamdeck_publicbeta
manifest=steam_client_${steam_channel}_linuxarm64
steam_root=${XDG_DATA_HOME:-$HOME/.local/share}/Steam
@@ -33,12 +33,37 @@ if [ -n "$repair" ]; then
[ "$(sha1sum "$part" | cut -d' ' -f1)" = "$sum" ] || rm -f "$part"
done
fi
[ -x "$steam_root/steamrtarm64/steam" ] && [ -f "$stamp" ] && exit 0
sync=
if [ "${1:-}" = --sync ]; then
case "${2:-}" in publicbeta|steamdeck_publicbeta) sync=$2 ;; *) sync=$steam_channel ;; esac
manifest=steam_client_${sync}_linuxarm64
fi
[ -z "$sync" ] && [ -x "$steam_root/steamrtarm64/steam" ] && [ -f "$stamp" ] && exit 0
work=$(mktemp -d)
trap 'rm -rf "$work"' EXIT
curl -fsSL "$cdn/$manifest" -o "$work/manifest"
cdn=""
for candidate in $cdn_list; do
if curl -fsSL --connect-timeout 10 --max-time 30 --retry 2 --retry-connrefused --retry-delay 3 \
"$candidate/$manifest" -o "$work/manifest"; then
cdn=$candidate
break
fi
done
[ -n "$cdn" ] || { echo "droiddeck-steam-install: no Steam client CDN answered for $manifest" >&2; exit 1; }
cdn_order=("$cdn")
for candidate in $cdn_list; do
[ "$candidate" = "$cdn" ] || cdn_order+=("$candidate")
done
version=$(awk -F'"' '$2 == "version" { print $4; exit }' "$work/manifest")
if [ -n "$sync" ]; then
installed=$(awk -F'"' '$2 == "version" { print $4; exit }' "$steam_root/package/$manifest.manifest" 2>/dev/null || true)
if [ -x "$steam_root/steamrtarm64/steam" ] && [ "$installed" = "$version" ]; then
chmod -R a+x "$steam_root/steamrtarm64" "$steam_root/linuxarm64" 2>/dev/null || true
exit 0
fi
echo "== STEP $(date -u +%H:%M:%S) updating the arm64 Steam client to $version (was ${installed:-none}) for the x86-64 client"
fi
awk -F'"' '
/^\t"/ && NF >= 3 && $4 == "" { block = $2 }
$2 == "file" { file[block] = $4 }
@@ -52,8 +77,16 @@ mkdir -p "$steam_root/package"
while read -r block file sum; do
i=$((${i:-0} + 1))
echo "== STEP $(date -u +%H:%M:%S) downloading Steam: $block ($i/$total)"
curl -fsSL "$cdn/$file" -o "$work/$file"
echo "$sum $work/$file" | sha256sum -c --quiet
fetched=""
for host in "${cdn_order[@]}"; do
if curl -fsSL --connect-timeout 10 --speed-limit 1024 --speed-time 60 --max-time 1800 \
"$host/$file" -o "$work/$file" && echo "$sum $work/$file" | sha256sum -c --quiet; then
fetched=$host
break
fi
rm -f "$work/$file"
done
[ -n "$fetched" ] || { echo "droiddeck-steam-install: $file failed on every CDN" >&2; exit 1; }
unzip -qo "$work/$file" -d "$steam_root"
rm -f "$work/$file"
done < "$work/parts"
@@ -66,14 +99,20 @@ find "$steam_root" -depth -name '*\\*' | while read -r odd; do
mv -f "$odd" "$fixed"
fi
done
echo "$steam_channel" > "$steam_root/package/beta"
chmod -R a+x "$steam_root/steamrtarm64" "$steam_root/linuxarm64" 2>/dev/null || true
if [ -n "$sync" ]; then
cp -f "$work/manifest" "$steam_root/package/$manifest.manifest"
else
echo "$steam_channel" > "$steam_root/package/beta"
fi
ln -sfn "$steam_root/steamrtarm64" "$steam_root/steamrtarm32"
chmod +x "$steam_root/steamrtarm64/steam" 2>/dev/null || true
mkdir -p "$HOME/.steam"
ln -sfn "$steam_root" "$HOME/.steam/root"
ln -sfn "$steam_root" "$HOME/.steam/steam"
ln -sfn "$steam_root/steamrtarm64" "$HOME/.steam/bin64"
ln -sfn "$steam_root/linuxarm64" "$HOME/.steam/sdk64"
# sdk64 is where x86_64 Steamworks looks for steamclient.so; arm64 builds look in sdkarm64.
ln -sfn "$steam_root/linux64" "$HOME/.steam/sdk64"
ln -sfn "$steam_root/linuxarm64" "$HOME/.steam/sdkarm64"
ln -sfn "$steam_root/steamrtarm64" "$HOME/.steam/binarm64"
ln -sfn "$steam_root/linux32" "$HOME/.steam/sdk32"
@@ -12,15 +12,22 @@ case $target in
esac
if [ "$ui" = desktop ] && [ "${BL_DESKTOP:-}" = 1 ]; then
steam_root=${XDG_DATA_HOME:-${HOME:-/root}/.local/share}/Steam
export LD_LIBRARY_PATH=$steam_root/steamrtarm64:$steam_root/steamrtarm64/panorama${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}
if [ "${BL_STEAM_CLIENT_ARCH:-}" = x86_64 ]; then
client_home=${BL_X64_HOME:-${HOME:-/root}/.droiddeck-x64}
client=(/usr/local/bin/droiddeck-steam-x64 --exec)
else
steam_root=${XDG_DATA_HOME:-${HOME:-/root}/.local/share}/Steam
export LD_LIBRARY_PATH=$steam_root/steamrtarm64:$steam_root/steamrtarm64/panorama${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}
client_home=$HOME
client=("$steam_root/steamrtarm64/steam")
fi
mkdir -p "${XDG_CACHE_HOME:-$HOME/.cache}/droiddeck"
exec 9>"${XDG_CACHE_HOME:-$HOME/.cache}/droiddeck/steam-desktop.lock"
if ! flock -n 9; then
for ((attempt = 0; attempt < 180; attempt++)); do
pid=$(cat "$HOME/.steam/steam.pid" 2>/dev/null || true)
if [ -p "$HOME/.steam/steam.pipe" ] && [[ "$pid" =~ ^[0-9]+$ ]] && kill -0 "$pid" 2>/dev/null; then
exec "$steam_root/steamrtarm64/steam" -nobigpicture -no-cef-sandbox \
pid=$(cat "$client_home/.steam/steam.pid" 2>/dev/null || true)
if [ -p "$client_home/.steam/steam.pipe" ] && [[ "$pid" =~ ^[0-9]+$ ]] && kill -0 "$pid" 2>/dev/null; then
exec "${client[@]}" -nobigpicture -no-cef-sandbox \
-cef-ozone-platform=x11 -cef-disable-gpu "${url:-steam://open/library}"
fi
sleep 0.5
@@ -11,4 +11,5 @@ if [ "${BL_DESKTOP:-}" = 1 ]; then
done
exec /usr/local/bin/droiddeck-steam-launch "$ui" ${url:+"$url"}
fi
[ "${BL_STEAM_CLIENT_ARCH:-}" = x86_64 ] && exec /usr/local/bin/droiddeck-steam-x64 --exec "$@"
exec "${HOME:-/root}/.local/share/Steam/steamrtarm64/steam" "$@"
@@ -180,12 +180,14 @@ def merge(fresh, current, state, seen):
def reconcile(existing, wanted, seen, record):
games, away = record["games"], dict(record["away"])
kept, ours, placed = [], [], {}
claimed = {(unquoted(fresh["Exe"]), fresh["AppName"]) for fresh in wanted.values()}
for value in existing.values():
if not isinstance(value, dict):
continue
tags = value.get("tags")
if not isinstance(tags, dict) or TAG not in tags.values():
kept.append(value)
if (unquoted(value.get("Exe")), value.get("AppName")) not in claimed:
kept.append(value)
continue
appid = value.get("appid")
if not isinstance(appid, int) or appid in placed:
@@ -342,9 +344,21 @@ def main():
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())],
protect=compat.adopt_extras(os.path.join(steam_root, "compatibilitytools.d")))
print("droiddeck-steam-shortcuts: mapped them to %s" % compat.TOOL)
tools = os.path.join(steam_root, "compatibilitytools.d")
x64_tool = os.environ.get("BL_COMPAT_TOOL")
own = {}
if x64_tool:
protect = {compat.first_key(os.path.join(tools, e, "compatibilitytool.vdf"), ["compatibilitytools", "compat_tools"]) or e: e
for e in (os.listdir(tools) if os.path.isdir(tools) else [])}
# Its own state: the arm64 client's state.json lists which of that client's titles follow its default.
own = {"default": x64_tool,
"directory": os.path.join(os.path.dirname(os.path.abspath(steam_root)), "droiddeck-compat"),
"linux_tool": "droiddeck-direct"}
else:
protect = compat.adopt_extras(tools)
used = compat.register_default(cfg, apps=[str(int(g["appid"]) & 0xFFFFFFFF) for g in games if g.get("exe") and not g.get("native")] + [str(appid) for appid in set(routes.values())],
protect=protect, **own)
print("droiddeck-steam-shortcuts: mapped them to %s" % used)
except Exception as e:
print("droiddeck-steam-shortcuts: compat mapping skipped (%s)" % e)
return 0
File diff suppressed because it is too large. Load diff
+150 -6
View File
@@ -7,13 +7,39 @@ driver=$vrdir/droiddeck
layer=$vrdir/layer
logs=$HOME/.local/share/Steam/logs
state=${XDG_RUNTIME_DIR:-/tmp}/droiddeck-steamvr
umask 077
mkdir -p "$state"
chmod 700 "$state"
PKG_URL=https://steamdeck-packages.steamos.cloud/archlinux-deckard-hotfixes/release/0.3.x/deckard-steamvr-rel-r25358740%2B28b72a4f-1-aarch64.pkg.tar.zst
PKG_SHA256=90a600775eb3e8856dc475f83166a93a290a0b1f3b4e82a69c8e2a8f06b9ddc9
running() { pgrep -x vrserver >/dev/null 2>&1; }
installed() { [ -x "$steamvr/bin/linuxarm64/vrstartup" ]; }
quest_settings() {
backup=$HOME/.local/share/droiddeck/steamvr-quest-settings.json
[ "$1" != restore ] || [ -f "$backup" ] || return 0
python3 "${DROIDDECK_VR_SETTINGS_HELPER:-/usr/local/bin/droiddeck-steamvr-settings}" "$1" \
"$HOME/.local/share/Steam/config/steamvr.vrsettings" "$backup"
}
configure_graphics() {
case "$(cat /sys/class/kgsl/kgsl-3d0/gpu_model 2>/dev/null)" in
Adreno840*)
# The session's forced sysmem mode loses the Vulkan device in SteamVR.
export TU_DEBUG="$(
IFS=', '
set -f
separator=
for flag in ${TU_DEBUG:-}; do
case "$flag" in ''|sysmem) continue ;; esac
printf '%s%s' "$separator" "$flag"
separator=,
done
)"
;;
esac
}
stop() {
rm -f "$state/active"
@@ -21,10 +47,29 @@ stop() {
for p in $(pgrep -x "$n"); do kill "$p" 2>/dev/null; done
done
for p in $(pgrep -f "$steamvr/bin/linuxarm64/vrcompositor-launcher"); do kill "$p" 2>/dev/null; done
return 0
attempts=0
while pgrep -x 'vrserver|vrcompositor' >/dev/null 2>&1; do
attempts=$((attempts + 1))
if [ "$attempts" = 10 ]; then
for p in $(pgrep -x 'vrserver|vrcompositor'); do kill -KILL "$p" 2>/dev/null; done
fi
[ "$attempts" -lt 20 ] || { echo 'SteamVR did not stop; preferences remain backed up' >&2; return 1; }
sleep 0.1
done
quest_settings restore
}
case "${1:-status}" in
launch)
# Library/URL entry point: use the same installer and start path as the app.
exec 8>"$state/launch.lock"
flock -n 8 || exit 0
if ! installed; then
"$0" install || exit $?
while [ -f "$state/installing" ]; do sleep 1; done
fi
"$0" start
;;
status)
i=0; installed && i=1
r=0; running && r=1
@@ -34,8 +79,9 @@ status)
echo "installed=$i running=$r installing=$n driver=$d"
;;
install)
exec 7>"$state/install.lock"
flock -n 7 || { echo "already installing"; exit 0; }
installed && { echo "SteamVR is already in $steamvr"; exit 0; }
[ -f "$state/installing" ] && { echo "already installing"; exit 0; }
: > "$state/installing"
trap 'rm -f "$state/installing"' EXIT
cache=$HOME/.cache/droiddeck-vr
@@ -52,14 +98,66 @@ install)
echo "SteamVR installed in $steamvr"
;;
stop)
stop
stop || exit 1
;;
start)
exec 9>"$state/start.lock"
flock -n 9 || { echo "SteamVR start already in progress"; exit 0; }
installed || { echo "SteamVR is not installed (droiddeck-steamvr install)"; exit 1; }
[ -f "$driver/bin/linuxarm64/driver_droiddeck.so" ] || { echo "the Cardboard driver is missing from $driver"; exit 1; }
stop
if [ -f "$state/active" ] && { running || pgrep -x vrstartup >/dev/null 2>&1; }; then
echo "DroidDeck SteamVR is already running"
exit 0
fi
stop || exit 1
sleep 1
mkdir -p "$HOME/.config/openvr" "$HOME/.config/openxr/1" "$logs" "$HOME/.local/share/Steam/config"
if [ -S "/run/droiddeck/droiddeck-xr-frames" ] && [ -z "${DROIDDECK_VR_PRESENT:-}" ]; then
export DROIDDECK_VR_PRESENT=questwsi
fi
python3 - "$HOME/.local/share/Steam/config/steamvr.vrsettings" <<'PY'
import json
import os
from pathlib import Path
import sys
import tempfile
path = Path(sys.argv[1])
try:
settings = json.loads(path.read_text()) if path.exists() else {}
section = settings.setdefault("steamvr", {})
defaults = {} if os.environ.get("DROIDDECK_VR_PRESENT", "").startswith("quest") else {"supersampleManualOverride": True, "supersampleScale": 1.0}
changed = any(key not in section for key in defaults)
for key, value in defaults.items():
section.setdefault(key, value)
driver = settings.get("driver_droiddeck")
if isinstance(driver, dict) and driver.get("blocked_by_safe_mode") is True:
driver["blocked_by_safe_mode"] = False
changed = True
print("SteamVR had blocked the DroidDeck driver after a crash; unblocked it")
if changed:
with tempfile.NamedTemporaryFile(mode="w", dir=path.parent, delete=False) as output:
temporary = Path(output.name)
try:
json.dump(settings, output, indent=3)
output.write("\n")
except BaseException:
temporary.unlink(missing_ok=True)
raise
try:
os.replace(temporary, path)
finally:
temporary.unlink(missing_ok=True)
except (OSError, ValueError, AttributeError, TypeError) as error:
print("Could not set SteamVR resolution defaults: " + str(error), file=sys.stderr)
try:
(path.parent / "vrserver_crash_timestamp.txt").unlink()
print("Removed SteamVR's crash marker so it starts without safe mode")
except FileNotFoundError:
pass
except OSError as error:
print("Could not remove SteamVR's crash marker: " + str(error), file=sys.stderr)
PY
cat > "$HOME/.config/openvr/openvrpaths.vrpath" <<JSON
{
"config": ["$HOME/.local/share/Steam/config"],
@@ -71,10 +169,53 @@ start)
}
JSON
ln -sf "$steamvr/steamxr_linuxarm64.json" "$HOME/.config/openxr/1/active_runtime.json"
chaperone=$HOME/.local/share/Steam/config/chaperone_info.vrchap
[ -s "$chaperone" ] || cat > "$chaperone" <<'JSON'
{
"jsonid" : "chaperone_info",
"universes" : [
{
"collision_bounds" : [
[ [ -1.0, 0.0, -1.0 ], [ -1.0, 2.43, -1.0 ], [ -1.0, 2.43, 1.0 ], [ -1.0, 0.0, 1.0 ] ],
[ [ -1.0, 0.0, 1.0 ], [ -1.0, 2.43, 1.0 ], [ 1.0, 2.43, 1.0 ], [ 1.0, 0.0, 1.0 ] ],
[ [ 1.0, 0.0, 1.0 ], [ 1.0, 2.43, 1.0 ], [ 1.0, 2.43, -1.0 ], [ 1.0, 0.0, -1.0 ] ],
[ [ 1.0, 0.0, -1.0 ], [ 1.0, 2.43, -1.0 ], [ -1.0, 2.43, -1.0 ], [ -1.0, 0.0, -1.0 ] ]
],
"play_area" : [ 2.0, 2.0 ],
"seated" : { "translation" : [ 0.0, -1.6, 0.0 ], "yaw" : 0.0 },
"standing" : { "translation" : [ 0.0, 0.0, 0.0 ], "yaw" : 0.0 },
"universeID" : "2"
}
],
"version" : 5
}
JSON
export VK_LAYER_PATH="$layer${VK_LAYER_PATH:+:$VK_LAYER_PATH}"
export VK_INSTANCE_LAYERS="VK_LAYER_DROIDDECK_vr${VK_INSTANCE_LAYERS:+:$VK_INSTANCE_LAYERS}"
export VK_LOADER_LAYERS_DISABLE="${VK_LOADER_LAYERS_DISABLE:-~implicit~}"
configure_graphics
export LD_PRELOAD="$layer/libdroiddeck_vr_scheduling.so${LD_PRELOAD:+:$LD_PRELOAD}"
if [ "${DROIDDECK_VR_PRESENT:-}" = questwsi ]; then
quest_settings apply || exit 1
startup_handed_off=0
trap '[ "$startup_handed_off" = 1 ] || quest_settings restore' EXIT
# The pinned Frame package's CVP constructor exits on Quest's unsupported SoC.
cvp=$steamvr/drivers/cv/bin/linuxarm64/libArcturusPerception.so
if [ -f "$cvp" ]; then
disabled=$cvp.droiddeck-disabled
if [ -e "$disabled" ]; then disabled=$(mktemp "$disabled.XXXXXX") || exit 1; fi
mv "$cvp" "$disabled" || exit 1
echo "Disabled Frame-only CVP backend for Quest; SteamVR uses its normal compositor"
fi
fi
if [ "${DROIDDECK_VR_PRESENT:-}" = questframes ]; then
export DROIDDECK_VR_PRODUCER_LEASE=${DROIDDECK_VR_PRODUCER_LEASE:-1}
fi
if [ -z "${DROIDDECK_VR_DISPLAY_MODE:-}" ] && [ -x "$driver/bin/linuxarm64/xr-display-mode" ]; then
mode=$("$driver/bin/linuxarm64/xr-display-mode") || mode=
if [ -n "$mode" ]; then export DROIDDECK_VR_DISPLAY_MODE="$mode"; fi
fi
shims=$state/shims
mkdir -p "$shims"
@@ -86,11 +227,14 @@ JSON
: > "$state/active"
cd "$steamvr/bin/linuxarm64" || exit 1
setsid ./vrstartup > "$state/vrstartup.log" 2>&1 < /dev/null &
startup_log=$logs/droiddeck-vrstartup.log
ln -sf "$startup_log" "$state/vrstartup.log"
setsid ./vrstartup 8>&- 9>&- > "$startup_log" 2>&1 < /dev/null &
startup_handed_off=1
echo "SteamVR starting; logs in $logs and $state/vrstartup.log"
;;
*)
echo "usage: droiddeck-steamvr status|install|start|stop" >&2
echo "usage: droiddeck-steamvr status|install|start|stop|launch" >&2
exit 2
;;
esac
+21
View File
@@ -0,0 +1,21 @@
#!/bin/sh
set -eu
[ "$#" -gt 0 ] || { echo 'usage: droiddeck-steamvr-game COMMAND [ARG...]' >&2; exit 2; }
pgrep -x vrserver >/dev/null 2>&1 || {
echo 'Start SteamVR before launching a game with droiddeck-steamvr-game.' >&2
exit 1
}
vrdir=${DROIDDECK_VR_DIR:-/usr/local/lib/droiddeck-vr}
export VK_LAYER_PATH="$vrdir/layer${VK_LAYER_PATH:+:$VK_LAYER_PATH}"
export VK_INSTANCE_LAYERS="VK_LAYER_DROIDDECK_vr${VK_INSTANCE_LAYERS:+:$VK_INSTANCE_LAYERS}"
export VK_LOADER_LAYERS_DISABLE="${VK_LOADER_LAYERS_DISABLE:-~implicit~}"
# Quest's guest GPU images use Vulkan sharing rather than DMA-BUF modifiers.
if [ -S "/run/droiddeck/droiddeck-xr-frames" ]; then
export gamescope_vr_use_modifiers=${gamescope_vr_use_modifiers:-false}
fi
export gamescope_vr_nudge_to_visible=${gamescope_vr_nudge_to_visible:-true}
exec gamescope --backend openvr \
--vr-overlay-key "gamescope.droiddeck.game.$$" \
--vr-overlay-default-name 'DroidDeck game' \
--vr-overlay-show-immediately --vr-overlay-physical-width 2.4 -- "$@"
@@ -0,0 +1,80 @@
#!/usr/bin/python3
"""Preserve SteamVR preferences across Quest's required compositor overrides."""
import json
import os
from pathlib import Path
import sys
OVERRIDES = {'enableLinuxVulkanAsync': True, 'motionSmoothing': False}
def read(path):
try:
with path.open() as source:
settings = json.load(source)
except FileNotFoundError:
return {}
if not isinstance(settings, dict) or not isinstance(settings.get('steamvr', {}), dict):
raise ValueError('Invalid SteamVR settings object')
return settings
def write(path, value):
path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
temporary = path.with_name(path.name + '.tmp')
with os.fdopen(os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | os.O_NOFOLLOW, 0o600), 'w') as destination:
json.dump(value, destination, indent=3)
destination.write('\n')
os.replace(temporary, path)
def saved_preferences(path):
try:
backup = read(path)
if not isinstance(backup.get('section'), bool) or not isinstance(backup.get('values'), dict):
raise ValueError('invalid backup object')
for key in OVERRIDES:
entry = backup['values'].get(key)
if not isinstance(entry, list) or len(entry) != 2 or not isinstance(entry[0], bool):
raise ValueError('invalid saved preference: ' + key)
return backup
except ValueError as error:
raise ValueError(f'Invalid preference backup {path}; repair the saved section/values and retry restore. '
'The backup and current preferences have been preserved.') from error
def update(operation, settings_path, backup_path):
settings = read(settings_path)
if operation == 'apply':
if backup_path.exists():
saved_preferences(backup_path)
else:
section = settings.get('steamvr', {})
write(backup_path, {'section': 'steamvr' in settings,
'values': {key: [key in section, section.get(key)] for key in OVERRIDES}})
settings.setdefault('steamvr', {}).update(OVERRIDES)
write(settings_path, settings)
elif operation == 'restore':
if not backup_path.exists():
return
backup = saved_preferences(backup_path)
section = settings.setdefault('steamvr', {})
for key in OVERRIDES:
present, value = backup['values'][key]
if present:
section[key] = value
else:
section.pop(key, None)
if not section and not backup['section']:
settings.pop('steamvr')
write(settings_path, settings)
backup_path.unlink()
else:
raise ValueError('Expected apply or restore')
if __name__ == '__main__':
try:
update(sys.argv[1], Path(sys.argv[2]), Path(sys.argv[3]))
except (OSError, ValueError, KeyError, IndexError, TypeError) as error:
sys.exit('Could not update SteamVR settings: ' + str(error))
@@ -6,8 +6,10 @@ whoever started it: the Games tab, a pinned shortcut, or the Steam client's own
looks for the store launcher DroidDeck wrote (.droiddeck-launch.bat) among the arguments; beside it
.droiddeck-store.json says which store and game it is.
For an Epic game the game needs a fresh exchange code to sign in, which only the app can mint. The
request goes through files under $BL_LAUNCH_DIR/stores (the session root, the same path on both
For an Epic game, once the Epic Games Launcher is installed (droiddeck-epic), the game is started
through it: the hidden launcher signs the game in and hands its arguments back in
.droiddeck-epic-args. Without the launcher, or when it cannot, the game needs a fresh exchange code
to sign in, which only the app can mint. The request goes through files under $BL_LAUNCH_DIR/stores (the session root, the same path on both
sides):
req/<id>.json {"op": "epic-code", "store": "epic", "id": "<app name>"} (tmp + rename)
@@ -38,6 +40,11 @@ from pathlib import Path
LAUNCHER = ".droiddeck-launch.bat"
SIDECAR = ".droiddeck-store.json"
EPIC_CODE = ".droiddeck-epic-code"
EPIC_ARGS = ".droiddeck-epic-args"
EPIC_CLIENT = "/usr/local/bin/droiddeck-epic"
EPIC_CLIENT_CURRENT = ".local/share/droiddeck-epic/current.json"
EPIC_HANDLED = "DROIDDECK_EPIC_HANDLED"
CLIENT_TIMEOUT = 150.0
TIMEOUT = 5.0
STALE_SECONDS = 300
SERVER_WAIT = 8.0
@@ -98,6 +105,30 @@ def drop_stale(folder, now=None):
return False
def client_wanted():
home = os.environ.get("HOME") or "/root"
return os.access(EPIC_CLIENT, os.X_OK) and os.path.isfile(os.path.join(home, EPIC_CLIENT_CURRENT))
def through_client(folder, sidecar, timeout=CLIENT_TIMEOUT):
extra = sidecar.get("extra") if isinstance(sidecar.get("extra"), dict) else {}
namespace, item = str(extra.get("namespace") or ""), str(extra.get("catalogItemId") or "")
if not namespace or not item:
return "no-catalog-ids"
command = [EPIC_CLIENT, "launch", "--app", str(sidecar.get("id")), "--namespace", namespace, "--item", item,
"--folder", str(folder), "--owner", str(os.getppid()), "--timeout", str(int(timeout))]
try:
run = subprocess.run(command, stdout=subprocess.PIPE, stdin=subprocess.DEVNULL, timeout=timeout + 30)
answer = json.loads(run.stdout.decode("utf-8", "replace").strip().splitlines()[-1])
except (OSError, ValueError, IndexError, subprocess.TimeoutExpired) as error:
return "error-" + type(error).__name__
if not isinstance(answer, dict):
return "no-answer"
if answer.get("ok") and (folder / EPIC_ARGS).is_file():
return "ok"
return str(answer.get("reason") or "failed")
def ask(channel, request, timeout=TIMEOUT):
"""Writes [request] under channel/req and waits for channel/resp; the answer, or None on timeout."""
req_dir, resp_dir = channel / "req", channel / "resp"
@@ -247,10 +278,16 @@ def cloud_on(sidecar):
return str(sidecar.get("store")) in CLOUD_STORES and sidecar.get("cloud", True) is not False
def exited(argv):
def exited(argv, code=0):
"""After the game: ask the app to upload what changed, without waiting for it."""
found = find_store_game(argv)
launch_dir = os.environ.get("BL_LAUNCH_DIR", "")
if found is not None and str(found[1].get("store")) == "epic" and os.environ.get(EPIC_HANDLED) != "1" \
and os.access(EPIC_CLIENT, os.X_OK):
try:
subprocess.run([EPIC_CLIENT, "exited", "--code", str(code)], stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, timeout=10)
except (OSError, subprocess.TimeoutExpired):
pass
if found is None or not launch_dir or not cloud_on(found[1]):
return 0
store, game = str(found[1].get("store")), str(found[1].get("id"))
@@ -329,7 +366,14 @@ def prepare_gog(sidecar, compat_data, launch_dir):
def main(argv):
if argv and argv[0] == "--exited":
return exited(argv[1:])
rest, code = argv[1:], 0
if rest[:1] == ["--code"] and len(rest) > 1:
try:
code = int(rest[1])
except ValueError:
pass
rest = rest[2:]
return exited(rest, code)
found = find_store_game(argv)
if found is None:
return 0
@@ -341,9 +385,27 @@ def main(argv):
if store == "gog":
prepare_gog(sidecar, compat_data, launch_dir)
if store == "epic":
drop_stale(folder)
handled = os.environ.get(EPIC_HANDLED) == "1" and (folder / EPIC_ARGS).is_file()
if not handled:
drop_stale(folder)
try:
(folder / EPIC_ARGS).unlink()
except OSError:
pass
choice = options(sidecar)
if not (choice["eos"] and not choice["offline"]):
client = None
if handled:
client = "ok"
elif choice["eos"] and not choice["offline"] and client_wanted():
client = through_client(folder, sidecar)
log("epic launch id=%s client=%s" % (game, client))
if client == "ok":
try:
(folder / EPIC_CODE).unlink()
except OSError:
pass
log("epic launch id=%s through=client" % game)
elif not (choice["eos"] and not choice["offline"]):
try:
(folder / EPIC_CODE).unlink()
except OSError:
@@ -0,0 +1,46 @@
#!/bin/bash
# Runs natively: droiddeck-steam-x64's x86 wrappers start it through an arm64 binary, which FEX hands to the CPU.
tool=$1; shift
x64_home=$HOME
# The game overlay tags the game's windows with the Steam app ID; without it gamescope never shows them.
overlay=0
case ${LD_PRELOAD:-} in *gameoverlayrenderer.so*) overlay=1 ;; esac
for v in $(compgen -e); do
case $v in FEX_*) unset "$v" ;; esac
done
unset LD_LIBRARY_PATH LD_PRELOAD STEAM_RUNTIME_STEAMRT STEAM_STEAMRT_RECURSION_GUARD \
LIBGL_ALWAYS_SOFTWARE LIBGL_DRI3_DISABLE GALLIUM_DRIVER BL_WEBHELPER_HIDE_TRACER PROOT_FP_OFF
game_display=${DISPLAY:-}
if [ -f "$x64_home/arm-session.env" ]; then
. "$x64_home/arm-session.env"
else
export HOME=/root
fi
[ -z "$game_display" ] || export DISPLAY=$game_display
# Proton takes its Steam client parts from the client's install folder; the x86-64 client's are x86.
export BL_X64_STEAM_ROOT=${STEAM_COMPAT_CLIENT_INSTALL_PATH:-}
export STEAM_COMPAT_CLIENT_INSTALL_PATH=$HOME/.local/share/Steam
arm_overlay=$STEAM_COMPAT_CLIENT_INSTALL_PATH/steamrtarm64/gameoverlayrenderer.so
if [ "$overlay" = 1 ] && [ -f "$arm_overlay" ]; then
export LD_PRELOAD=$arm_overlay${LD_PRELOAD:+:$LD_PRELOAD}
fi
dir=$HOME/.local/share/Steam/compatibilitytools.d/$tool
manifest=$dir/toolmanifest.vdf
[ -f "$manifest" ] || { echo "droiddeck-x64-arm-proton: no tool $dir" >&2; exit 127; }
if ! grep -q droiddeck-proton-wrap "$manifest" 2>/dev/null; then
python3 - "${dir%/*}" <<'PY' >&2 || true
import importlib.machinery, importlib.util, sys
path = "/usr/local/bin/steam-compatibility"
spec = importlib.util.spec_from_file_location("compat", path, loader=importlib.machinery.SourceFileLoader("compat", path))
compat = importlib.util.module_from_spec(spec)
spec.loader.exec_module(compat)
compat.adopt_extras(sys.argv[1])
PY
fi
cmd=$(sed -n 's/^[[:space:]]*"commandline"[[:space:]]*"\([^"]*\)".*/\1/p' "$manifest" | head -n 1)
entry=${cmd%% *}
exec "$dir/${entry#/}" "$@"
@@ -0,0 +1,20 @@
#!/bin/bash
# The arm64 client's web helper for the x86-64 client, run natively: FEX hands this arm64 program to the CPU.
x64_home=$HOME
arm=/root/.local/share/Steam/steamrtarm64
for v in $(compgen -e); do
case $v in FEX_*) unset "$v" ;; esac
done
unset LD_PRELOAD LIBGL_ALWAYS_SOFTWARE LIBGL_DRI3_DISABLE BL_WEBHELPER_HIDE_TRACER BL_X64_ARM_WEBHELPER
if [ -f "$x64_home/arm-session.env" ]; then
eval "$(grep -E '^declare -x (VK_ICD_FILENAMES|VK_DRIVER_FILES|GALLIUM_DRIVER|MESA_LOADER_DRIVER_OVERRIDE|LIBGL_KOPPER_DRI2|TU_DEBUG|ZINK_DEBUG|ZINK_DESCRIPTORS|MESA_NO_ERROR|MESA_DISK_CACHE_DATABASE)=' "$x64_home/arm-session.env")"
fi
export LD_LIBRARY_PATH=$arm:$arm/panorama LIBGL_KOPPER_DISABLE=true
args=()
for a in "$@"; do
case $a in --disable-gpu|--disable-gpu-compositing) ;; *) args+=("$a") ;; esac
done
cd "$arm" || exit 1
exec "$arm/steamwebhelper" "${args[@]}" --ignore-gpu-blocklist
@@ -0,0 +1,10 @@
#!/bin/bash
# Steam's compositor draws each browser window from its X pixmap: frames must reach X, not gamescope's WSI layer.
# gamescope sets vk_xwayland_wait_ready=false for its children; kopper swapchains flashed black even with the wait.
unset BL_X64_ARM_WEBHELPER
# The shim already added the GPU flags (preload/webhelper.c) to these arguments.
export BL_WEBHELPER_ARGS=stock DISABLE_GAMESCOPE_WSI=1 vk_xwayland_wait_ready=true LIBGL_KOPPER_DISABLE=true
if [ -x ./steamwebhelper ]; then
exec ./steamwebhelper "$@"
fi
exec "$HOME/.local/share/Steam/steamrt64/steamwebhelper" "$@"
@@ -21,7 +21,11 @@ FEX_LAUNCHER = "droiddeck-fex-tool"
FEX_FILES = ("toolmanifest.vdf", "compatibilitytool.vdf", FEX_LAUNCHER)
FEX_APPID = "3127680"
SNIPER_APPID = "1628350"
FEX_DEPENDENCIES = (FEX_APPID, SNIPER_APPID)
SLR4_APPID = "4183110"
FEX_DEPENDENCIES = (FEX_APPID, SNIPER_APPID, SLR4_APPID)
REQUIRED_TOOLS = (PROTON_ARM64_APPID,) + FEX_DEPENDENCIES
FULLY_INSTALLED = 4
UPDATE_REQUIRED = 2
REQUEST_HANDOFF_SECONDS = 30
PLAYABLE_TYPES = frozenset(("game", "demo", "application", "beta"))
COMPAT_DIR = os.path.join(os.environ.get("HOME", "/root"), ".local", "share", "droiddeck-compat")
@@ -73,7 +77,7 @@ bl_run() {
if [ -n "${BL_STORE_EXIT:-}" ]; then
"$@"
rc=$?
/usr/local/bin/droiddeck-store-launch --exited "${BL_STORE_ARGS[@]}" || true
/usr/local/bin/droiddeck-store-launch --exited --code "$rc" "${BL_STORE_ARGS[@]}" || true
exit $rc
fi
exec "$@"
@@ -210,8 +214,40 @@ bl_idtech3() {
}
"""
# Source games report VAC-secure or insecure only in their console, written to console.log only with -condebug.
# The app keeps the switch and the records in /root: the x86-64 client runs games with its own HOME.
BL_VACDIAG_SETUP = """
bl_vacdiag() {
[ -f /root/.droiddeck-vac-diagnostics ] || return 0
[ "${verb:-}" = waitforexitandrun ] || return 0
local exe= a dir added=no app=${SteamAppId:-${STEAM_COMPAT_APP_ID:-0}}
for a in "$@"; do case $a in *.exe|*.EXE) exe=$a ;; esac; done
[ -n "$exe" ] || return 0
dir=$(dirname "$exe")
# Source: <mod>/gameinfo.txt beside the exe. Source 2: game/bin/win64/<exe> with game/<mod>/gameinfo.gi.
if ls "$dir"/*/gameinfo.txt >/dev/null 2>&1 || ls "$dir"/../../*/gameinfo.gi >/dev/null 2>&1; then
case " $* " in
*" -condebug "*) echo "droiddeck-proton: vac-diag: app $app already has -condebug" >&2 ;;
*) BL_EXTRA_ARGS+=(-condebug); added=yes
echo "droiddeck-proton: vac-diag: app $app is a Source title; launched with -condebug" >&2 ;;
esac
else
added=not-source
echo "droiddeck-proton: vac-diag: app $app is not a Source title; it keeps no console log to read" >&2
fi
case " $* " in
*" -insecure "*) echo "droiddeck-proton: vac-diag: app $app has -insecure in its launch options - it can never be VAC-secure this way" >&2 ;;
esac
printf '%s\tapp %s\tcondebug %s\t%s\n' "$(date +%s)" "$app" "$added" "${exe##*/}" >> /root/.droiddeck-vac-launches
}
"""
BL_DIRECTAUDIO_SETUP = """
bl_directaudio() {
case "${verb:-}" in
run|waitforexitandrun|runinprefix) ;;
*) return 0 ;;
esac
base=$1
[ -n "${BL_DIRECTAUDIO:-}" ] || return 0
[ -d "$BL_DIRECTAUDIO" ] || return 0
@@ -305,6 +341,7 @@ if [ -n "$depot" ]; then
bl_directaudio "$depot"
bl_game_cpus
bl_idtech3 "$@"
bl_vacdiag "$@"
bl_libpath
BL_STORE_PROTON="$depot/proton"; export BL_STORE_PROTON
bl_store_launch "$@"
@@ -320,7 +357,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" + BL_DIRECTAUDIO_SETUP + BL_GAME_CPUS_SETUP + BL_IDTECH3_SETUP
+ BL_COMPONENTS_SETUP + BL_LIBPATH_SETUP + BL_STORE_SETUP, 1)
+ BL_VACDIAG_SETUP + BL_COMPONENTS_SETUP + BL_LIBPATH_SETUP + BL_STORE_SETUP, 1)
LAUNCHER_SH = launcher_sh()
@@ -359,6 +396,7 @@ bl_components "$here"
bl_directaudio "$here"
bl_game_cpus
bl_idtech3 "$@"
bl_vacdiag "$@"
bl_libpath
BL_STORE_PROTON="$here/%s"; export BL_STORE_PROTON
bl_store_launch "$@"
@@ -586,7 +624,7 @@ def adopt_extras(tools):
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 + BL_STORE_SETUP, 1)
+ BL_VACDIAG_SETUP + BL_COMPONENTS_SETUP + BL_LIBPATH_SETUP + BL_STORE_SETUP, 1)
write_changed(wrapper, body, 0o755)
write_changed(manifest, EXTRA_MANIFEST_VDF)
write_changed(compat_vdf, EXTRA_COMPAT_TOOL_VDF % (name, display_name(entry)))
@@ -660,6 +698,26 @@ def launch_programs(config):
return found
def launch_options(config):
"""An app's launch options as Steam lists them: executable, arguments, working folder, type and oslist."""
launch = config.get("launch") if isinstance(config, dict) else None
found = []
for key, option in launch.items() if isinstance(launch, dict) else ():
if not isinstance(option, dict) or not option.get("executable"):
continue
settings = option.get("config") if isinstance(option.get("config"), dict) else {}
found.append({
"key": str(key),
"executable": str(option["executable"]),
"arguments": str(option.get("arguments", "")),
"workingdir": str(option.get("workingdir", "")),
"type": str(option.get("type", "")).lower(),
"oslist": str(settings.get("oslist", "")).lower(),
"betakey": str(settings.get("betakey", "")),
})
return found
def appinfo_entries(path):
import struct
try:
@@ -751,6 +809,7 @@ def appinfo_entries(path):
"type": str(common.get("type", "")).lower(),
"recommended": str(recommended),
"launch": launch_programs(info.get("config")),
"launch_options": launch_options(info.get("config")),
}
if app == STEAM_PLAY_MANIFESTS:
extended = info.get("extended", {})
@@ -787,17 +846,46 @@ def native_targets(steam_root, apps):
return {}
targets = {}
for app, (oslist, osarch, kind) in appinfo_platforms(os.path.join(steam_root, "appcache", "appinfo.vdf"), wanted).items():
if kind not in PLAYABLE_TYPES or "windows" in oslist or "linux" not in oslist:
if kind not in PLAYABLE_TYPES or "linux" not in oslist:
continue
if "arm64" in osarch or "aarch64" in osarch:
targets[app] = None
continue
if "windows" in oslist:
targets[app] = NATIVE_CHOICE
continue
targets[app] = FEX_TOOL
return targets
def linux_runtime_tool(name):
low = name.lower()
return low == "fex" or low.startswith("steamlinuxruntime")
def app_manifest(steam_root, app):
for library in libraries(steam_root):
try:
with open(os.path.join(library, "steamapps", "appmanifest_%s.acf" % app), encoding="utf-8", errors="replace") as f:
return tokenize(f.read())
except OSError:
continue
return None
def manifest_flags(tokens):
for i in range(len(tokens) - 1):
if tokens[i].lower() == '"stateflags"':
value = tokens[i + 1].strip('"')
return int(value) if value.isdigit() else 0
return 0
def tool_downloads(steam_root):
"""(app, "install" or "update") for each tool the client has yet to install or bring up to date."""
wanted = []
for app in REQUIRED_TOOLS:
tokens = app_manifest(steam_root, app)
if tokens is None:
wanted.append((app, "install"))
elif not manifest_flags(tokens) & FULLY_INSTALLED or manifest_flags(tokens) & UPDATE_REQUIRED:
wanted.append((app, "update"))
return wanted
def fex_missing(steam_root):
@@ -877,18 +965,22 @@ def app_order(app):
DEFERRED_GAME_TOOL = object()
NATIVE_CHOICE = object()
def plan_mapping(current, installed, runnable, default, auto, native=None, picks=(), overrides=None):
def plan_mapping(current, installed, runnable, default, auto, native=None, picks=(), overrides=None, managed=None,
native_choices=()):
runnable = {n.lower() for n in runnable}
installed = set(installed)
picks = set(picks)
native = native or {}
overrides = overrides or {}
managed = set(auto) if managed is None else set(managed)
native_choices = set(native_choices)
changes, kept = {}, {}
if current.get("0", "") != default:
changes["0"] = default
for app in sorted((set(current) | installed | picks | set(auto) | set(overrides)) - {"0"}, key=app_order):
for app in sorted((set(current) | installed | picks | set(auto) | set(overrides) | native_choices) - {"0"}, key=app_order):
name = current.get(app, "")
if app in overrides:
target = overrides[app]
@@ -902,9 +994,26 @@ def plan_mapping(current, installed, runnable, default, auto, native=None, picks
continue
mine = auto.get(app)
target = native.get(app, default)
stale = unrunnable(name, runnable) or (app in native and linux_runtime_tool(name))
if not name and app in native_choices:
target = NATIVE_CHOICE
stale = unrunnable(name, runnable)
if name and not stale and (mine is None or name != mine):
continue
if target is NATIVE_CHOICE:
if not name and (app in native_choices or app in current or app in managed):
kept[app] = NATIVE_CHOICE
continue
target = default
if target is None:
if stale:
target = default
if name != target:
changes[app] = target
continue
else:
if name and app in managed and name == mine:
changes[app] = None
continue
if not name and app not in installed and app not in picks:
continue
if name != target:
@@ -1043,8 +1152,37 @@ def read_mapping(tokens, mapping):
return current
def read_config_mapping(config_path):
"""Read per-app choices without creating or rewriting the client's mapping block."""
try:
with open(config_path, encoding="utf-8", errors="replace") as f:
tokens = tokenize(f.read())
except OSError:
return None
depth = 0
for token in tokens:
if token == "{":
depth += 1
elif token == "}":
depth -= 1
if depth < 0:
return None
if depth != 0:
return None
steam = find_block(tokens, ["InstallConfigStore", "Software", "Valve", "Steam"])
if steam is None:
return None
mapping = find_block(tokens[steam + 1:], ["CompatToolMapping"])
return read_mapping(tokens, mapping + steam + 1) if mapping is not None else {}
def set_mapping(tokens, mapping, app, tool):
block = find_block(tokens[mapping + 1:], [app])
if tool is None:
if block is not None:
block += mapping + 1
del tokens[block - 1:block_end(tokens, block) + 1]
return
if block is None:
tokens[mapping + 1:mapping + 1] = [
'"%s"' % app, "{", '"name"', '"%s"' % tool, '"config"', '""', '"priority"', '"75"' if app == "0" else '"250"', "}"]
@@ -1074,6 +1212,21 @@ def steam_running():
return False
def game_running():
try:
pids = [p for p in os.listdir("/proc") if p.isdigit()]
except OSError:
return False
for pid in pids:
try:
with open("/proc/%s/cmdline" % pid, "rb") as f:
if b"\0SteamLaunch\0AppId=" in f.read():
return True
except OSError:
continue
return False
def live_helper_running(directory=None):
try:
with open(state_path("live.pid", directory)) as f:
@@ -1084,7 +1237,8 @@ def live_helper_running(directory=None):
return False
def register_default(config_path, apps=(), protect=(), default=None, catalog=None, directory=None, settle=False, picks=()):
def register_default(config_path, apps=(), protect=(), default=None, catalog=None, directory=None, settle=False, picks=(),
linux_tool=FEX_TOOL):
"""Writes the mapping: the "0" default and every title that follows it (see plan_mapping).
With settle, the default itself is decided first (see choose_default): before the client
starts, config.vdf holds what the client last kept, menu changes included."""
@@ -1108,14 +1262,22 @@ def register_default(config_path, apps=(), protect=(), default=None, catalog=Non
default = state.get("default") if state.get("default") in names else TOOL
steam_root = os.path.dirname(os.path.dirname(os.path.abspath(config_path)))
overrides = requested_games(game_requests(directory), catalog)
managed = state.get("auto", {}).keys() if isinstance(state.get("auto"), dict) else ()
native_choices = state.get("native_choices", ())
native = native_targets(steam_root, set(apps) | set(picks) | set(managed) | set(native_choices))
if linux_tool != FEX_TOOL:
native = {app: linux_tool if tool == FEX_TOOL else tool for app, tool in native.items()}
changes, auto = plan_mapping(
current, apps, names, default, followers(state, current), native_targets(steam_root, apps), picks, overrides)
current, apps, names, default, followers(state, current), native, picks,
overrides, managed, native_choices)
for app, tool in changes.items():
set_mapping(tokens, mapping, app, tool)
text = serialize(tokens)
if text != serialize(tokenize(original)):
write_changed(config_path, text)
state["auto"] = auto
state["auto"] = {app: tool for app, tool in auto.items() if tool is not NATIVE_CHOICE}
state["native_choices"] = sorted(app for app, tool in auto.items() if tool is NATIVE_CHOICE)
state.pop("native", None)
state["tools"] = catalog
state.setdefault("default", default)
write_json(state_path("state.json", directory), state)
@@ -1171,8 +1333,71 @@ def remove_tool(tool_dir):
shutil.rmtree(tool_dir)
def local_tools(steam_root):
"""The names of the compatibility tools installed in steam_root/compatibilitytools.d."""
names = set()
tools = os.path.join(steam_root, "compatibilitytools.d")
try:
entries = os.listdir(tools)
except OSError:
return names
for entry in entries:
try:
with open(os.path.join(tools, entry, "compatibilitytool.vdf"), encoding="utf-8", errors="replace") as f:
m = re.search(r'"compat_tools"\s*\{\s*"([^"]+)"', f.read())
except OSError:
continue
if m:
names.add(m.group(1).lower())
return names
def x64_repoint(steam_root, tool, live=False):
"""The x86-64 client (droiddeck-steam-x64): its tools are arm64 wrappers that script makes and
its Linux titles run as Linux builds (FEX), so only the entries the client aimed at a Proton it
cannot start are repointed, to `tool`. Tools in its own compatibilitytools.d are kept: the
wrappers include proton-cachyos-*-a64, which starts with "proton" like Valve's own.
Returns the app ids repointed."""
config = os.path.join(steam_root, "config", "config.vdf")
if not tool or not os.path.isfile(config):
return []
with open(config, encoding="utf-8", errors="replace") as f:
original = f.read()
tokens = tokenize(original)
mapping = mapping_block(tokens)
if mapping is None:
return []
keep = local_tools(steam_root)
moved = []
current = read_mapping(tokens, mapping)
if "0" not in current:
set_mapping(tokens, mapping, "0", tool)
for app, name in current.items():
named = name.lower()
# A tool named arm64 is never this client's (its wrappers are -a64), so this legacy name is always repointed.
legacy = named == "droiddeck-proton-arm64"
if (named.startswith("proton") or legacy) and named != tool.lower() \
and (legacy or named not in keep):
set_mapping(tokens, mapping, app, tool)
if app != "0":
moved.append(app)
text = serialize(tokens)
if text != serialize(tokenize(original)):
write_changed(config, text)
print("steam-compatibility: x86-64 client's Proton entries point at %s" % tool)
# Steam reads a mapping changed while it runs only at its next start; the session restarts it (.bl-compat-pending).
if moved and live:
with open(os.path.join(os.path.expanduser("~"), ".bl-compat-pending"), "a") as f:
f.write("".join("%s\n" % a for a in moved))
print("steam-compatibility: repointed while the client runs: %s" % " ".join(moved))
return moved
def main():
steam_root = sys.argv[1]
if "--x64" in sys.argv[2:]:
x64_repoint(steam_root, os.environ.get("BL_COMPAT_TOOL"), "--live" in sys.argv[2:])
return
tools = os.path.join(steam_root, "compatibilitytools.d")
os.makedirs(tools, exist_ok=True)
legacy = os.path.join(tools, LEGACY_TOOL)
+4 -2
View File
@@ -91,7 +91,8 @@ static int enabled(void) {
if (cached < 0) {
const char *off = getenv("BL_NO_DIR_CACHE");
cached = strcmp(program_invocation_short_name, "steam") == 0 &&
strstr(program_invocation_name, "steamrtarm64") != NULL && !(off && strcmp(off, "1") == 0);
(strstr(program_invocation_name, "steamrtarm64") != NULL ||
strstr(program_invocation_name, "steamrt64") != NULL) && !(off && strcmp(off, "1") == 0);
if (cached) pthread_atfork(NULL, NULL, after_fork);
}
return cached && !forked;
@@ -256,9 +257,10 @@ static void install(struct listing *l) {
int slot = find(l->dev, l->ino);
if (slot >= 0) {
struct listing *old = table[slot];
int old_wd = old->wd;
table[slot] = l;
detach(old);
if (old->wd != l->wd) release(old->wd);
if (old_wd != l->wd) release(old_wd);
return;
}
int victim = -1;
+20
View File
@@ -5,10 +5,12 @@
#define _GNU_SOURCE
#include <dlfcn.h>
#include <limits.h>
#include <linux/input.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/sysmacros.h>
#include <sys/types.h>
@@ -176,6 +178,24 @@ static int caller_is_winebus(void *caller) {
return strstr(info.dli_fname, "winebus.so") != NULL;
}
/* Wine's HID haptics give every XInput rumble a 1000 ms cutoff and xinput only writes on a change,
* but XInput motors hold their speed until the next XInputSetState; evdev's length 0 holds until
* stopped. Only this library, preloaded first, sees winebus as the caller. The length is put back
* because winebus compares its copy with the next state to decide whether to upload again. */
__attribute__((visibility("hidden"))) int bl_winebus_rumble_ioctl(int (*real)(int, unsigned long, void *), int fd,
unsigned long request, void *arg, void *caller,
int *rc) {
struct ff_effect *effect = arg;
__u16 length;
if (request != EVIOCSFF || effect == NULL || effect->type != FF_RUMBLE || !caller_is_winebus(caller)) return 0;
length = effect->replay.length;
effect->replay.length = 0;
*rc = real(fd, request, arg);
effect->replay.length = length;
return 1;
}
char *realpath(const char *path, char *resolved) {
static char *(*real_realpath)(const char *, char *);
void *caller = __builtin_return_address(0);
+42 -3
View File
@@ -6,6 +6,7 @@
#include <linux/netlink.h>
#include <netinet/in.h>
#include <stdio.h>
#include <limits.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
@@ -262,6 +263,7 @@ __attribute__((visibility("hidden"))) void bl_binfmt_before(const char *path, ch
__attribute__((visibility("hidden"))) int bl_binfmt_retry(const char *path, char *const argv[], char *const envp[], int error);
__attribute__((visibility("hidden"))) void bl_binfmt_before_search(const char *file, char *const argv[], char *const envp[]);
__attribute__((visibility("hidden"))) int bl_binfmt_after_search(const char *file, char *const argv[], char *const envp[], int error);
__attribute__((visibility("hidden"))) char *const *bl_webhelper_argv(const char *path, char *const argv[]);
__attribute__((visibility("hidden"))) int bl_binfmt_spawn(pid_t *pid, const char *path, const posix_spawn_file_actions_t *fa,
const posix_spawnattr_t *attr, char *const argv[], char *const envp[],
spawn_fn real);
@@ -308,10 +310,39 @@ static int maybe_answer_lsof(const char *path, char *const argv[]) {
_exit(0);
}
int execve(const char *path, char *const argv[], char *const envp[]) {
static char **web_helper_redirect(const char *path, char *const argv[], const char **launcher) {
const char *want = getenv("BL_X64_ARM_WEBHELPER");
if (!want || !*want || !path) return NULL;
const char *base = strrchr(path, '/');
if (strcmp(base ? base + 1 : path, "steamwebhelper") != 0) return NULL;
if (!strstr(path, "/steamrt64/")) {
char cwd[PATH_MAX];
size_t n;
if (path[0] == '/' || !getcwd(cwd, sizeof(cwd))) return NULL;
n = strlen(cwd);
if (n < 10 || strcmp(cwd + n - 10, "/steamrt64") != 0) return NULL;
}
int argc = 0;
while (argv && argv[argc]) argc++;
char **out = calloc((size_t)argc + 2, sizeof(char *));
if (!out) return NULL;
out[0] = (char *)want;
for (int i = 1; i < argc; i++) out[i] = argv[i];
*launcher = want;
return out;
}
int execve(const char *path, char *const argv_in[], char *const envp[]) {
char *const *argv = bl_webhelper_argv(path, argv_in);
static int (*real)(const char *, char *const[], char *const[]);
if (!real) real = (int (*)(const char *, char *const[], char *const[]))dlsym(RTLD_NEXT, "execve");
maybe_answer_lsof(path, argv);
const char *launcher = NULL;
char **redirected = web_helper_redirect(path, argv, &launcher);
if (redirected) {
real(launcher, redirected, envp);
free(redirected);
}
bl_binfmt_before(path, argv, envp);
real(path, argv, envp);
return bl_binfmt_retry(path, argv, envp, errno);
@@ -332,7 +363,8 @@ static int answer_lsof_via_spawn(const char *path, char *const argv[], pid_t *pi
return 0;
}
int execvp(const char *file, char *const argv[]) {
int execvp(const char *file, char *const argv_in[]) {
char *const *argv = bl_webhelper_argv(file, argv_in);
static int (*real)(const char *, char *const[]);
if (!real) real = (int (*)(const char *, char *const[]))dlsym(RTLD_NEXT, "execvp");
maybe_answer_lsof(file, argv);
@@ -341,10 +373,17 @@ int execvp(const char *file, char *const argv[]) {
return bl_binfmt_after_search(file, argv, environ, errno);
}
int execv(const char *path, char *const argv[]) {
int execv(const char *path, char *const argv_in[]) {
char *const *argv = bl_webhelper_argv(path, argv_in);
static int (*real)(const char *, char *const[]);
if (!real) real = (int (*)(const char *, char *const[]))dlsym(RTLD_NEXT, "execv");
maybe_answer_lsof(path, argv);
const char *launcher = NULL;
char **redirected = web_helper_redirect(path, argv, &launcher);
if (redirected) {
real(launcher, redirected);
free(redirected);
}
bl_binfmt_before(path, argv, environ);
real(path, argv);
return bl_binfmt_retry(path, argv, environ, errno);
+8 -5
View File
@@ -406,6 +406,8 @@ int bl_kgsl_poll(int (*real)(int, unsigned long, void *), int fd, unsigned long
void *arg, int *rc) __attribute__((visibility("hidden")));
int bl_ntsync_ioctl(int fd, unsigned long request, void *arg, int *rc) __attribute__((visibility("hidden")));
int bl_drm_gem_close(int fd, unsigned long request, void *arg, int *rc) __attribute__((visibility("hidden")));
int bl_winebus_rumble_ioctl(int (*real)(int, unsigned long, void *), int fd, unsigned long request,
void *arg, void *caller, int *rc) __attribute__((visibility("hidden")));
int ioctl(int fd, unsigned long request, ...) {
typedef int (*ioctl_fn)(int, unsigned long, void *);
@@ -419,6 +421,7 @@ int ioctl(int fd, unsigned long request, ...) {
if (bl_ntsync_ioctl(fd, request, arg, &rc)) return rc;
if (bl_drm_gem_close(fd, request, arg, &rc)) return rc;
if (real == NULL) real = (ioctl_fn) dlsym(RTLD_NEXT, "ioctl");
if (bl_winebus_rumble_ioctl(real, fd, request, arg, __builtin_return_address(0), &rc)) return rc;
if (!bl_kgsl_poll(real, fd, request, arg, &rc)) rc = quest_kgsl_ioctl(real, fd, request, arg);
bl_kgsl_chip_id_fixup(request, arg, rc);
if (arg == NULL || !is_link_query(request)) return rc;
@@ -535,11 +538,11 @@ static FILE *synthesize(const char *table) {
return out;
}
int bl_status_without_tracer(const char *path, int flags) __attribute__((visibility("hidden")));
int bl_status_without_tracer(const char *path, int flags, const void *caller) __attribute__((visibility("hidden")));
static FILE *open_stream(fopen_fn real, const char *path, const char *mode) {
static FILE *open_stream(fopen_fn real, const char *path, const char *mode, const void *caller) {
int status = mode && mode[0] == 'r' && !strchr(mode, '+')
? bl_status_without_tracer(path, O_RDONLY | O_CLOEXEC) : -1;
? bl_status_without_tracer(path, O_RDONLY | O_CLOEXEC, caller) : -1;
if (status >= 0) {
FILE *copy = fdopen(status, "r");
if (copy == NULL) close(status);
@@ -557,11 +560,11 @@ static FILE *open_stream(fopen_fn real, const char *path, const char *mode) {
FILE *fopen(const char *path, const char *mode) {
static fopen_fn real;
if (real == NULL) real = (fopen_fn) dlsym(RTLD_NEXT, "fopen");
return open_stream(real, path, mode);
return open_stream(real, path, mode, __builtin_return_address(0));
}
FILE *fopen64(const char *path, const char *mode) {
static fopen_fn real;
if (real == NULL) real = (fopen_fn) dlsym(RTLD_NEXT, "fopen64");
return open_stream(real, path, mode);
return open_stream(real, path, mode, __builtin_return_address(0));
}
+3 -3
View File
@@ -11,7 +11,7 @@
#include <string.h>
#include <sys/types.h>
int bl_status_without_tracer(const char *path, int flags) __attribute__((visibility("hidden")));
int bl_status_without_tracer(const char *path, int flags, const void *caller) __attribute__((visibility("hidden")));
int bl_writable_retry(int dirfd, const char *path, int flags) __attribute__((visibility("hidden")));
int bl_ntsync_open(const char *path, int flags) __attribute__((visibility("hidden")));
int bl_dircache_create(int dirfd, const char *path, int flags, mode_t mode,
@@ -51,7 +51,7 @@ int open(const char *path, int flags, ...) {
errno = EACCES;
return -1;
}
if ((fd = bl_status_without_tracer(path, flags)) >= 0) return fd;
if ((fd = bl_status_without_tracer(path, flags, __builtin_return_address(0))) >= 0) return fd;
if ((fd = bl_ntsync_open(path, flags)) != -2) return fd;
if (real_open == NULL) real_open = dlsym(RTLD_NEXT, "open");
if (real_open == NULL) {
@@ -76,7 +76,7 @@ int openat(int dirfd, const char *path, int flags, ...) {
errno = EACCES;
return -1;
}
if ((fd = bl_status_without_tracer(path, flags)) >= 0) return fd;
if ((fd = bl_status_without_tracer(path, flags, __builtin_return_address(0))) >= 0) return fd;
if ((fd = bl_ntsync_open(path, flags)) != -2) return fd;
if (real_openat == NULL) real_openat = dlsym(RTLD_NEXT, "openat");
if (real_openat == NULL) {
+2 -1
View File
@@ -42,7 +42,8 @@ static int enabled(void) {
if (cached >= 0) return cached;
off = getenv("BL_NO_PATH_CACHE");
cached = strcmp(program_invocation_short_name, "steam") == 0 &&
strstr(program_invocation_name, "steamrtarm64") != NULL &&
(strstr(program_invocation_name, "steamrtarm64") != NULL ||
strstr(program_invocation_name, "steamrt64") != NULL) &&
!(off != NULL && off[0] == '1');
return cached;
}
+1 -1
View File
@@ -7,7 +7,7 @@
#include <unistd.h>
static int in_steam_dirs(const char *path) {
return path != NULL && (strstr(path, "/Steam/steamrtarm64/") != NULL
return path != NULL && (strstr(path, "/Steam/steamrtarm64/") != NULL || strstr(path, "/Steam/steamrt64/") != NULL
|| strstr(path, "/Steam/ubuntu12_64/") != NULL || strstr(path, "/Steam/linuxarm64/") != NULL);
}
+55
View File
@@ -0,0 +1,55 @@
/* In Deck mode (-steamos3) the x86-64 client's SteamOS audio manager passes libpulse the NULL operation of a
* failed request, and libpulse aborts on it ("Assertion 'o' failed ... pa_operation_get_state()"). */
#if defined(__x86_64__) || defined(__i386__)
#define _GNU_SOURCE
#include <dlfcn.h>
#include <stddef.h>
typedef struct pa_operation pa_operation;
#define PA_OPERATION_CANCELLED 2
/* A libpulse loaded with RTLD_LOCAL (Wine's winepulse.so) is not in RTLD_NEXT's scope. */
static void *libpulse(const char *name) {
void *fn = dlsym(RTLD_NEXT, name);
if (!fn) {
void *handle = dlopen("libpulse.so.0", RTLD_LAZY | RTLD_NOLOAD);
if (handle) {
fn = dlsym(handle, name);
dlclose(handle);
}
}
return fn;
}
int pa_operation_get_state(pa_operation *o) {
static int (*next)(pa_operation *);
if (!o)
return PA_OPERATION_CANCELLED;
if (!next)
next = (int (*)(pa_operation *))libpulse("pa_operation_get_state");
return next ? next(o) : PA_OPERATION_CANCELLED;
}
void pa_operation_unref(pa_operation *o) {
static void (*next)(pa_operation *);
if (!o)
return;
if (!next)
next = (void (*)(pa_operation *))libpulse("pa_operation_unref");
if (next)
next(o);
}
void pa_operation_cancel(pa_operation *o) {
static void (*next)(pa_operation *);
if (!o)
return;
if (!next)
next = (void (*)(pa_operation *))libpulse("pa_operation_cancel");
if (next)
next(o);
}
#else
typedef int pulseguard_arm_build_has_nothing_to_do;
#endif
+178
View File
@@ -2,13 +2,18 @@
#include <dlfcn.h>
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <linux/futex.h>
#include <linux/magic.h>
#include <pthread.h>
#include <stdarg.h>
#include <stddef.h>
#include <stdint.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/uio.h>
#include <sys/vfs.h>
#include <unistd.h>
#ifndef SYS_openat2
@@ -17,6 +22,17 @@
#define BL_RESOLVE_BENEATH 0x08
#define BL_RESOLVE_IN_ROOT 0x10
// The kernel's MAXSYMLINKS.
#define BL_MAX_SYMLINKS 40
#define BL_PROC_ROOT_INO 1
#ifdef SYS_newfstatat
#define BL_SYS_FSTATAT SYS_newfstatat
typedef struct stat bl_stat;
#else
#define BL_SYS_FSTATAT SYS_fstatat64
typedef struct stat64 bl_stat;
#endif
struct bl_open_how {
uint64_t flags;
@@ -25,8 +41,22 @@ struct bl_open_how {
};
static long (*real_syscall)(long, ...);
static void *(*real_dlopen)(const char *, int);
static int openat2_missing;
void *dlopen(const char *filename, int flags) {
if (!real_dlopen) {
real_dlopen = (void *(*)(const char *, int))dlsym(RTLD_NEXT, "dlopen");
}
const char *basename = filename ? strrchr(filename, '/') : NULL;
basename = basename ? basename + 1 : filename;
// Steam's deep binding bypasses the robust-list shim under PRoot.
if (basename && strcmp(basename, "vrclient.so") == 0) {
flags &= ~RTLD_DEEPBIND;
}
return real_dlopen(filename, flags);
}
int bl_fsync_syscall(long number, const long *args, long *ret) __attribute__((visibility("hidden")));
static struct robust_list_head *thread_robust_head(void) {
@@ -61,6 +91,151 @@ static struct robust_list_head *thread_robust_head(void) {
return head;
}
// Magic links are procfs links below a process's directory; procfs's root holds only plain ones (self, thread-self, mounts).
static int is_magic_link(int dirfd, char *link, size_t parent_len) {
int fd = (int)real_syscall(SYS_openat, (long)dirfd, (long)link, (long)(O_PATH | O_NOFOLLOW | O_CLOEXEC), 0L);
if (fd < 0) {
return 0;
}
struct statfs fs;
int procfs = real_syscall(SYS_fstatfs, (long)fd, (long)&fs) == 0 && fs.f_type == PROC_SUPER_MAGIC;
real_syscall(SYS_close, (long)fd);
if (!procfs) {
return 0;
}
char saved = link[parent_len];
link[parent_len] = 0;
bl_stat parent;
long result = real_syscall(BL_SYS_FSTATAT, (long)dirfd, (long)(parent_len ? link : "."), (long)&parent, 0L);
link[parent_len] = saved;
return result != 0 || parent.st_ino != BL_PROC_ROOT_INO;
}
// RESOLVE_IN_ROOT walked one component at a time: absolute symlinks restart at dirfd and ".." stops there.
static long openat_in_root(int dirfd, const char *path, int flags, long mode) {
char resolved[PATH_MAX];
char pending[PATH_MAX];
size_t resolved_len = 0;
int symlinks = 0;
int have_root = 0;
int root_on_procfs = 0;
dev_t root_dev = 0;
// O_NOFOLLOW and O_CREAT | O_EXCL leave a final symlink alone, unless a trailing slash follows it.
int nofollow = (flags & O_NOFOLLOW) || (flags & (O_CREAT | O_EXCL)) == (O_CREAT | O_EXCL);
const char *rest = path;
for (;;) {
while (*rest == '/') {
rest++;
}
if (!*rest) {
break;
}
const char *name = rest;
const char *end = name;
while (*end && *end != '/') {
end++;
}
size_t len = (size_t)(end - name);
rest = end;
while (*rest == '/') {
rest++;
}
int last = !*rest;
int trailing_slash = last && rest != end;
if (len == 1 && name[0] == '.') {
continue;
}
if (len == 2 && name[0] == '.' && name[1] == '.') {
while (resolved_len > 0 && resolved[resolved_len - 1] != '/') {
resolved_len--;
}
if (resolved_len > 0) {
resolved_len--;
}
continue;
}
size_t separator = resolved_len > 0;
size_t candidate_len = resolved_len + separator + len;
if (candidate_len + 1 >= PATH_MAX) {
errno = ENAMETOOLONG;
return -1;
}
if (separator) {
resolved[resolved_len] = '/';
}
memcpy(resolved + resolved_len + separator, name, len);
resolved[candidate_len] = 0;
bl_stat st;
int follow = !last || trailing_slash || !nofollow;
long stat_result = follow ? real_syscall(BL_SYS_FSTATAT, (long)dirfd, (long)resolved, (long)&st, (long)AT_SYMLINK_NOFOLLOW) : -1;
if (stat_result == 0 && S_ISLNK(st.st_mode)) {
if (++symlinks > BL_MAX_SYMLINKS) {
errno = ELOOP;
return -1;
}
if (!have_root) {
bl_stat root;
struct statfs root_fs;
if (real_syscall(BL_SYS_FSTATAT, (long)dirfd, (long)".", (long)&root, 0L) != 0) {
return -1;
}
root_dev = root.st_dev;
root_on_procfs = real_syscall(SYS_fstatfs, (long)dirfd, (long)&root_fs) == 0 && root_fs.f_type == PROC_SUPER_MAGIC;
have_root = 1;
}
if ((st.st_dev != root_dev || root_on_procfs) && is_magic_link(dirfd, resolved, resolved_len)) {
// RESOLVE_IN_ROOT refuses magic links.
errno = EXDEV;
return -1;
}
size_t rest_len = strlen(end);
if (rest_len + 1 >= PATH_MAX) {
errno = ENAMETOOLONG;
return -1;
}
char *tail = pending + PATH_MAX - rest_len - 1;
memmove(tail, end, rest_len + 1);
long target_len = real_syscall(SYS_readlinkat, (long)dirfd, (long)resolved, (long)pending, (long)(PATH_MAX - rest_len));
if (target_len <= 0) {
if (target_len == 0) {
errno = ENOENT;
}
return -1;
}
if ((size_t)target_len + rest_len >= PATH_MAX) {
errno = ENAMETOOLONG;
return -1;
}
memmove(pending + target_len, tail, rest_len + 1);
if (pending[0] == '/') {
resolved_len = 0;
}
rest = pending;
continue;
}
if (last) {
resolved_len = candidate_len;
if (trailing_slash) {
resolved[resolved_len++] = '/';
}
break;
}
if (stat_result != 0) {
return -1;
}
if (!S_ISDIR(st.st_mode)) {
errno = ENOTDIR;
return -1;
}
resolved_len = candidate_len;
}
if (resolved_len == 0) {
resolved[resolved_len++] = '.';
}
resolved[resolved_len] = 0;
return real_syscall(SYS_openat, (long)dirfd, (long)resolved, (long)flags, mode);
}
static long openat2_via_openat(const long *args) {
const char *path = (const char *)args[1];
const struct bl_open_how *how = (const struct bl_open_how *)args[2];
@@ -68,6 +243,9 @@ static long openat2_via_openat(const long *args) {
errno = EINVAL;
return -1;
}
if ((how->resolve & BL_RESOLVE_IN_ROOT) && (int)args[0] != AT_FDCWD) {
return openat_in_root((int)args[0], path, (int)how->flags, (long)how->mode);
}
if (how->resolve & BL_RESOLVE_IN_ROOT) {
while (*path == '/') {
path++;
+2 -1
View File
@@ -145,7 +145,8 @@ static int steam_client(void) {
static int cached = -1;
if (cached < 0)
cached = strcmp(program_invocation_short_name, "steam") == 0 &&
strstr(program_invocation_name, "steamrtarm64") != NULL;
(strstr(program_invocation_name, "steamrtarm64") != NULL ||
strstr(program_invocation_name, "steamrt64") != NULL);
return cached;
}
+14 -5
View File
@@ -4,8 +4,10 @@
#define _GNU_SOURCE
#include <ctype.h>
#include <dlfcn.h>
#include <errno.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/syscall.h>
@@ -31,9 +33,16 @@ static int is_status_path(const char *path) {
return strcmp(rest, "/status") == 0;
}
static int is_web_helper(void) {
return strcmp(program_invocation_short_name, "steamwebhelper") == 0 ||
strcmp(program_invocation_short_name, "vrwebhelper") == 0;
static int is_web_helper(const void *caller) {
if (strcmp(program_invocation_short_name, "steamwebhelper") != 0 &&
strcmp(program_invocation_short_name, "vrwebhelper") != 0)
return 0;
const char *hide = getenv("BL_WEBHELPER_HIDE_TRACER");
Dl_info info;
if (hide && hide[0] == '1' && caller && dladdr(caller, &info) && info.dli_fname
&& strstr(info.dli_fname, "libtier0_s.so"))
return 0;
return 1;
}
static int write_all(int fd, const char *data, size_t len) {
@@ -47,13 +56,13 @@ static int write_all(int fd, const char *data, size_t len) {
return 0;
}
__attribute__((visibility("hidden"))) int bl_status_without_tracer(const char *path, int flags) {
__attribute__((visibility("hidden"))) int bl_status_without_tracer(const char *path, int flags, const void *caller) {
char text[STATUS_MAX];
size_t len = 0;
int saved = errno;
int out = -1;
if ((flags & O_ACCMODE) != O_RDONLY || !is_status_path(path) || is_web_helper()) return -1;
if ((flags & O_ACCMODE) != O_RDONLY || !is_status_path(path) || is_web_helper(caller)) return -1;
int in = (int)syscall(SYS_openat, AT_FDCWD, path, O_RDONLY | O_CLOEXEC);
if (in < 0) goto done;
for (;;) {
+73
View File
@@ -0,0 +1,73 @@
#define _GNU_SOURCE
#include <stdlib.h>
#include <string.h>
#ifndef WEBHELPER_DEFAULT
#define WEBHELPER_DEFAULT "--no-zygote --in-process-gpu -AudioServiceOutOfProcess"
#endif
static int is_webhelper_browser(const char *path, char *const argv[]) {
if (!path || !argv) return 0;
const char *base = strrchr(path, '/');
base = base ? base + 1 : path;
if (strcmp(base, "steamwebhelper")) return 0;
for (int i = 1; argv[i]; i++)
if (!strncmp(argv[i], "--type=", 7)) return 0;
return 1;
}
static char *join_features(const char *have, const char *add) {
size_t a = have ? strlen(have) : 0, b = strlen(add);
char *out = malloc(a + b + 2);
if (!out) return NULL;
out[0] = 0;
if (a) strcat(strcat(out, have), ",");
return strcat(out, add);
}
__attribute__((visibility("hidden"))) char *const *bl_webhelper_argv(const char *path, char *const argv[]) {
if (!is_webhelper_browser(path, argv)) return argv;
const char *spec = getenv("BL_WEBHELPER_ARGS");
if (!spec || !*spec) spec = WEBHELPER_DEFAULT;
if (!strcmp(spec, "stock")) return argv;
int argc = 0;
while (argv[argc]) argc++;
char *tokens = strdup(spec);
if (!tokens) return argv;
int extra = 0;
for (char *c = tokens; *c; c++)
if (*c == ' ') extra++;
char **out = calloc(argc + extra + 4, sizeof *out);
if (!out) return argv;
const char *enable = NULL, *disable = NULL;
int n = 0;
for (int i = 0; i < argc; i++) {
if (i && !strncmp(argv[i], "--enable-features=", 18)) enable = argv[i] + 18;
else if (i && !strncmp(argv[i], "--disable-features=", 19)) disable = argv[i] + 19;
else out[n++] = argv[i];
}
char *add_enable = NULL, *add_disable = NULL, *save = NULL;
for (char *t = strtok_r(tokens, " ", &save); t; t = strtok_r(NULL, " ", &save)) {
if (t[0] == '+' && t[1]) {
char *joined = join_features(add_enable, t + 1);
free(add_enable);
add_enable = joined;
} else if (t[0] == '-' && t[1] && t[1] != '-') {
char *joined = join_features(add_disable, t + 1);
free(add_disable);
add_disable = joined;
} else if (!strncmp(t, "--", 2)) {
out[n++] = t;
}
}
char *merged;
if (add_enable && (merged = join_features(enable, add_enable))) enable = merged;
if (add_disable && (merged = join_features(disable, add_disable))) disable = merged;
char *flag;
if (enable && (flag = malloc(strlen(enable) + 19))) out[n++] = strcat(strcpy(flag, "--enable-features="), enable);
if (disable && (flag = malloc(strlen(disable) + 20))) out[n++] = strcat(strcpy(flag, "--disable-features="), disable);
out[n] = NULL;
return out;
}