mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-19 04:46:08 +00:00
feat: Epic Games Launcher for Linux (#928)
* feat: Epic Games Launcher for Linux Install Epic's official Linux launcher (EGLv2) from Epic's CDN with Valve's Steam Runtime 4 and run it under FEX, signed in with the linked Epic account. Epic games launch through a hidden launcher instance so they get the launcher's own arguments, with the exchange-code launch as the fallback, and DroidDeck installs show up in the launcher as installed. In the launcher, touch scrolls like a phone app and the gamepad drives the UI: D-pad and left stick move the selection, A opens, B goes back, the right stick and triggers scroll proportionally, X opens the options menu, Y the keyboard and LB/RB switch tabs. * feat: Epic Games Launcher for Linux Install Epic's official Linux launcher (EGLv2) from Epic's CDN with Valve's Steam Runtime 4 and run it under FEX, signed in with the linked Epic account. Epic games launch through a hidden launcher instance so they get the launcher's own arguments, with the exchange-code launch as the fallback, and DroidDeck installs show up in the launcher as installed. In the launcher, touch scrolls like a phone app and the gamepad drives the UI: D-pad and left stick move the selection, A opens, B goes back, the right stick and triggers scroll proportionally, X opens the options menu, Y the keyboard and LB/RB switch tabs. * Route Epic games through Steam, import launcher installs, offer the second library - Every Epic launch goes Steam -> Epic Games Launcher -> game; Play inside the open launcher hands the game to Steam - Games installed from inside the launcher get a Games-tab entry and launch through Steam; the launcher installs to the last Stores target - Stores install picker offers the Steam second library, with side-by-side choices - uruntime xattr-only failures no longer fail the launcher unpack (app-extract) * Hand launcher Play and Steam links to Steam, wait for FEX on first run Play on a game the launcher just installed is matched to its install record and handed to Steam. Steam games listed in the launcher open steam://rungameid links, which now start the game in a Steam session. Opening the launcher before Steam has downloaded FEX asks Steam for it and starts Steam instead of failing with no-fex. * Address review: FEX check, play-in-Steam action, touch route thread, scroll scale fexReady needs a FEX binary in Steam's FEX tool, not just its folder. The play-in-Steam action stays until the link is handled, so Run Steam at startup can't start a session first. The pad touch route reads the mouse mode without side effects off the main thread and posts the pad update there. Vertical scroll uses the output height. A status-2 unpack counts only when AppRun is there. The xdg-open command is tested end to end for Steam links. * Open the launcher through Steam, recover dropped shortcuts, sign out of both The Epic Games Launcher now runs as its own Steam shortcut, so opening it starts Steam, which opens the launcher, and Play inside it goes to the running Steam. Steam dropped a running shortcut from its library when the game exited after a sleep/wake replay or a server re-logon, and launching it then waited forever at ShowInterstitials. login1 only replays sleep/wake when Steam is asleep. The session restarts Steam when a requested shortcut is missing, and when a game exits with its shortcut gone and nothing else runs. Resuming after a long pause no longer reports failure while traced processes are still waking, so "Steam is paused" goes away on the first tap. Signing out of the launcher signs DroidDeck's Epic store out, and signing out in DroidDeck restarts the launcher signed out and clears the Epic web cookies. * Address review: one session-switch poll, Epic setup can't block a session A new switch confirmation replaces the pending poll instead of adding a second one that could start the session again. Epic library sync and install-folder setup at session start are each guarded, so a bad preference no longer stops the guest from launching. * Uninstall the Epic Games Launcher from the Games tab An Uninstall button next to Launch asks first, closes a running session, and removes the launcher and its runtime. The launcher's sign-in and install records stay, so its games keep their Games-tab entries and a reinstall comes back signed in. Its Steam shortcut goes away on the next Steam start. * Address review: uninstall only after the session has ended The launcher's files are removed only once the session is not running and its phase has ended; a shutdown still in progress after the wait reports failure instead. The confirmation reads the session state from the front-end state. * Find FEX that Steam installed on the second library Steam's tools on a second library live in DroidDeck's private copy, which the session binds over the library. The launcher's FEX check only looked on the shared storage, so with FEX there it always asked Steam for FEX and only Steam opened. It now checks the private copy too. * Start games without Steam, per-game Settings menu with Wine sync "Start without Steam" now really leaves the Steam client out: the game runs in its own Proton/FEX through droiddeck-proton-run in a run session, and the Epic Games Launcher opens on its own with its games playing in it. Run sessions for these games are not pinned to the big cores and get DirectAudio and the added-games list like Steam. The Games tab card is now "Settings", titled "<game> Settings": Start without Steam, FEX preset, Wine sync (ntsync, fsync, esync, wineserver or the app default) and Default, which puts everything changed for the game back to the app's settings. The app-wide Wine sync choice is shown in the Steam settings Session tab. * Address review: uninstall guard, routed games, shortcut matching Opening or reinstalling the Epic Games Launcher waits while it is being uninstalled. Added games that are Steam installs keep their Start without Steam setting under their Steam app id and start as that Steam game. Live shortcut lookups wait for Steam's library to load and match a same-name shortcut by its executable, so no duplicate is added. The session treats the open launcher as itself even when it could not tell its Steam app id. * Address review: drop a queued launcher switch when it is uninstalled A confirmed switch to the Epic Games Launcher that is still waiting for the old session to end is cancelled when the launcher is uninstalled, and never starts while the uninstall runs. The launcher id test sets its environment for its own runs only.
This commit is contained in:
1 parent
83eda433c8
commit
97f976ef6c
107 files changed
+8860
-371
No files matched your search
@@ -41,6 +41,14 @@ 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 \
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -581,6 +581,31 @@ def wait_for_steam_shortcut_overview(agent_dir, game_id, timeout=45):
|
||||
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
|
||||
environment, and Proton's wine processes inherit it)."""
|
||||
@@ -858,6 +883,28 @@ def main(argv):
|
||||
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
|
||||
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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
|
||||
@@ -563,13 +563,32 @@ def want_fex():
|
||||
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 +605,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:
|
||||
|
||||
@@ -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")
|
||||
|
||||
@@ -251,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)
|
||||
|
||||
|
||||
@@ -340,7 +310,6 @@ def main():
|
||||
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]:
|
||||
|
||||
@@ -10,7 +10,9 @@ import importlib.util
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import uuid
|
||||
|
||||
import gi
|
||||
@@ -24,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">
|
||||
@@ -80,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
|
||||
@@ -149,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()
|
||||
|
||||
@@ -171,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:
|
||||
@@ -195,6 +213,15 @@ 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))
|
||||
|
||||
@@ -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__":
|
||||
|
||||
@@ -301,6 +301,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
|
||||
@@ -311,17 +329,17 @@ 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
|
||||
;;
|
||||
@@ -495,6 +513,9 @@ case $mode in
|
||||
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
|
||||
@@ -514,6 +535,44 @@ case $mode in
|
||||
esac
|
||||
done < <(xprop -spy -root "${atoms[@]}" 2>/dev/null)
|
||||
) &
|
||||
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=
|
||||
@@ -539,44 +598,7 @@ case $mode in
|
||||
fi
|
||||
if [ -n "$_bl_held" ]; then
|
||||
set -- "${_bl_rest[@]}"
|
||||
(
|
||||
_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 "$_bl_held" 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 $_bl_held"
|
||||
_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 $_bl_held"
|
||||
_bl_launch_ready=1
|
||||
fi
|
||||
if [ "$_bl_launch_ready" = 1 ]; then
|
||||
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"
|
||||
fi
|
||||
) &
|
||||
steam_hold_launch "$_bl_held" &
|
||||
fi
|
||||
fi
|
||||
if [ -s "$HOME/.bl-autolaunch" ]; then
|
||||
@@ -727,6 +749,81 @@ BUSCONF
|
||||
echo "== steam args: ${_bl_ui[*]} ${_bl_cdp[*]} ${_bl_lang[*]} -clientbeta $steam_channel -no-cef-sandbox -cef-ozone-platform=x11 ${_bl_cef[*]} $*"
|
||||
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_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_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_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
|
||||
@@ -766,6 +863,8 @@ BUSCONF
|
||||
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"
|
||||
@@ -827,7 +926,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=$!
|
||||
@@ -842,6 +941,7 @@ BUSCONF
|
||||
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 < "$_d/cmdline" 2>/dev/null || continue
|
||||
@@ -887,8 +987,9 @@ BUSCONF
|
||||
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"
|
||||
@@ -939,6 +1040,25 @@ 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 --
|
||||
|
||||
@@ -184,7 +184,7 @@ def unimported(steam_root, snapshot, candidates):
|
||||
|
||||
|
||||
def watch(steam_root, listing):
|
||||
games = [game for game in read_json(listing, []) if not store_game(game)]
|
||||
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 = {}, {}
|
||||
@@ -408,6 +408,9 @@ def route(steam_root, acct, games):
|
||||
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)
|
||||
|
||||
@@ -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,7 +344,7 @@ 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())],
|
||||
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=compat.adopt_extras(os.path.join(steam_root, "compatibilitytools.d")))
|
||||
print("droiddeck-steam-shortcuts: mapped them to %s" % compat.TOOL)
|
||||
except Exception as e:
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -73,7 +73,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 "$@"
|
||||
@@ -660,6 +660,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 +771,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", {})
|
||||
|
||||
@@ -70,7 +70,7 @@ def required():
|
||||
for arch in ['x86_64', 'i386']:
|
||||
paths += ['assets/linuxfs/' + arch + '/' + lib for lib in ['libfakeinput.so', 'libblsession.so']]
|
||||
paths += ['assets/linuxfs/x86_64/' + lib for lib in
|
||||
['libfaultreport.so', 'libthunkaudit.so', 'libvulkan-thunk.so']]
|
||||
['libfaultreport.so', 'libthunkaudit.so', 'libvulkan-thunk.so', 'libwebkitinput.so']]
|
||||
paths += ['assets/linuxfs/i386/libfaultreport.so']
|
||||
paths += ['assets/linuxfs/usr/local/lib/droiddeck-msitools/' + name for name in
|
||||
['msiinfo', 'cabextract', '7z', '7z.so', 'libmsi-1.0.so.0', 'libgsf-1.so.114', 'libgcab-1.0.so.0']]
|
||||
|
||||
@@ -516,6 +516,65 @@ class ProtonRunTest(Temp):
|
||||
self.assertEqual(env["SteamAppId"], "413150")
|
||||
self.assertTrue((self.root / "steamapps/compatdata/413150").is_dir())
|
||||
|
||||
def run_main(self, argv):
|
||||
calls, dirs = [], []
|
||||
with mock.patch.dict(os.environ, {"STEAM_COMPAT_CLIENT_INSTALL_PATH": str(self.root)}), \
|
||||
mock.patch.object(RUN["os"], "execve", lambda *a: calls.append(a)), \
|
||||
mock.patch.object(RUN["os"], "chdir", dirs.append), mock.patch.dict(RUN, {"say": lambda message: None}):
|
||||
code = RUN["main"](argv)
|
||||
return code, calls, dirs
|
||||
|
||||
def test_without_steam_a_steam_game_starts_its_default_windows_launch(self):
|
||||
info = {"common": {"type": "Game", "oslist": "windows,linux"}, "config": {"launch": {
|
||||
"0": {"executable": "Bin\\Game.exe", "arguments": "-dx11 \"-name=Two Words\"", "workingdir": "bin",
|
||||
"type": "default", "config": {"oslist": "windows"}},
|
||||
"1": {"executable": "game.sh", "type": "default", "config": {"oslist": "linux"}},
|
||||
"2": {"executable": "Beta.exe", "type": "default", "config": {"oslist": "windows", "betakey": "beta"}},
|
||||
"3": {"executable": "Tools\\Editor.exe", "type": "option1"},
|
||||
}}}
|
||||
self.write("Steam/appcache/appinfo.vdf", appinfo({413150: info}))
|
||||
program = self.game("413150", "Some Game", "bin/game.exe")
|
||||
self.game("413150", "Some Game", "Tools/Editor.exe")
|
||||
code, calls, dirs = self.run_main(["--app", "413150", "--options", "-windowed"])
|
||||
self.assertIsNone(code)
|
||||
entry, argv, env = calls[0]
|
||||
self.assertEqual(argv[1:], ["waitforexitandrun", str(program), "-dx11", "-name=Two Words", "-windowed"])
|
||||
self.assertEqual((env["SteamAppId"], env["STEAM_COMPAT_DATA_PATH"]),
|
||||
("413150", str(self.root / "steamapps/compatdata/413150")))
|
||||
self.assertEqual(dirs, [str(program.parent)])
|
||||
|
||||
def test_without_steam_a_game_steam_cannot_start_is_refused(self):
|
||||
self.write("Steam/appcache/appinfo.vdf", appinfo({413150: STARDEW}))
|
||||
self.assertEqual(self.run_main(["--app", "413150"])[0], 2)
|
||||
self.assertEqual(self.run_main(["--app", "3384071994"])[0], 2)
|
||||
self.assertEqual(self.run_main(["--app", "0"])[0], 2)
|
||||
self.assertEqual(self.run_main(["--app", "game"])[0], 2)
|
||||
linux = {"common": {"type": "Game"}, "config": {"launch": {"0": {"executable": "run.sh", "config": {"oslist": "linux"}}}}}
|
||||
self.write("Steam/appcache/appinfo.vdf", appinfo({70: linux}))
|
||||
self.game("70", "Linux Game", "run.sh")
|
||||
self.assertEqual(self.run_main(["--app", "70"])[0], 2)
|
||||
|
||||
def test_without_steam_a_shortcut_keeps_its_prefix_folder_and_launch_options(self):
|
||||
bat = self.write("Games/Epic/Game/.droiddeck-launch.bat", b"@echo off")
|
||||
start = self.tmp / "Games/Epic/Game/Binaries"
|
||||
start.mkdir()
|
||||
code, calls, dirs = self.run_main(["--app", "2733369024", "--dir", str(start), "--options",
|
||||
"PROTON_LOG=1 %command% -epicportal", "--", str(bat)])
|
||||
self.assertIsNone(code)
|
||||
entry, argv, env = calls[0]
|
||||
self.assertEqual(argv[1:], ["waitforexitandrun", str(bat), "-epicportal"])
|
||||
self.assertEqual((env["STEAM_COMPAT_DATA_PATH"], env["SteamAppId"], env["SteamGameId"], env["PROTON_LOG"]),
|
||||
(str(self.root / "steamapps/compatdata/2733369024"), "0", str(2733369024 << 32 | 0x02000000), "1"))
|
||||
self.assertTrue((self.root / "steamapps/compatdata/2733369024").is_dir())
|
||||
self.assertEqual(dirs, [str(start)])
|
||||
|
||||
def test_launch_options_split_like_steam_does(self):
|
||||
split = RUN["split_options"]
|
||||
self.assertEqual(split(""), ({}, []))
|
||||
self.assertEqual(split("-windowed -w 1280"), ({}, ["-windowed", "-w", "1280"]))
|
||||
self.assertEqual(split("A=1 B=\"x y\" gamemoderun %command% -dx12"), ({"A": "1", "B": "x y"}, ["-dx12"]))
|
||||
self.assertEqual(split("\"unterminated -x"), ({}, ["\"unterminated", "-x"]))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -291,6 +291,53 @@ class AgentTest(unittest.TestCase):
|
||||
self.assertFalse(result["supported"])
|
||||
evaluate.assert_not_called()
|
||||
|
||||
def test_shortcut_state_tells_a_lost_shortcut_from_a_loading_library(self):
|
||||
game_id = str((3333273269 << 32) | 0x02000000)
|
||||
self.assertEqual("not-shortcut", agent.steam_shortcut_state(self.dir, "413150"))
|
||||
for values, wanted, calls in ((["loading", "ready"], "ready", 2), (["loading", "missing"], "missing", 3),
|
||||
([None], "loading", 3)):
|
||||
clock = [0.0]
|
||||
replies = [{"value": v} for v in values] + [{"value": values[-1]}] * 10
|
||||
with self.subTest(values=values), patch.object(agent, "cdp_eval", side_effect=replies) as evaluate, \
|
||||
patch.object(agent.time, "monotonic", side_effect=lambda: clock[0]), \
|
||||
patch.object(agent.time, "sleep", side_effect=lambda delay: clock.__setitem__(0, clock[0] + delay)):
|
||||
self.assertEqual(wanted, agent.steam_shortcut_state(self.dir, game_id, timeout=1))
|
||||
self.assertEqual(calls, evaluate.call_count)
|
||||
self.assertIn("GetAppOverviewByGameID(%s)" % json.dumps(game_id), evaluate.call_args_list[0].args[1])
|
||||
|
||||
def test_shortcut_state_waits_out_an_unreachable_client_but_not_other_errors(self):
|
||||
game_id = str((3333273269 << 32) | 0x02000000)
|
||||
clock = [0.0]
|
||||
with patch.object(agent, "cdp_eval", side_effect=agent.AgentError("NO_DEVTOOLS", "down")), \
|
||||
patch.object(agent.time, "monotonic", side_effect=lambda: clock[0]), \
|
||||
patch.object(agent.time, "sleep", side_effect=lambda delay: clock.__setitem__(0, clock[0] + delay)):
|
||||
self.assertEqual("loading", agent.steam_shortcut_state(self.dir, game_id, timeout=1))
|
||||
with patch.object(agent, "cdp_eval", side_effect=agent.AgentError("CDP_EXCEPTION", "boom")):
|
||||
with self.assertRaises(agent.AgentError):
|
||||
agent.steam_shortcut_state(self.dir, game_id, timeout=1)
|
||||
|
||||
def test_shortcut_state_command_exits_with_the_state(self):
|
||||
game_id = str((3333273269 << 32) | 0x02000000)
|
||||
launch = self.dir.parent
|
||||
with patch.dict(os.environ, {"BL_LAUNCH_DIR": str(launch)}):
|
||||
for state, code in (("ready", 0), ("missing", 4), ("not-shortcut", 3), ("loading", 1)):
|
||||
with self.subTest(state=state), patch.object(agent, "steam_shortcut_state", return_value=state) as ask:
|
||||
self.assertEqual(code, agent.main(["--steam-shortcut-state", game_id, "2"]))
|
||||
self.assertEqual((launch / "agent", game_id, "2"), ask.call_args.args)
|
||||
with patch.object(agent, "steam_shortcut_state", side_effect=agent.AgentError("CDP_EXCEPTION", "boom")):
|
||||
self.assertEqual(1, agent.main(["--steam-shortcut-state", game_id]))
|
||||
self.assertEqual(2, agent.main(["--steam-shortcut-state"]))
|
||||
|
||||
def test_asleep_command_reports_steams_own_sleep_state(self):
|
||||
with patch.dict(os.environ, {"BL_LAUNCH_DIR": str(self.dir.parent)}):
|
||||
for value, code in (("yes", 0), ("no", 5), ("unknown", 1), (None, 1)):
|
||||
with self.subTest(value=value), patch.object(agent, "cdp_eval", return_value={"value": value}) as ask:
|
||||
self.assertEqual(code, agent.main(["--steam-asleep"]))
|
||||
self.assertIn("m_bSuspending", ask.call_args.args[1])
|
||||
self.assertFalse(ask.call_args.kwargs["await_promise"])
|
||||
with patch.object(agent, "cdp_eval", side_effect=agent.AgentError("NO_DEVTOOLS", "down")):
|
||||
self.assertEqual(1, agent.main(["--steam-asleep"]))
|
||||
|
||||
def test_cdp_exception(self):
|
||||
server = FakeDevTools({"result": {"result": {"type": "object"}, "exceptionDetails": {
|
||||
"text": "Uncaught", "exception": {"description": "ReferenceError: SteamClient is not defined"}}}})
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -317,6 +317,35 @@ class ExtractTest(FexTestCase):
|
||||
self.assertTrue((self.home / ".config/droiddeck/fex-wanted").is_file())
|
||||
self.assertFalse(json.loads((self.home / ".local/share/droiddeck-fex/status.json").read_text())["ready"])
|
||||
|
||||
def test_uruntime_that_only_drops_extended_attributes_still_unpacks(self):
|
||||
tool = self.uruntime(
|
||||
"mkdir -p AppDir && touch AppDir/AppRun\n"
|
||||
"echo 'Failed to exec memfd: EACCES: Permission denied. Trying tmpfile in /tmp...' >&2\n"
|
||||
"echo 'write_xattr: could not write xattr security.selinux for file ./AppDir/.DirIcon because you are not superuser!' >&2\n"
|
||||
"echo 'Further error messages of this type are suppressed!' >&2\n"
|
||||
"exit 2\n")
|
||||
with mock.patch.dict(G, {"URUNTIME": tool, "fex_install": lambda: None, "steam_running": lambda: False}):
|
||||
status, said = self.quiet(FEX["extract"], "image.AppImage")
|
||||
self.assertEqual(status, 0)
|
||||
self.assertIn("could not keep the image's extended attributes", said)
|
||||
self.assertTrue(Path("squashfs-root/AppRun").is_file())
|
||||
|
||||
def test_an_attribute_only_failure_without_apprun_is_not_taken_as_unpacked(self):
|
||||
tool = self.uruntime(
|
||||
"mkdir -p AppDir\n"
|
||||
"echo 'write_xattr: could not write xattr security.selinux for file ./AppDir/.DirIcon because you are not superuser!' >&2\n"
|
||||
"exit 2\n")
|
||||
with mock.patch.dict(G, {"URUNTIME": tool, "fex_install": lambda: None, "steam_running": lambda: False, "prepare": lambda: None}):
|
||||
status, said = self.quiet(FEX["extract"], "image.AppImage")
|
||||
self.assertIn("uruntime could not extract it (status 2)", said)
|
||||
self.assertNotIn("could not keep the image's extended attributes", said)
|
||||
self.assertFalse(os.path.lexists("squashfs-root/AppRun"))
|
||||
|
||||
def test_other_uruntime_errors_are_not_taken_as_unpacked(self):
|
||||
self.assertFalse(FEX["only_xattrs_failed"]("write_xattr: could not write xattr\nwrite_file: failed to create file x\n"))
|
||||
self.assertFalse(FEX["only_xattrs_failed"](""))
|
||||
self.assertTrue(FEX["only_xattrs_failed"]("proot error: execveat() failed\nwrite_xattr: could not write xattr\n"))
|
||||
|
||||
def test_an_arm64_image_does_not_ask_for_fex(self):
|
||||
self.write(self.image, elf(183) + b"payload", 0o755)
|
||||
tool = self.uruntime("mkdir -p squashfs-root\n")
|
||||
@@ -335,6 +364,33 @@ class ExtractTest(FexTestCase):
|
||||
self.assertIn("no AppImage runtime for ARM64, no FEX yet and no unsquashfs", said)
|
||||
self.assertFalse(os.path.lexists("squashfs-root"))
|
||||
|
||||
def test_unsquashfs_fallback_disables_unwritable_xattrs(self):
|
||||
tool = self.uruntime("exit 1\n")
|
||||
commands = []
|
||||
|
||||
def call(argv, **kwargs):
|
||||
commands.append(argv)
|
||||
if argv[0] == tool:
|
||||
return 1
|
||||
(self.work / "squashfs-root").mkdir()
|
||||
(self.work / "squashfs-root/AppRun").touch()
|
||||
return 0
|
||||
|
||||
with mock.patch.dict(G, {
|
||||
"URUNTIME": tool,
|
||||
"prepare": lambda: None,
|
||||
"fex_install": lambda: None,
|
||||
"steam_running": lambda: False,
|
||||
"want_fex": lambda: None,
|
||||
}), mock.patch("shutil.which", return_value="/usr/bin/unsquashfs"), \
|
||||
mock.patch("subprocess.call", side_effect=call):
|
||||
status, said = self.quiet(FEX["extract"], "image.AppImage")
|
||||
self.assertEqual(status, 0)
|
||||
self.assertIn("uruntime could not extract it (status 1)", said)
|
||||
self.assertEqual(commands[-1][0], "/usr/bin/unsquashfs")
|
||||
self.assertIn("-no-xattrs", commands[-1])
|
||||
self.assertTrue(Path("squashfs-root/AppRun").is_file())
|
||||
|
||||
|
||||
class LaunchTest(FexTestCase):
|
||||
def test_the_guest_environment(self):
|
||||
|
||||
@@ -90,6 +90,12 @@ class GameEnvironmentTest(unittest.TestCase):
|
||||
self.assertEqual(env["REMOVE"], "inherited")
|
||||
self.assertEqual(MODULE["apply_config"](env, config, "43")["CUSTOM"], "shared")
|
||||
|
||||
def test_a_games_wine_sync_choice_also_reaches_its_setup_runs(self):
|
||||
env = {"BL_SYNC": "1", "BL_SYNC_FALLBACK": "1", "BL_FSYNC_FIRST": "0", "OTHER": "kept"}
|
||||
config = {"version": 1, "games": {"42": {"BL_SYNC": "0", "BL_FSYNC_FIRST": "1", "PROTON_NO_ESYNC": "1", "FEX_TSOENABLED": "1"}}}
|
||||
chosen = MODULE["apply_config"](env, MODULE["sync_config"](config, "42"), "42")
|
||||
self.assertEqual(chosen, {"BL_SYNC": "0", "BL_SYNC_FALLBACK": "1", "BL_FSYNC_FIRST": "1", "PROTON_NO_ESYNC": "1", "OTHER": "kept"})
|
||||
|
||||
def test_component_profiles_override_general_and_restore_it_for_the_next_game(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
@@ -947,28 +953,6 @@ if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
|
||||
class StartWithoutSteamTest(unittest.TestCase):
|
||||
def test_start_without_steam_uses_umu_or_runinprefix_and_only_when_asked(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
ge = Path(tmp) / "ge/proton"
|
||||
ge.parent.mkdir()
|
||||
ge.write_text('if "UMU_ID" in os.environ:\n argv = [wine, "c:\\\\windows\\\\system32\\\\umu.exe"]\n')
|
||||
valve = Path(tmp) / "valve/proton"
|
||||
valve.parent.mkdir()
|
||||
valve.write_text('argv = [wine, "c:\\\\windows\\\\system32\\\\steam.exe"]\n')
|
||||
start = MODULE["start_without_steam"]
|
||||
game = [str(ge), "waitforexitandrun", "/games/Game.exe", "-windowed"]
|
||||
self.assertEqual(start(game, {}, "3384071994"), (game, {}))
|
||||
on = {"DROIDDECK_NO_STEAM": "1"}
|
||||
self.assertEqual(start(game, on, "3384071994"), (game, dict(on, UMU_ID="0")))
|
||||
self.assertEqual(start(game, on, "570940")[1]["UMU_ID"], "570940")
|
||||
self.assertEqual(start(game, dict(on, UMU_ID="umu-1"), "570940")[1]["UMU_ID"], "umu-1")
|
||||
plain = [str(valve)] + game[1:]
|
||||
self.assertEqual(start(plain, on, "570940"), ([str(valve), "runinprefix", "/games/Game.exe", "-windowed"], on))
|
||||
for other in ([str(ge), "run", "/x.exe"], [str(ge), "waitforexitandrun"], [str(valve), "getcompatpath", "/x"]):
|
||||
self.assertEqual(start(other, on, "570940"), (other, on))
|
||||
|
||||
|
||||
class ForceSsbsTest(unittest.TestCase):
|
||||
def test_libssbs_is_preloaded_only_when_asked_and_only_into_arm64_proton(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
|
||||
@@ -23,6 +23,7 @@ IFACE = NAME + ".Manager"
|
||||
@unittest.skipUnless(Gio and os.environ.get("DBUS_SESSION_BUS_ADDRESS"), "requires dbus-run-session and PyGObject")
|
||||
class SleepHandshakeTest(unittest.TestCase):
|
||||
ARGS = []
|
||||
AGENT_EXIT = None
|
||||
|
||||
def setUp(self):
|
||||
self.directory = tempfile.TemporaryDirectory()
|
||||
@@ -37,7 +38,16 @@ class SleepHandshakeTest(unittest.TestCase):
|
||||
lambda bus, sender, path, interface, name, body: self.signals.append(body.unpack()[0]))
|
||||
env = dict(os.environ, BL_LAUNCH_DIR=str(self.dir),
|
||||
DBUS_SYSTEM_BUS_ADDRESS=os.environ["DBUS_SESSION_BUS_ADDRESS"])
|
||||
self.process = subprocess.Popen(["/usr/bin/python3", str(SCRIPT), *self.ARGS], env=env,
|
||||
script = SCRIPT
|
||||
if self.AGENT_EXIT is not None:
|
||||
bin_dir = self.dir / "bin"
|
||||
bin_dir.mkdir()
|
||||
script = bin_dir / SCRIPT.name
|
||||
script.write_text(SCRIPT.read_text())
|
||||
agent = bin_dir / "droiddeck-agent"
|
||||
agent.write_text("#!/bin/sh\necho \"$@\" >> \"%s\"\nexit %d\n" % (self.dir / "agent-calls", self.AGENT_EXIT))
|
||||
agent.chmod(0o755)
|
||||
self.process = subprocess.Popen(["/usr/bin/python3", str(script), *self.ARGS], env=env,
|
||||
stdout=subprocess.DEVNULL)
|
||||
self.wait_for(lambda: (self.dir / "steam-sleep-ready").exists())
|
||||
|
||||
@@ -220,6 +230,53 @@ class SleepHandshakeTest(unittest.TestCase):
|
||||
self.call(IFACE, "PowerOff", GLib.Variant("(b)", (True,)))
|
||||
|
||||
|
||||
class FakeAgentCase(unittest.TestCase):
|
||||
ARGS = []
|
||||
setUp = SleepHandshakeTest.setUp
|
||||
tearDown = SleepHandshakeTest.tearDown
|
||||
wait_for = SleepHandshakeTest.wait_for
|
||||
call = SleepHandshakeTest.call
|
||||
suspend = SleepHandshakeTest.suspend
|
||||
state = SleepHandshakeTest.state
|
||||
request_wake = SleepHandshakeTest.request_wake
|
||||
|
||||
def asked(self):
|
||||
path = self.dir / "agent-calls"
|
||||
return path.read_text().split() if path.exists() else []
|
||||
|
||||
|
||||
@unittest.skipUnless(Gio and os.environ.get("DBUS_SESSION_BUS_ADDRESS"), "requires dbus-run-session and PyGObject")
|
||||
class AwakeSteamTest(FakeAgentCase):
|
||||
AGENT_EXIT = 5
|
||||
|
||||
def test_resuming_an_awake_steam_sends_no_sleep_wake_pair(self):
|
||||
self.request_wake()
|
||||
self.wait_for(lambda: self.asked())
|
||||
deadline = time.monotonic() + 1.5
|
||||
while time.monotonic() < deadline:
|
||||
self.wait_for(lambda: True)
|
||||
time.sleep(0.05)
|
||||
self.assertEqual([], self.signals)
|
||||
self.assertEqual(["--steam-asleep"], self.asked())
|
||||
|
||||
def test_a_pending_sleep_still_wakes_without_asking_steam(self):
|
||||
token = self.suspend()
|
||||
self.state(token, "paused")
|
||||
self.request_wake()
|
||||
self.wait_for(lambda: self.signals == [True, False])
|
||||
self.assertEqual([], self.asked())
|
||||
|
||||
|
||||
@unittest.skipUnless(Gio and os.environ.get("DBUS_SESSION_BUS_ADDRESS"), "requires dbus-run-session and PyGObject")
|
||||
class AsleepSteamTest(FakeAgentCase):
|
||||
AGENT_EXIT = 0
|
||||
|
||||
def test_resuming_a_sleeping_steam_replays_the_pair(self):
|
||||
self.request_wake()
|
||||
self.wait_for(lambda: self.signals == [True, False])
|
||||
self.assertEqual(["--steam-asleep"], self.asked())
|
||||
|
||||
|
||||
class WithNetworkManagerTest(SleepHandshakeTest):
|
||||
ARGS = ["--with-netmanager"]
|
||||
|
||||
|
||||
@@ -65,6 +65,7 @@ static void send_toplevel_configure(struct surface *s) { (void)s; resizes++; }
|
||||
#define pointer_event(...) ((void)0)
|
||||
#define pointer_button(...) ((void)0)
|
||||
#define scroll_event(...) ((void)0)
|
||||
#define axis_event(...) ((void)0)
|
||||
#define pointer_delta(...) ((void)0)
|
||||
#define deliver_touch(m) ((void)0)
|
||||
#define deliver_pointer(m) (pointers++)
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import signal
|
||||
import subprocess
|
||||
import tempfile
|
||||
import time
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
SESSION = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-session"
|
||||
|
||||
|
||||
def run_program_function():
|
||||
match = re.search(r"^ run_program\(\) \{\n.*?^ \}\n", SESSION.read_text(), re.M | re.S)
|
||||
return match.group(0)
|
||||
|
||||
|
||||
class RunStatusTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.dir = Path(tempfile.mkdtemp())
|
||||
self.addCleanup(shutil.rmtree, self.dir, True)
|
||||
|
||||
def run_with(self, command, launch_dir=True):
|
||||
env = dict(os.environ)
|
||||
env.pop("BL_LAUNCH_DIR", None)
|
||||
if launch_dir:
|
||||
env["BL_LAUNCH_DIR"] = str(self.dir)
|
||||
return subprocess.run(["bash", "-c", run_program_function() + "run_program " + command + "; echo unreachable"],
|
||||
env=env, capture_output=True, text=True, timeout=30)
|
||||
|
||||
def test_the_program_status_is_kept_for_the_app(self):
|
||||
run = self.run_with("sh -c 'exit 7'")
|
||||
self.assertEqual(7, run.returncode)
|
||||
self.assertNotIn("unreachable", run.stdout)
|
||||
self.assertEqual("7\n", (self.dir / "run-status").read_text())
|
||||
self.assertFalse((self.dir / "run-status.tmp").exists())
|
||||
|
||||
def test_a_clean_exit_is_recorded_as_zero(self):
|
||||
self.assertEqual(0, self.run_with("true").returncode)
|
||||
self.assertEqual("0\n", (self.dir / "run-status").read_text())
|
||||
|
||||
def test_nothing_is_written_without_a_launch_dir(self):
|
||||
self.assertEqual(3, self.run_with("sh -c 'exit 3'", launch_dir=False).returncode)
|
||||
self.assertEqual([], os.listdir(self.dir))
|
||||
|
||||
def signalled(self, sig, program):
|
||||
env = dict(os.environ, BL_LAUNCH_DIR=str(self.dir))
|
||||
ready = self.dir / "ready"
|
||||
proc = subprocess.Popen(["bash", "-c", run_program_function() + "run_program " + program],
|
||||
env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
self.addCleanup(proc.kill)
|
||||
deadline = time.monotonic() + 10
|
||||
while not ready.exists() and time.monotonic() < deadline:
|
||||
time.sleep(0.05)
|
||||
self.assertTrue(ready.exists())
|
||||
proc.send_signal(sig)
|
||||
return proc.wait(timeout=10)
|
||||
|
||||
def test_a_stop_signal_reaches_the_program(self):
|
||||
program = ("python3 -c 'import signal, sys, time; signal.signal(signal.SIGTERM, lambda *a: sys.exit(9)); "
|
||||
"open(sys.argv[1], \"w\").close(); time.sleep(30)' %s" % (self.dir / "ready"))
|
||||
self.assertEqual(9, self.signalled(signal.SIGTERM, program))
|
||||
self.assertEqual("9\n", (self.dir / "run-status").read_text())
|
||||
|
||||
def test_an_interrupt_reaches_the_program(self):
|
||||
program = ("python3 -c 'import sys, time; open(sys.argv[1], \"w\").close(); time.sleep(30)' %s"
|
||||
% (self.dir / "ready"))
|
||||
self.assertEqual(130, self.signalled(signal.SIGINT, program))
|
||||
self.assertEqual("130\n", (self.dir / "run-status").read_text())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -8,15 +8,8 @@ import unittest
|
||||
|
||||
SESSION = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-session"
|
||||
SOURCE = SESSION.read_text()
|
||||
END = SOURCE.index(
|
||||
' if [ -s "$HOME/.bl-autolaunch" ]; then',
|
||||
SOURCE.index(" _bl_launch_ready="),
|
||||
)
|
||||
START = SOURCE.rfind(
|
||||
' if [ -n "${BL_LAUNCH_DIR:-}" ] && [ -z "${BL_DESKTOP:-}" ]; then',
|
||||
0,
|
||||
END,
|
||||
)
|
||||
START = SOURCE.index(" steam_hold_launch() {")
|
||||
END = SOURCE.index(' if [ -s "$HOME/.bl-autolaunch" ]; then', START)
|
||||
assert START >= 0
|
||||
LAUNCH_BLOCK = textwrap.dedent(SOURCE[START:END])
|
||||
|
||||
@@ -103,6 +96,20 @@ class SteamColdLaunchTest(unittest.TestCase):
|
||||
self.assertEqual("1", self.agent_count.read_text().strip())
|
||||
self.assertFalse(self.sleep_args.exists())
|
||||
|
||||
def test_a_restart_for_a_game_waits_for_its_overview_too(self):
|
||||
game_id = str((3551182975 << 32) | 0x02000000)
|
||||
loop = SOURCE[SOURCE.index(' if [ -s "$HOME/.bl-restart-game" ]; then'):SOURCE.index(' if [ -f "$HOME/.bl-restart-once" ]; then')]
|
||||
self.assertIn('steam_hold_launch "$_bl_again" &', loop)
|
||||
self.assertNotIn("set -- \"steam://rungameid/", loop)
|
||||
script = self.block + '\nsteam_hold_launch "%s"\n' % game_id
|
||||
env = dict(os.environ, HOME=str(self.root), BL_LAUNCH_DIR=str(self.launch_dir),
|
||||
PATH=str(self.bin) + os.pathsep + os.environ["PATH"],
|
||||
AGENT_ARGS=str(self.agent_args), SLEEP_ARGS=str(self.sleep_args),
|
||||
AGENT_COUNT=str(self.agent_count), AGENT_STATUS="1 0")
|
||||
result = subprocess.run(["bash", "-c", script, "restart"], env=env, text=True, capture_output=True, timeout=10, check=True)
|
||||
self.assertEqual(game_id, (self.launch_dir / "steam-game").read_text().strip(), result.stdout)
|
||||
self.assertEqual(["--wait-steam-shortcut-overview", game_id, "45"], self.agent_args.read_text().splitlines())
|
||||
|
||||
def test_non_game_steam_urls_remain_on_the_original_startup_arguments(self):
|
||||
url = "steam://open/library"
|
||||
result = self.run_launch(url, 0)
|
||||
|
||||
@@ -84,6 +84,17 @@ class ImportsTest(unittest.TestCase):
|
||||
imports.watch(str(self.steam), str(listing))
|
||||
identify.assert_not_called()
|
||||
|
||||
def test_native_programs_stay_shortcuts_and_are_never_looked_up(self):
|
||||
self.snapshot()
|
||||
game = dict(self.game, native=True)
|
||||
self.assertEqual(([game], {}), imports.route(self.steam, self.acct, [game]))
|
||||
self.assertFalse((self.steam / 'steamapps/appmanifest_42.acf').exists())
|
||||
listing = self.root / 'games.json'
|
||||
listing.write_text(json.dumps([game]))
|
||||
with patch.object(imports, 'identify') as identify:
|
||||
imports.watch(str(self.steam), str(listing))
|
||||
identify.assert_not_called()
|
||||
|
||||
def test_migrates_only_unchanged_legacy_import_manifests(self):
|
||||
self.snapshot()
|
||||
imports.route(self.steam, self.acct, [self.game])
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
import textwrap
|
||||
import unittest
|
||||
|
||||
SESSION = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-session"
|
||||
SOURCE = SESSION.read_text()
|
||||
START = SOURCE.index(" steam_other_game_running() {")
|
||||
END = SOURCE.index(" steam_bring_forward() {", START)
|
||||
FUNCTIONS = textwrap.dedent(SOURCE[START:END])
|
||||
GAME = str((3333273269 << 32) | 0x02000000)
|
||||
|
||||
|
||||
class SteamShortcutRecoveryTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
self.root = Path(self.temp.name)
|
||||
self.launch = self.root / "session"
|
||||
self.launch.mkdir()
|
||||
self.bin = self.root / "bin"
|
||||
self.bin.mkdir()
|
||||
steam = self.root / "steam/steamrtarm64"
|
||||
steam.mkdir(parents=True)
|
||||
self.steam_log = self.root / "steam-args"
|
||||
(steam / "steam").write_text("#!/bin/sh\nprintf '%s\\n' \"$*\" >> \"$STEAM_LOG\"\n")
|
||||
(steam / "steam").chmod(0o755)
|
||||
self.agent = self.bin / "droiddeck-agent"
|
||||
self.agent.write_text(
|
||||
"#!/bin/sh\n"
|
||||
"n=$(cat \"$AGENT_COUNT\" 2>/dev/null || echo 0); n=$((n + 1)); echo $n > \"$AGENT_COUNT\"\n"
|
||||
"i=0; last=0\n"
|
||||
"for s in $AGENT_STATES; do i=$((i + 1)); last=$s; [ \"$i\" -eq \"$n\" ] && exit \"$s\"; done\n"
|
||||
"exit \"$last\"\n")
|
||||
self.agent.chmod(0o755)
|
||||
|
||||
def launch_game(self, states, focusable="769", extra=None):
|
||||
xprop = self.bin / "xprop"
|
||||
xprop.write_text("#!/bin/sh\necho 'GAMESCOPE_FOCUSABLE_APPS(CARDINAL) = %s'\n" % focusable)
|
||||
xprop.chmod(0o755)
|
||||
script = "nap() { :; }\nsteam_root=%s\n%s\nsteam_launch_game %s\n" % (
|
||||
self.root / "steam", FUNCTIONS.replace("/usr/local/bin/droiddeck-agent", str(self.agent)), GAME)
|
||||
env = dict(os.environ, HOME=str(self.root), BL_LAUNCH_DIR=str(self.launch),
|
||||
PATH=str(self.bin) + os.pathsep + os.environ["PATH"], STEAM_LOG=str(self.steam_log),
|
||||
AGENT_COUNT=str(self.root / "agent-count"), AGENT_STATES=states, **(extra or {}))
|
||||
result = subprocess.run(["bash", "-c", script], env=env, text=True, capture_output=True, timeout=10)
|
||||
self.assertEqual(0, result.returncode, result.stderr)
|
||||
steam = self.steam_log.read_text().splitlines() if self.steam_log.exists() else []
|
||||
restart = self.root / ".bl-restart-game"
|
||||
return steam, restart.read_text().strip() if restart.exists() else None, result.stdout
|
||||
|
||||
def test_a_shortcut_that_stays_known_launches_once(self):
|
||||
steam, restart, _ = self.launch_game("0")
|
||||
self.assertEqual(["steam://rungameid/" + GAME], steam)
|
||||
self.assertIsNone(restart)
|
||||
self.assertEqual("9", (self.root / "agent-count").read_text().strip())
|
||||
|
||||
def test_a_shortcut_dropped_while_launching_restarts_steam_for_it(self):
|
||||
steam, restart, out = self.launch_game("0 0 4")
|
||||
self.assertEqual(["steam://rungameid/" + GAME, "-shutdown"], steam)
|
||||
self.assertEqual(GAME, restart)
|
||||
self.assertIn("dropped shortcut", out)
|
||||
|
||||
def test_a_shortcut_already_lost_restarts_steam_without_launching(self):
|
||||
steam, restart, out = self.launch_game("4")
|
||||
self.assertEqual(["-shutdown"], steam)
|
||||
self.assertEqual(GAME, restart)
|
||||
self.assertIn("lost shortcut", out)
|
||||
|
||||
def test_steam_is_restarted_only_once_for_the_same_game(self):
|
||||
steam, restart, _ = self.launch_game("4")
|
||||
self.assertEqual(GAME, restart)
|
||||
(self.root / ".bl-restart-game").unlink()
|
||||
self.steam_log.unlink()
|
||||
(self.root / "agent-count").unlink()
|
||||
steam, restart, out = self.launch_game("4")
|
||||
self.assertEqual(["steam://rungameid/" + GAME], steam)
|
||||
self.assertIsNone(restart)
|
||||
self.assertIn("already restarted", out)
|
||||
|
||||
def test_a_ready_shortcut_allows_a_later_restart_again(self):
|
||||
self.launch_game("4")
|
||||
(self.root / ".bl-restart-game").unlink()
|
||||
(self.root / "agent-count").unlink()
|
||||
self.launch_game("0")
|
||||
self.assertFalse((self.root / ".bl-restarted-for").exists())
|
||||
|
||||
def test_a_running_game_is_never_cut_off_by_a_restart(self):
|
||||
steam, restart, _ = self.launch_game("0 4", focusable="769,3703311242")
|
||||
self.assertEqual(["steam://rungameid/" + GAME], steam)
|
||||
self.assertIsNone(restart)
|
||||
steam, restart, _ = self.launch_game("4", focusable="769,3703311242")
|
||||
self.assertIsNone(restart)
|
||||
|
||||
def test_the_open_launcher_does_not_count_as_a_running_game(self):
|
||||
(self.launch / "epic-open").write_text("2702387189\n")
|
||||
steam, restart, _ = self.launch_game("0 4", focusable="769,2702387189")
|
||||
self.assertEqual(GAME, restart)
|
||||
|
||||
def test_the_launcher_without_its_steam_id_still_does_not_count_as_a_running_game(self):
|
||||
(self.launch / "epic-open").write_text("1\n")
|
||||
launcher = {"BL_EPIC_APP_ID": "2702387189"}
|
||||
steam, restart, _ = self.launch_game("0 4", focusable="769,2702387189", extra=launcher)
|
||||
self.assertEqual(GAME, restart)
|
||||
for marker in (".bl-restart-game", ".bl-restarted-for", "agent-count"):
|
||||
(self.root / marker).unlink(missing_ok=True)
|
||||
steam, restart, _ = self.launch_game("4", focusable="769,2702387189,3703311242", extra=launcher)
|
||||
self.assertIsNone(restart)
|
||||
|
||||
def test_steam_games_are_launched_without_watching(self):
|
||||
steam, restart, _ = self.launch_game("3")
|
||||
self.assertEqual(["steam://rungameid/" + GAME], steam)
|
||||
self.assertIsNone(restart)
|
||||
self.assertEqual("1", (self.root / "agent-count").read_text().strip())
|
||||
|
||||
def check_exits(self, listings, states, beats):
|
||||
pgrep = self.bin / "pgrep"
|
||||
pgrep.write_text(
|
||||
"#!/bin/bash\n"
|
||||
"n=$(cat \"$PGREP_COUNT\" 2>/dev/null || echo 0); n=$((n + 1)); echo $n > \"$PGREP_COUNT\"\n"
|
||||
"IFS='|' read -r -a runs <<< \"$PGREP_RUNS\"\n"
|
||||
"line=${runs[$((n - 1))]:-}\n"
|
||||
"[ -n \"$line\" ] || exit 1\n"
|
||||
"printf '%s\\n' \"$line\"\n")
|
||||
pgrep.chmod(0o755)
|
||||
script = "steam_root=%s\n%s\ndeclare -A _bl_ran=()\n_bl_exited=\n%s" % (
|
||||
self.root / "steam", FUNCTIONS.replace("/usr/local/bin/droiddeck-agent", str(self.agent)),
|
||||
"steam_check_exits\n" * beats)
|
||||
env = dict(os.environ, HOME=str(self.root), BL_LAUNCH_DIR=str(self.launch),
|
||||
PATH=str(self.bin) + os.pathsep + os.environ["PATH"], STEAM_LOG=str(self.steam_log),
|
||||
AGENT_COUNT=str(self.root / "agent-count"), AGENT_STATES=states,
|
||||
PGREP_COUNT=str(self.root / "pgrep-count"), PGREP_RUNS="|".join(listings))
|
||||
result = subprocess.run(["bash", "-c", script], env=env, text=True, capture_output=True, timeout=10)
|
||||
self.assertEqual(0, result.returncode, result.stderr)
|
||||
steam = self.steam_log.read_text().splitlines() if self.steam_log.exists() else []
|
||||
agent = self.root / "agent-count"
|
||||
return steam, (self.root / ".bl-restart-lost").exists(), int(agent.read_text()) if agent.exists() else 0, result.stdout
|
||||
|
||||
RUNNING = "41 /root/.local/share/Steam/steamrtarm64/reaper SteamLaunch AppId=3333273269 -- /x/.droiddeck-launch.bat"
|
||||
|
||||
def test_a_shortcut_dropped_when_its_game_exits_restarts_steam_once_nothing_runs(self):
|
||||
steam, marker, asked, out = self.check_exits([self.RUNNING, "", "", ""], "4", 3)
|
||||
self.assertEqual(["-shutdown"], steam)
|
||||
self.assertTrue(marker)
|
||||
self.assertEqual(1, asked)
|
||||
self.assertIn("3333273269", out)
|
||||
|
||||
def test_a_shortcut_still_listed_after_its_game_exits_is_left_alone(self):
|
||||
steam, marker, asked, _ = self.check_exits([self.RUNNING, "", "", ""], "0", 4)
|
||||
self.assertEqual([], steam)
|
||||
self.assertFalse(marker)
|
||||
self.assertEqual(1, asked)
|
||||
|
||||
def test_the_check_waits_a_quiet_beat_after_the_exit(self):
|
||||
steam, _, asked, _ = self.check_exits([self.RUNNING, ""], "4", 2)
|
||||
self.assertEqual([], steam)
|
||||
self.assertEqual(0, asked)
|
||||
|
||||
def test_a_game_started_meanwhile_is_never_cut_off(self):
|
||||
steam, marker, _, _ = self.check_exits([self.RUNNING, "", "", self.RUNNING], "4", 3)
|
||||
self.assertEqual([], steam)
|
||||
self.assertFalse(marker)
|
||||
|
||||
def test_steam_games_are_not_checked(self):
|
||||
game = "41 /root/.local/share/Steam/steamrtarm64/reaper SteamLaunch AppId=1245620 -- /x/eldenring.exe"
|
||||
steam, _, asked, _ = self.check_exits([game, "", "", ""], "4", 3)
|
||||
self.assertEqual([], steam)
|
||||
self.assertEqual(0, asked)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -147,6 +147,18 @@ class ShortcutsTest(unittest.TestCase):
|
||||
self.assertEqual({'1': 'Favorites', '0': shortcuts.TAG}, entry['tags'])
|
||||
self.assertEqual({'0': shortcuts.TAG}, shortcuts.merge(shortcuts.shortcut(self.game()), dict(shortcuts.shortcut(self.game()), tags={}), None, 0)[0]['tags'])
|
||||
|
||||
def test_a_copy_the_running_client_added_of_an_added_game_is_dropped(self):
|
||||
self.run_writer(self.game())
|
||||
path = self.config / 'shortcuts.vdf'
|
||||
data = shortcuts.parse(path.read_bytes())['shortcuts']
|
||||
live = dict(shortcuts.shortcut(self.game(appid=0x91234567)), tags={})
|
||||
own = dict(shortcuts.shortcut(self.game(exe='Other.exe', appid=0x92345678)), tags={})
|
||||
renamed = dict(shortcuts.shortcut(self.game(appid=0x93456789, name='My copy')), tags={})
|
||||
data.update({'7': live, '8': own, '9': renamed})
|
||||
path.write_bytes(shortcuts.write({'shortcuts': data}))
|
||||
entries = self.run_writer(self.game())
|
||||
self.assertEqual({APPID, 0x92345678, 0x93456789}, set(entries))
|
||||
|
||||
def test_a_damaged_record_is_started_over(self):
|
||||
self.run_writer(self.game())
|
||||
(self.config / shortcuts.RECORD).write_text('{not json')
|
||||
|
||||
@@ -241,7 +241,7 @@ class CloudHooks(unittest.TestCase):
|
||||
self.assertIn('bl_run ${BL_TASKSET:-} /usr/local/bin/droiddeck-game-env', sh)
|
||||
self.assertNotIn('exec ${BL_TASKSET:-} /usr/local/bin/droiddeck-game-env', sh)
|
||||
self.assertIn('[ $? -eq 10 ] && BL_STORE_EXIT=1', compat.BL_STORE_SETUP)
|
||||
self.assertIn('droiddeck-store-launch --exited "${BL_STORE_ARGS[@]}"', compat.BL_STORE_SETUP)
|
||||
self.assertIn('droiddeck-store-launch --exited --code "$rc" "${BL_STORE_ARGS[@]}"', compat.BL_STORE_SETUP)
|
||||
self.assertIn('exec "$@"', compat.BL_STORE_SETUP)
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user