mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-12-05 20:45:43 +00:00
Compare commits
57
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9cf869316d | ||
|
|
c3f2e6e12e | ||
|
|
7598dd0c22 | ||
|
|
8f3d7a5a40 | ||
|
|
b7480aed4e | ||
|
|
b3103eb504 | ||
|
|
76bc0c236a | ||
|
|
220f7573a7 | ||
|
|
957aae95fa | ||
|
|
e6b7158530 | ||
|
|
20b5785b17 | ||
|
|
fdce4ba2a3 | ||
|
|
c1cd433cb2 | ||
|
|
c887aa1cd2 | ||
|
|
6b349bfd8b | ||
|
|
952b6983e8 | ||
|
|
df058c7c1a | ||
|
|
217c58d4b3 | ||
|
|
39a3535eb5 | ||
|
|
d0796720b8 | ||
|
|
c1509a0c11 | ||
|
|
74bbd5c53f | ||
|
|
11d8bcba2e | ||
|
|
2435324c08 | ||
|
|
1ac4295709 | ||
|
|
166ed6630f | ||
|
|
a80647d0a5 | ||
|
|
521da21f05 | ||
|
|
b765844842 | ||
|
|
084aa2f6a0 | ||
|
|
1067145839 | ||
|
|
d23b32f22e | ||
|
|
d7cdf12ebf | ||
|
|
38ec930b70 | ||
|
|
0f08981dd8 | ||
|
|
6b00181c1d | ||
|
|
e26ef06695 | ||
|
|
58125fc723 | ||
|
|
536a05e06c | ||
|
|
26c30344d9 | ||
|
|
6c7c50b625 | ||
|
|
9436447f5d | ||
|
|
e4ab8a0e44 | ||
|
|
bade6edea5 | ||
|
|
981956a12f | ||
|
|
d7bb0f6dd2 | ||
|
|
aa76a79b49 | ||
|
|
4453a46382 | ||
|
|
e2c5a2d37f | ||
|
|
977d8c4735 | ||
|
|
a5f7405032 | ||
|
|
7e4ed9b7df | ||
|
|
1e659a5ea0 | ||
|
|
a566e255af | ||
|
|
d9a788046b | ||
|
|
19262fd7bd | ||
|
|
8c7016e2c4 |
No files matched your search
@@ -0,0 +1,34 @@
|
||||
name: Build bionic runtime pack and DroidDeck-Bionic tool
|
||||
|
||||
on:
|
||||
push:
|
||||
paths:
|
||||
- 'tools/bionic-runtime/**'
|
||||
- 'tools/gamescope/patches/0117-wsi-cache-present-bypass-check.patch'
|
||||
- 'tools/gamescope/patches/0119-wsi-default-images-under-limiter.patch'
|
||||
- 'app/src/main/cpp/fakeinput_steam.cpp'
|
||||
- '.github/workflows/build-bionic-runtime.yml'
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 45
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Host tools
|
||||
run: |
|
||||
set -euo pipefail
|
||||
sudo apt-get update -qq
|
||||
sudo apt-get install -y -qq --no-install-recommends libwayland-bin libwayland-dev libx11-dev libx11-xcb-dev \
|
||||
libxcb1-dev libxcb-composite0-dev libglm-dev zstd
|
||||
- name: Build
|
||||
run: |
|
||||
set -euo pipefail
|
||||
export NDK="${ANDROID_NDK_LATEST_HOME:-${ANDROID_NDK_HOME:-$ANDROID_NDK_ROOT}}"
|
||||
export BUILD_NUMBER=${{ github.run_number }}
|
||||
tools/bionic-runtime/build.sh "$RUNNER_TEMP/bionic-runtime" "$PWD/out"
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: droiddeck-bionic-runtime-${{ github.sha }}
|
||||
path: out/*
|
||||
@@ -588,7 +588,7 @@ jobs:
|
||||
path: |
|
||||
~/.cache/droiddeck-pack-inputs
|
||||
~/.cache/droiddeck-build
|
||||
key: pack-inputs-v2-${{ hashFiles('tools/packs/build.sh', 'tools/packs/fetch-verified.sh', 'tools/packs/tracking/release.env', 'tools/packs/zstd/release.env', 'tools/powervr/release.json') }}
|
||||
key: pack-inputs-v2-${{ hashFiles('tools/packs/build.sh', 'tools/packs/fetch-verified.sh', 'tools/packs/tracking/release.env', 'tools/powervr/release.json') }}
|
||||
restore-keys: pack-inputs-v2-
|
||||
- name: Build the add-on packs
|
||||
run: |
|
||||
|
||||
@@ -302,6 +302,15 @@
|
||||
android:resizeableActivity="true"
|
||||
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|keyboard|keyboardHidden|navigation|uiMode|density" />
|
||||
|
||||
<activity
|
||||
android:name=".session.KeepTopActivity"
|
||||
android:exported="false"
|
||||
android:excludeFromRecents="true"
|
||||
android:noHistory="true"
|
||||
android:taskAffinity="${applicationId}.keeptop"
|
||||
android:theme="@android:style/Theme.Translucent.NoTitleBar.Fullscreen"
|
||||
android:resizeableActivity="true"
|
||||
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|keyboard|keyboardHidden|navigation|uiMode|density" />
|
||||
<activity
|
||||
android:name=".ui.SessionTypingActivity"
|
||||
android:exported="false"
|
||||
|
||||
@@ -205,6 +205,11 @@ static void controller_fork_prepare();
|
||||
static void controller_fork_parent();
|
||||
static void controller_fork_child();
|
||||
|
||||
// bionic: libc's own start-up calls hooked functions (access) before environ is set. Settings read
|
||||
// then would be empty and cached for good, so until environ exists hooks see defaults, uncached.
|
||||
extern "C" char **environ;
|
||||
static bool env_ready() { return environ != nullptr; }
|
||||
|
||||
struct FakeConfig {
|
||||
const char *hook_dir;
|
||||
const char *udev_data_dir;
|
||||
@@ -218,6 +223,10 @@ struct FakeConfig {
|
||||
// would throw a recursive-init error there, so the fields are filled without allocating, and a
|
||||
// reentry on the initializing thread gets them while other threads wait for the fork handlers.
|
||||
static FakeConfig &config() {
|
||||
if (!env_ready()) {
|
||||
static FakeConfig early = {"/data/data/com.termux/files/home/fake-input", nullptr, false, false, false};
|
||||
return early;
|
||||
}
|
||||
static FakeConfig cfg;
|
||||
static std::atomic<int> state{0};
|
||||
static __thread bool initializing __attribute__((tls_model("initial-exec")));
|
||||
@@ -587,7 +596,7 @@ get_fake_input_rdev(const char *event) {
|
||||
|
||||
__attribute__((visibility("hidden"))) static void load_ring_paths() {
|
||||
std::lock_guard<std::recursive_mutex> guard(controller_mutex());
|
||||
if (ring_paths_loaded)
|
||||
if (ring_paths_loaded || !env_ready())
|
||||
return;
|
||||
|
||||
const char *spec = getenv("FAKE_EVDEV_MEMFD_PATHS");
|
||||
@@ -807,12 +816,25 @@ __attribute__((visibility("hidden"))) static bool is_steam_client() {
|
||||
__attribute__((visibility("hidden"))) static bool presents_steam_virtual() {
|
||||
static int known;
|
||||
if (known == 0) {
|
||||
if (!env_ready()) return false;
|
||||
const char *enabled = getenv("FAKE_EVDEV_STEAM_VIRTUAL");
|
||||
known = enabled && atoi(enabled) && !is_steam_client() ? 1 : -1;
|
||||
}
|
||||
return known == 1;
|
||||
}
|
||||
|
||||
// The bionic Proton layer's winebus has no udev bus, and its SDL bus skips 28de:11ff (Proton reads Steam's virtual
|
||||
// pad through udev/evdev), so with FAKE_EVDEV_STEAM_PAD_AS_X360=1 other processes see that pad as a plain Xbox 360 pad.
|
||||
__attribute__((visibility("hidden"))) static bool steam_pad_as_x360() {
|
||||
static int known;
|
||||
if (known == 0) {
|
||||
if (!env_ready()) return false;
|
||||
const char *v = getenv("FAKE_EVDEV_STEAM_PAD_AS_X360");
|
||||
known = v && atoi(v) && !is_steam_client() ? 1 : -1;
|
||||
}
|
||||
return known == 1;
|
||||
}
|
||||
|
||||
__attribute__((visibility("hidden"))) static bool
|
||||
presents_xbox_triggers(const FakeController &fake) {
|
||||
return fake.uinput || !is_steam_client();
|
||||
@@ -1391,6 +1413,7 @@ static std::unordered_map<int, std::shared_ptr<DeckHidraw>> &deck_map() {
|
||||
|
||||
static bool fake_deck_enabled() {
|
||||
static int enabled = -1;
|
||||
if (enabled < 0 && !env_ready()) return false;
|
||||
if (enabled < 0) enabled = getenv("FAKE_EVDEV_DECK") && atoi(getenv("FAKE_EVDEV_DECK")) ? 1 : 0;
|
||||
return enabled == 1;
|
||||
}
|
||||
@@ -1398,6 +1421,7 @@ static bool fake_deck_enabled() {
|
||||
__attribute__((visibility("hidden"))) static uint32_t session_pad_type() {
|
||||
static int type = -1;
|
||||
if (type < 0) {
|
||||
if (!env_ready()) return PAD_TYPE_DECK;
|
||||
const char *env = getenv("FAKE_EVDEV_PAD_TYPE");
|
||||
type = env && !strcmp(env, "steamcontroller") ? PAD_TYPE_STEAM
|
||||
: env && !strcmp(env, "xbox360") ? PAD_TYPE_XBOX
|
||||
@@ -1470,6 +1494,7 @@ __attribute__((visibility("hidden"))) static uint64_t monotonic_us() {
|
||||
|
||||
static bool fake_triton_enabled() {
|
||||
static int enabled = -1;
|
||||
if (enabled < 0 && !env_ready()) return false;
|
||||
if (enabled < 0)
|
||||
enabled = fake_deck_enabled() && getenv("FAKE_EVDEV_TRITON") && atoi(getenv("FAKE_EVDEV_TRITON")) ? 1 : 0;
|
||||
return enabled == 1;
|
||||
@@ -2091,6 +2116,7 @@ static_assert(sizeof(TouchRingFile) <= TOUCH_RING_SIZE, "TouchRingFile layout");
|
||||
|
||||
__attribute__((visibility("hidden"))) static TouchRingFile *touch_ring() {
|
||||
static TouchRingFile *ring = nullptr;
|
||||
if (!env_ready()) return nullptr;
|
||||
static std::once_flag once;
|
||||
std::call_once(once, [] {
|
||||
const char *path = getenv("FAKE_TOUCHCTL_RING");
|
||||
@@ -2434,6 +2460,7 @@ __attribute__((constructor)) static void start_touch_controller() {
|
||||
static constexpr long SYSFS_FS_MAGIC = 0x62656572;
|
||||
|
||||
__attribute__((visibility("hidden"))) static const char *deck_listing_dir() {
|
||||
if (!env_ready()) return nullptr;
|
||||
static const char *dir = getenv("FAKE_DECK_SYSFS_LISTING");
|
||||
return dir && *dir ? dir : nullptr;
|
||||
}
|
||||
@@ -3689,6 +3716,10 @@ EXPORT int ioctl(int fd, ioctl_request_t op, ...) {
|
||||
id.bustype = 0x03;
|
||||
if (made) {
|
||||
id = made->id;
|
||||
if (steam_pad_as_x360() && id.vendor == STEAM_VIRTUAL_VENDOR_ID && id.product == STEAM_VIRTUAL_PRODUCT_ID) {
|
||||
id.vendor = X360_VENDOR_ID;
|
||||
id.product = X360_PRODUCT_ID;
|
||||
}
|
||||
} else if (presents_steam_virtual()) {
|
||||
id.vendor = STEAM_VIRTUAL_VENDOR_ID;
|
||||
id.product = STEAM_VIRTUAL_PRODUCT_ID;
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/ioctl.h>
|
||||
#include <sys/system_properties.h>
|
||||
#include <time.h>
|
||||
#include <unistd.h>
|
||||
|
||||
@@ -25,6 +26,7 @@ struct droiddeck_dma_buf_sync_file { uint32_t flags; int32_t fd; };
|
||||
#define DROIDDECK_DMA_BUF_IOCTL_IMPORT_SYNC_FILE _IOW('b', 3, struct droiddeck_dma_buf_sync_file)
|
||||
|
||||
extern volatile int g_zero_copy;
|
||||
extern volatile int g_zero_copy_ahb;
|
||||
|
||||
struct ahb_buf {
|
||||
uint64_t id;
|
||||
@@ -340,7 +342,7 @@ static void bind_ahb(struct wl_client *c, void *data, uint32_t ver, uint32_t id)
|
||||
if (!r) { wl_client_post_no_memory(c); return; }
|
||||
wl_resource_set_implementation(r, &ahb_impl, NULL, on_client_resource_destroyed);
|
||||
wl_list_insert(&g_clients, wl_resource_get_link(r));
|
||||
if (ver >= BANNER_AHB_V1_MODE_SINCE_VERSION) banner_ahb_v1_send_mode(r, g_zero_copy ? 1u : 0u);
|
||||
if (ver >= BANNER_AHB_V1_MODE_SINCE_VERSION) banner_ahb_v1_send_mode(r, (g_zero_copy || g_zero_copy_ahb) ? 1u : 0u);
|
||||
if (last_named != c) {
|
||||
last_named = c;
|
||||
droiddeck_log("layer", "zero-copy: %s bound banner_ahb_v1 version %u (%s)", droiddeck_client_name(c), ver,
|
||||
@@ -356,13 +358,14 @@ void ahb_swapchain_set_mode(int on, int live) {
|
||||
on ? "on" : "off");
|
||||
return;
|
||||
}
|
||||
if (g_mode_sent == on) return;
|
||||
g_mode_sent = on;
|
||||
const int want = on || g_zero_copy_ahb;
|
||||
if (g_mode_sent == want) return;
|
||||
g_mode_sent = want;
|
||||
int told = 0;
|
||||
struct wl_resource *r;
|
||||
wl_resource_for_each(r, &g_clients) {
|
||||
if (wl_resource_get_version(r) >= BANNER_AHB_V1_MODE_SINCE_VERSION) {
|
||||
banner_ahb_v1_send_mode(r, (uint32_t)on);
|
||||
banner_ahb_v1_send_mode(r, (uint32_t)want);
|
||||
told++;
|
||||
}
|
||||
}
|
||||
@@ -401,5 +404,13 @@ void ahb_swapchain_init(struct wl_display *display) {
|
||||
}
|
||||
g_advertised = 1;
|
||||
droiddeck_log("layer", "zero-copy: banner_ahb_v1 version 2 advertised (games built for it present their own gralloc buffers while the switch is on)");
|
||||
// Android buffers only: programs that hand over their own gralloc buffers (bionic games, also through gamescope)
|
||||
// are asked for them and shown on the display layer; every other frame keeps the copy path.
|
||||
char prop[PROP_VALUE_MAX] = {0};
|
||||
__system_property_get("persist.droiddeck.zero_copy_ahb", prop);
|
||||
if (prop[0] == '1') {
|
||||
g_zero_copy_ahb = 1;
|
||||
droiddeck_log("layer", "zero-copy: Android buffers only (persist.droiddeck.zero_copy_ahb=1): programs that send their own gralloc buffers go on the display layer, other frames keep the copy");
|
||||
}
|
||||
ahb_swapchain_set_mode(g_zero_copy, 0);
|
||||
}
|
||||
@@ -317,6 +317,7 @@ static struct { unsigned lit, dark, failed; } g_bfi_stats;
|
||||
volatile int g_hide_shell;
|
||||
|
||||
volatile int g_zero_copy;
|
||||
volatile int g_zero_copy_ahb;
|
||||
static int g_zero_copy_paused;
|
||||
static int g_zero_copy_fx_skip_said;
|
||||
|
||||
@@ -2404,7 +2405,13 @@ static void render_scene(void) {
|
||||
rendered = vkp_render(w, h, dl.d, dl.n) == 0;
|
||||
} else if (hdr_route == 0 || hdr_route == 3) {
|
||||
const int pass_on = fx_on || framegen;
|
||||
int li = (g_zero_copy && !framegen && !bfi && !cardboard && !cursor_on) ? layer_candidate(&dl, w, h) : -1;
|
||||
int li = ((g_zero_copy || g_zero_copy_ahb) && !framegen && !bfi && !cardboard && !cursor_on) ? layer_candidate(&dl, w, h) : -1;
|
||||
if (li >= 0 && !g_zero_copy) {
|
||||
/* Android buffers only: the fullscreen frame goes on the display layer only when it is a gralloc buffer
|
||||
* its program handed over and no screen effect needs the pass; everything else keeps the copy. */
|
||||
const struct surface *cs = surface_for_image(dl.d[li].img);
|
||||
if (fx_on || !cs || !cs->dmabuf_buf || !ahb_swapchain_has_ahb(cs->dmabuf_buf)) li = -1;
|
||||
}
|
||||
int over = li >= 0 ? dl.n - 1 - li : 0;
|
||||
const int fx_blocks = (li >= 0 && fx_on && over > 0);
|
||||
if (fx_blocks) { li = -1; over = 0; }
|
||||
|
||||
@@ -149,7 +149,7 @@ internal class ProtonMenu(
|
||||
|
||||
fun refreshProtons() {
|
||||
refreshExperimental()
|
||||
protonRows = ProtonExtras.tools.map {
|
||||
protonRows = ProtonExtras.offered(activity).map {
|
||||
val all = ProtonExtras.installedAll(activity, it)
|
||||
ProtonRow(it.id, it.name, all.lastOrNull(), ProtonExtras.queued(activity, it), all, ProtonExtras.update(activity, it))
|
||||
}
|
||||
|
||||
@@ -260,7 +260,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
private var steamController: SteamControllerBle? = null
|
||||
private var onScreenControls: OnScreenControls? = null
|
||||
private var bottomInputControls: OnScreenControls? = null
|
||||
private var primaryInputLayout by mutableStateOf<com.droiddeck.launcher.input.SavedInputLayout?>(null)
|
||||
private var primaryInputLayout: com.droiddeck.launcher.input.SavedInputLayout? = null
|
||||
private var secondaryInputLayout by mutableStateOf<com.droiddeck.launcher.input.SavedInputLayout?>(null)
|
||||
private var steamTouchControls: com.droiddeck.launcher.input.SteamTouchControls? = null
|
||||
private var steamTouchAvailable by mutableStateOf(false)
|
||||
@@ -643,12 +643,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
private var suspendPolicy by mutableStateOf(SessionPrefs.SUSPEND_MANUAL)
|
||||
private var steamDownloadsInBackground by mutableStateOf(false)
|
||||
private var oscMode by mutableStateOf(SessionPrefs.OSC_AUTO)
|
||||
private var oscRearButtons by mutableStateOf(false)
|
||||
private var oscTrackpads by mutableStateOf(false)
|
||||
private var onScreenButtonsVisible by mutableStateOf(false)
|
||||
private var layoutOptions by mutableStateOf<List<com.droiddeck.launcher.input.ControlsChoice.Option>>(emptyList())
|
||||
private var layoutOptions by mutableStateOf<List<Pair<String, String>>>(emptyList())
|
||||
private var layoutChoice by mutableStateOf("")
|
||||
private var layoutHint by mutableStateOf<String?>(null)
|
||||
private var layoutEditor by mutableStateOf<Triple<String, String, String>?>(null)
|
||||
private var layoutEditorScope: String? = null
|
||||
private var layoutEditorSplit: com.droiddeck.launcher.ui.InputEditorSplit? = null
|
||||
@@ -1747,26 +1744,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
layoutGame = controlsGameName(),
|
||||
layoutOptions = layoutOptions,
|
||||
layoutChoice = layoutChoice,
|
||||
layoutHint = layoutHint,
|
||||
onLayout = ::chooseLayout,
|
||||
onDeleteLayout = ::deleteLayout,
|
||||
oscRearButtons = oscRearButtons.takeIf {
|
||||
unfoldedPanel == null && !usesSteamTouchLayout() && com.droiddeck.launcher.input.PadKit.current(this).steam &&
|
||||
primaryInputLayout?.let(com.droiddeck.launcher.input.OnScreenLayout::hasBuiltInKit) == true
|
||||
},
|
||||
oscTrackpads = oscTrackpads,
|
||||
onOscRearButtons = { shown ->
|
||||
SessionPrefs.setOscRearButtons(this, shown)
|
||||
oscRearButtons = shown
|
||||
onScreenControls?.reload()
|
||||
bottomInputControls?.reload()
|
||||
},
|
||||
onOscTrackpads = { shown ->
|
||||
SessionPrefs.setOscTrackpads(this, shown)
|
||||
oscTrackpads = shown
|
||||
onScreenControls?.reload()
|
||||
bottomInputControls?.reload()
|
||||
},
|
||||
onEditLayout = when {
|
||||
layoutChoice == com.droiddeck.launcher.input.GameControls.STEAM -> steamTouchControls?.takeIf { steamTouchAvailable && onScreenButtonsVisible && it.visibility == View.VISIBLE }?.let { view -> {
|
||||
drawerOpen = false
|
||||
@@ -2578,8 +2556,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
suspendPolicy = SessionPrefs.suspendPolicy(this, SessionState.mode)
|
||||
steamDownloadsInBackground = SessionPrefs.steamDownloadsInBackground(this)
|
||||
oscMode = sessionOscMode()
|
||||
oscRearButtons = SessionPrefs.oscRearButtons(this)
|
||||
oscTrackpads = SessionPrefs.oscTrackpads(this)
|
||||
backHold = SessionPrefs.backHold(this)
|
||||
backActionsInverted = SessionPrefs.backActionsInverted(this)
|
||||
physicalShortcuts.bindings = PhysicalShortcuts.read(this)
|
||||
@@ -3254,6 +3230,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
|
||||
private fun onSessionEnded(status: Int) {
|
||||
ended = true
|
||||
uiHandler.removeCallbacks(guardWhenRunning)
|
||||
com.droiddeck.launcher.session.KeepTopActivity.release()
|
||||
++steamVrRequestGeneration
|
||||
if (isInPictureInPictureMode) {
|
||||
runOnUiThread { finish() }
|
||||
@@ -4435,15 +4413,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
private fun refreshLayoutOptions() {
|
||||
val steam = SessionState.mode == SessionService.MODE_STEAM
|
||||
val game = controlsGameId()
|
||||
val desktop = loadingMode() == SessionService.MODE_DESKTOP
|
||||
layoutOptions = com.droiddeck.launcher.input.ControlsChoice.options(this, game, steam, controlsGameName(), desktop)
|
||||
layoutChoice = com.droiddeck.launcher.input.ControlsChoice.current(this, game, steam, desktop)
|
||||
layoutHint = if (com.droiddeck.launcher.input.ControlsChoice.steamUnavailable(this, game, steam)) getString(R.string.osc_layout_steam_unavailable) else null
|
||||
}
|
||||
|
||||
private fun deleteLayout(id: String) {
|
||||
runCatching { com.droiddeck.launcher.input.ControlsChoice.delete(this, id) }.onFailure { Log.w(TAG, "could not delete layout $id", it) }
|
||||
refreshLayoutOptions()
|
||||
layoutOptions = com.droiddeck.launcher.input.ControlsChoice.options(this, game, steam, controlsGameName())
|
||||
layoutChoice = com.droiddeck.launcher.input.ControlsChoice.current(this, game, steam, loadingMode() == SessionService.MODE_DESKTOP)
|
||||
}
|
||||
|
||||
private fun chooseLayout(id: String) {
|
||||
@@ -5748,6 +5719,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
|
||||
override fun onPictureInPictureModeChanged(inPip: Boolean, newConfig: android.content.res.Configuration) {
|
||||
super.onPictureInPictureModeChanged(inPip, newConfig)
|
||||
if (inPip) {
|
||||
uiHandler.removeCallbacks(guardWhenRunning)
|
||||
uiHandler.removeCallbacks(rearmAfterYield)
|
||||
com.droiddeck.launcher.session.KeepTopActivity.stepAside()
|
||||
}
|
||||
if (::pip.isInitialized) pip.changed(inPip)
|
||||
if (!inPip && surfaceW > 0) resizeOutputForWindow(surfaceW, surfaceH)
|
||||
applyUnfoldedControls()
|
||||
@@ -5756,7 +5732,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
}
|
||||
|
||||
override fun startActivityForResult(intent: Intent, requestCode: Int, options: Bundle?) {
|
||||
if (::pip.isInitialized && (requestCode >= 0 || intent.component?.packageName == packageName ||
|
||||
if (::pip.isInitialized && intent.component?.className != com.droiddeck.launcher.session.KeepTopActivity::class.java.name &&
|
||||
(requestCode >= 0 || intent.component?.packageName == packageName ||
|
||||
intent.action in setOf(Intent.ACTION_CHOOSER, Intent.ACTION_SEND, Intent.ACTION_OPEN_DOCUMENT,
|
||||
Intent.ACTION_GET_CONTENT, "android.settings.PICTURE_IN_PICTURE_SETTINGS"))) pip.background()
|
||||
super.startActivityForResult(intent, requestCode, options)
|
||||
@@ -5788,6 +5765,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
}
|
||||
|
||||
override fun onStop() {
|
||||
if (lightPause.stopped()) departureCleanup()
|
||||
uiHandler.removeCallbacks(guardWhenRunning)
|
||||
uiHandler.removeCallbacks(rearmAfterYield)
|
||||
com.droiddeck.launcher.session.KeepTopActivity.stepAside()
|
||||
if (runtimeRemovalBlocked) { super.onStop(); return }
|
||||
started = false
|
||||
if (::hud.isInitialized) hud.setBackgrounded(true)
|
||||
@@ -5832,6 +5813,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
|
||||
override fun onResume() {
|
||||
super.onResume()
|
||||
com.droiddeck.launcher.session.KeepTopActivity.onYield = onGuardYield
|
||||
uiHandler.removeCallbacks(lightPauseCheck)
|
||||
when (lightPause.resumed(com.droiddeck.launcher.session.KeepTopActivity.bounces)) {
|
||||
com.droiddeck.launcher.session.LightPause.Resume.LIGHT -> return
|
||||
com.droiddeck.launcher.session.LightPause.Resume.CLEANUP_FIRST -> departureCleanup()
|
||||
com.droiddeck.launcher.session.LightPause.Resume.NORMAL -> Unit
|
||||
}
|
||||
drawerGameInventoryRevision++
|
||||
com.droiddeck.launcher.input.SystemKeyCapture.attach(this, { hasWindowFocus() && !appUiOwnsPointer() && CompositorHost.isStarted }) { event ->
|
||||
com.droiddeck.launcher.input.GuestKeys.send(event) { code, down -> sendGuestKey(code, down, 8) }
|
||||
@@ -5897,8 +5885,73 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
SessionPrefs.sessionPrefs(this).registerOnSharedPreferenceChangeListener(cardboardPrefListener)
|
||||
}
|
||||
|
||||
private var memoryPressureAt = 0L
|
||||
private var focusBounce = false
|
||||
private val lightPause = com.droiddeck.launcher.session.LightPause()
|
||||
private val lightPauseCheck = Runnable { if (lightPause.timedOut()) departureCleanup() }
|
||||
private var topResumed = false
|
||||
private val guardWhenRunning = object : Runnable {
|
||||
override fun run() {
|
||||
if (!topResumed || isFinishing) return
|
||||
if (SessionState.running) guardOtherDisplays() else uiHandler.postDelayed(this, 2_000)
|
||||
}
|
||||
}
|
||||
|
||||
// A touch that removed a guard while the session kept the top spot did not move focus to that
|
||||
// display, so the guard comes back unless the user carries on there.
|
||||
private val rearmAfterYield = Runnable {
|
||||
if (topResumed && !isFinishing) {
|
||||
com.droiddeck.launcher.session.KeepTopActivity.rearm()
|
||||
guardOtherDisplays()
|
||||
}
|
||||
}
|
||||
private val onGuardYield: () -> Unit = {
|
||||
uiHandler.removeCallbacks(rearmAfterYield)
|
||||
uiHandler.postDelayed(rearmAfterYield, com.droiddeck.launcher.session.KeepTopActivity.YIELD_GRACE_MS)
|
||||
}
|
||||
|
||||
// RUNNING_LOW and RUNNING_CRITICAL are not delivered from API 34, so the guard also goes up
|
||||
// as soon as a running session is on top.
|
||||
override fun onTrimMemory(level: Int) {
|
||||
super.onTrimMemory(level)
|
||||
if (!com.droiddeck.launcher.session.TopUnderPressure.isPressure(level)) return
|
||||
memoryPressureAt = android.os.SystemClock.elapsedRealtime()
|
||||
guardOtherDisplays()
|
||||
}
|
||||
|
||||
override fun onTopResumedActivityChanged(isTopResumedActivity: Boolean) {
|
||||
super.onTopResumedActivityChanged(isTopResumedActivity)
|
||||
topResumed = isTopResumedActivity
|
||||
uiHandler.removeCallbacks(guardWhenRunning)
|
||||
uiHandler.removeCallbacks(rearmAfterYield)
|
||||
if (isTopResumedActivity) {
|
||||
com.droiddeck.launcher.session.KeepTopActivity.rearm()
|
||||
uiHandler.post(guardWhenRunning)
|
||||
}
|
||||
else if (com.droiddeck.launcher.session.TopUnderPressure.shouldReclaim(
|
||||
android.os.SystemClock.elapsedRealtime(), memoryPressureAt, SessionState.running, isFinishing)) guardOtherDisplays()
|
||||
}
|
||||
|
||||
private fun guardOtherDisplays() {
|
||||
if (!SessionState.running || isFinishing || isInPictureInPictureMode) return
|
||||
val wasResumed = lifecycle.currentState.isAtLeast(androidx.lifecycle.Lifecycle.State.RESUMED)
|
||||
val bounced = com.droiddeck.launcher.session.KeepTopActivity.guardOtherDisplays(this, display?.displayId ?: android.view.Display.DEFAULT_DISPLAY)
|
||||
if (com.droiddeck.launcher.session.KeepTopActivity.hasPendingStarts()) {
|
||||
uiHandler.removeCallbacks(guardWhenRunning)
|
||||
uiHandler.postDelayed(guardWhenRunning, com.droiddeck.launcher.session.KeepTopActivity.RETRY_MS)
|
||||
}
|
||||
if (!bounced) return
|
||||
if (!wasResumed) return
|
||||
focusBounce = true
|
||||
uiHandler.postDelayed({ focusBounce = false }, 500)
|
||||
}
|
||||
|
||||
override fun onPause() {
|
||||
departureCleanup()
|
||||
if (focusBounce) {
|
||||
focusBounce = false
|
||||
lightPause.paused(com.droiddeck.launcher.session.KeepTopActivity.bounces)
|
||||
uiHandler.postDelayed(lightPauseCheck, 200)
|
||||
} else departureCleanup()
|
||||
super.onPause()
|
||||
}
|
||||
|
||||
@@ -6561,6 +6614,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
uiHandler.removeCallbacks(guardWhenRunning)
|
||||
uiHandler.removeCallbacks(rearmAfterYield)
|
||||
if (com.droiddeck.launcher.session.KeepTopActivity.onYield === onGuardYield) com.droiddeck.launcher.session.KeepTopActivity.onYield = null
|
||||
com.droiddeck.launcher.session.KeepTopActivity.release()
|
||||
synchronized(frameGenGlobalLock) {
|
||||
frameGenActivityActive = false
|
||||
frameGenRequests.incrementAndGet()
|
||||
|
||||
@@ -24,84 +24,14 @@ object ControlsChoice {
|
||||
return if (chosen == null) library else library.selectPart(desktop, InputRole.PRIMARY, chosen)
|
||||
}
|
||||
|
||||
data class Option(val id: String, val name: String, val detail: String? = null, val deletable: Boolean = false)
|
||||
|
||||
/** Layouts made for one game, so they're listed only for that game. Layouts made before that was recorded are recognised by carrying the name of the game that draws them. */
|
||||
private fun owners(context: Context, library: InputLibrary): Map<String, Set<Long>> {
|
||||
val named = GameControls.games(context).mapNotNull { game ->
|
||||
val layout = own(library, GameControls.bindings(context, game))?.let { library.preset(it).layoutId } ?: return@mapNotNull null
|
||||
val name = GameControls.name(context, game) ?: return@mapNotNull null
|
||||
(layout to game).takeIf { library.layouts.any { it.id == layout && it.name == name } }
|
||||
}
|
||||
return (named + GameControls.madeFor(context).toList()).groupBy({ it.first }, { it.second }).mapValues { it.value.toSet() }
|
||||
}
|
||||
|
||||
private fun defaults(library: InputLibrary) =
|
||||
listOf(false, true).mapNotNull { library.activeLayout(it, InputRole.PRIMARY)?.id }.toSet()
|
||||
|
||||
private fun deletable(context: Context, library: InputLibrary, layout: SavedInputLayout): Boolean {
|
||||
if (!layout.editable || layout.id == InputLibraries.OVERLAY || layout.id in defaults(library)) return false
|
||||
if (GameControls.games(context).any { game -> own(library, GameControls.bindings(context, game))?.let { library.preset(it).layoutId } == layout.id }) return false
|
||||
return library.profiles.none { p -> p.parts.any { (role, part) -> part.layout == layout.id && drawn(library, p.id, role) } } &&
|
||||
library.bindings.none { it.layoutId == layout.id && library.selectedBindings(it.id) }
|
||||
}
|
||||
|
||||
/** Whether [profile]'s [role] part is what a mode shows, rather than one a choice made since covers. */
|
||||
private fun drawn(library: InputLibrary, profile: String, role: InputRole) =
|
||||
listOf(false, true).any { desktop -> library.activeId(desktop) == profile && library.selection(desktop).parts[role] == null }
|
||||
|
||||
private fun keeps(library: InputLibrary, profile: String) =
|
||||
profile == InputProfile.GAME || profile == InputProfile.DESKTOP || listOf(false, true).any { library.activeId(it) == profile }
|
||||
|
||||
fun options(context: Context, game: Long?, steamMode: Boolean, gameName: String? = null, desktop: Boolean = false): List<Option> {
|
||||
fun options(context: Context, game: Long?, steamMode: Boolean, gameName: String? = null): List<Pair<String, String>> {
|
||||
val library = InputLibraries.read(context)
|
||||
val own = game != null && game in GameControls.games(context)
|
||||
val current = current(context, game, steamMode, desktop)
|
||||
val owners = owners(context, library)
|
||||
val defaults = defaults(library)
|
||||
val forGame = gameName?.takeIf { game != null && it.isNotBlank() }
|
||||
val saved = library.layouts.filter { it.editable && it.supports(InputRole.PRIMARY) && it.id != InputLibraries.OVERLAY }
|
||||
.filter { l -> l.id == current || l.id in defaults || owners[l.id].isNullOrEmpty() || game in owners[l.id].orEmpty() }
|
||||
.map { l ->
|
||||
val mine = game != null && game in owners[l.id].orEmpty() && l.id !in defaults
|
||||
Option(l.id, l.name, if (mine && forGame != null) context.getString(R.string.osc_layout_detail_game, forGame) else null,
|
||||
l.id != current && deletable(context, library, l))
|
||||
}
|
||||
return (if (own) listOf(Option(DEFAULT, context.getString(R.string.osc_default))) else emptyList()) +
|
||||
Option(InputLibraries.OVERLAY, context.getString(R.string.osc_layout_gamepad), context.getString(R.string.osc_layout_gamepad_detail)) +
|
||||
(if (steamMode) listOf(Option(GameControls.STEAM, context.getString(R.string.osc_layout_steam), context.getString(R.string.osc_layout_steam_detail))) else emptyList()) +
|
||||
saved +
|
||||
(if (forGame != null) listOf(Option(NEW, context.getString(R.string.osc_layout_new_for, forGame))) else emptyList())
|
||||
}
|
||||
|
||||
/** Whether [game] chose Steam's touch controls but runs where they can't be shown. */
|
||||
fun steamUnavailable(context: Context, game: Long?, steamMode: Boolean) = !steamMode && GameControls.steamLayout(context, game)
|
||||
|
||||
/** Deletes the saved layout [id] and its actions. A profile that can no longer be chosen goes with it; one that can falls back to the stock layout. */
|
||||
fun delete(context: Context, id: String) {
|
||||
val games = GameControls.games(context).mapNotNull { GameControls.bindings(context, it) }.toSet()
|
||||
InputLibraries.update(context) { library ->
|
||||
val layout = library.layouts.first { it.id == id }
|
||||
require(deletable(context, library, layout))
|
||||
val users = library.usersOfLayout(id)
|
||||
val orphans = users.filterNot { keeps(library, it.id) }
|
||||
var result = users.filter { keeps(library, it.id) }.fold(library) { acc, p ->
|
||||
p.parts.filterValues { it.layout == id }.keys.fold(acc) { lib, role ->
|
||||
lib.chooseLayout(p.id, role, when {
|
||||
role == InputRole.PRIMARY -> InputLibraries.OVERLAY
|
||||
p.base == InputProfile.DESKTOP -> InputLibraries.TRACKPAD
|
||||
else -> InputLibraries.DECK
|
||||
})
|
||||
}
|
||||
}
|
||||
result = orphans.fold(result) { acc, p -> acc.removeProfile(p.id) }
|
||||
val loose = orphans.flatMap { p -> p.parts.values.map { it.bindings } }.toSet()
|
||||
.filter { b -> b !in games && result.usersOfBindings(b).isEmpty() && !result.selectedBindings(b) && result.bindings.any { it.id == b } }
|
||||
.filterNot { b -> InputStockLayouts.presets(InputStockLayouts.layouts()).any { it.id == b } }
|
||||
result = loose.fold(result) { acc, b -> acc.removeBindings(b) }
|
||||
result.removeLayout(id)
|
||||
}
|
||||
GameControls.forgetLayout(context, id)
|
||||
return (if (own) listOf(DEFAULT to context.getString(R.string.osc_default)) else emptyList()) +
|
||||
listOf(InputLibraries.OVERLAY to context.getString(R.string.osc_layout_gamepad)) +
|
||||
(if (steamMode) listOf(GameControls.STEAM to context.getString(R.string.osc_layout_steam)) else emptyList()) +
|
||||
library.layouts.filter { it.editable && it.supports(InputRole.PRIMARY) && it.id != InputLibraries.OVERLAY }.map { it.id to it.name } +
|
||||
(if (game != null && !gameName.isNullOrBlank()) listOf(NEW to context.getString(R.string.osc_layout_new_for, gameName)) else emptyList())
|
||||
}
|
||||
|
||||
fun current(context: Context, game: Long?, steamMode: Boolean, desktop: Boolean = false): String =
|
||||
@@ -131,7 +61,6 @@ object ControlsChoice {
|
||||
val layoutId = newInputId()
|
||||
val bindingsId = newInputId()
|
||||
InputLibraries.update(context) { latest -> copyForGame(context, latest, game, name, desktop, layoutId, bindingsId) }
|
||||
GameControls.markMadeFor(context, layoutId, game)
|
||||
GameControls.choose(context, game, bindingsId, steam = false, name = name)
|
||||
return layoutId to bindingsId
|
||||
}
|
||||
@@ -151,10 +80,7 @@ object ControlsChoice {
|
||||
}
|
||||
|
||||
/** Uses [bindingsId], made by [copyForGame], for [game] only. */
|
||||
fun useForGame(context: Context, game: Long, name: String, bindingsId: String) {
|
||||
InputLibraries.read(context).bindings.firstOrNull { it.id == bindingsId }?.layoutId?.let { GameControls.markMadeFor(context, it, game) }
|
||||
GameControls.choose(context, game, bindingsId, steam = false, name = name)
|
||||
}
|
||||
fun useForGame(context: Context, game: Long, name: String, bindingsId: String) = GameControls.choose(context, game, bindingsId, steam = false, name = name)
|
||||
|
||||
/** The profile, layout and actions the editor opens for [game], or null when its layout can't be edited here. */
|
||||
fun editTarget(context: Context, game: Long?, desktop: Boolean): Triple<String, String, String>? {
|
||||
|
||||
@@ -6,7 +6,6 @@ import com.droiddeck.launcher.session.SessionPrefs
|
||||
/** Which on-screen layout each game uses. Games without a choice use the default profile's main-screen layout. */
|
||||
object GameControls {
|
||||
const val STEAM = "steam"
|
||||
private const val MADE_FOR = "layout-for."
|
||||
|
||||
private fun prefs(context: Context) = context.getSharedPreferences("game-controls", Context.MODE_PRIVATE)
|
||||
|
||||
@@ -29,15 +28,6 @@ object GameControls {
|
||||
.filter { it.endsWith(".steam") || it.endsWith(".bindings") }
|
||||
.mapNotNull { it.substringBeforeLast('.').toLongOrNull() }.distinct().sorted()
|
||||
|
||||
/** Layouts made for one game, by layout id. */
|
||||
fun madeFor(context: Context): Map<String, Long> = prefs(context).all.mapNotNull { (key, value) ->
|
||||
if (key.startsWith(MADE_FOR) && value is Long) key.removePrefix(MADE_FOR) to value else null
|
||||
}.toMap()
|
||||
|
||||
fun markMadeFor(context: Context, layout: String, game: Long) { prefs(context).edit().putLong(MADE_FOR + layout, game).apply() }
|
||||
|
||||
fun forgetLayout(context: Context, layout: String) { prefs(context).edit().remove(MADE_FOR + layout).apply() }
|
||||
|
||||
fun name(context: Context, game: Long): String? = prefs(context).getString("$game.name", null)
|
||||
|
||||
fun clear(context: Context, game: Long) {
|
||||
|
||||
@@ -2,7 +2,6 @@ package com.droiddeck.launcher.input
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.Rect
|
||||
import android.graphics.RectF
|
||||
import kotlin.math.max
|
||||
import kotlin.math.min
|
||||
|
||||
@@ -19,12 +18,6 @@ object KitLayout {
|
||||
/** Whether [id] names one of a kit's own controls rather than a key or control the player added. */
|
||||
fun isKit(id: String) = id.startsWith("legacy:") || id == DPAD_ID || id == KEYBOARD_ID
|
||||
|
||||
internal fun visibleOnOverlay(control: InputControl, rearButtons: Boolean, trackpads: Boolean): Boolean = when (control) {
|
||||
InputControl.L4, InputControl.L5, InputControl.R4, InputControl.R5 -> rearButtons
|
||||
InputControl.LEFT_PAD, InputControl.RIGHT_PAD -> trackpads
|
||||
else -> true
|
||||
}
|
||||
|
||||
/** The control a kit id stands for in a layout that keeps no kit positions, so bindings saved for it stay valid. */
|
||||
fun element(id: String): InputSurfaceElement? = when {
|
||||
id == DPAD_ID -> InputSurfaceElement(InputControl.LS, 0f, 0f, .1f, .1f, id, InputElementKind.DPAD)
|
||||
@@ -79,24 +72,22 @@ object KitLayout {
|
||||
dpad(220f, 345f, 150f)) + face(1375f, 345f, 58f, 96f) + listOf(
|
||||
Spec(InputControl.LS, 290f, 640f, 96f), Spec(InputControl.RS, 1310f, 640f, 96f),
|
||||
Spec(InputControl.LEFT_PAD, 470f, 360f, 88f, shape = InputButtonShape.ROUNDED), Spec(InputControl.RIGHT_PAD, 1130f, 360f, 88f, shape = InputButtonShape.ROUNDED),
|
||||
Spec(InputControl.SELECT, 660f, 850f, 46f, 26f, shape = InputButtonShape.PILL), Spec(InputControl.START, 940f, 850f, 46f, 26f, shape = InputButtonShape.PILL),
|
||||
Spec(InputControl.SELECT, 660f, 150f, 46f, 26f, shape = InputButtonShape.PILL), Spec(InputControl.START, 940f, 150f, 46f, 26f, shape = InputButtonShape.PILL),
|
||||
Spec(InputControl.GUIDE, 370f, 852f, 66f, 30f, shape = InputButtonShape.PILL), Spec(InputControl.QAM, 1230f, 852f, 66f, 30f, shape = InputButtonShape.PILL),
|
||||
keyboard(136f))
|
||||
kit.playStation -> shoulders() + listOf(dpad(250f, 395f, 125f)) + face(1350f, 395f, 58f, 96f) + listOf(
|
||||
Spec(InputControl.LS, 565f, 690f, 100f), Spec(InputControl.RS, 1035f, 690f, 100f),
|
||||
Spec(InputControl.L3, 430f, 590f, 42f, ax = 565f, ay = 690f), Spec(InputControl.R3, 1170f, 590f, 42f, ax = 1035f, ay = 690f),
|
||||
Spec(InputControl.SELECT, 640f, 850f, 50f, 30f, shape = InputButtonShape.PILL), Spec(InputControl.START, 960f, 850f, 50f, 30f, shape = InputButtonShape.PILL),
|
||||
Spec(InputControl.SELECT, 640f, 150f, 50f, 30f, shape = InputButtonShape.PILL), Spec(InputControl.START, 960f, 150f, 50f, 30f, shape = InputButtonShape.PILL),
|
||||
Spec(InputControl.GUIDE, 800f, 250f, 46f), Spec(InputControl.QAM, 220f, 848f, 46f), keyboard(136f))
|
||||
else -> shoulders() + listOf(Spec(InputControl.LS, 235f, 400f, 104f), dpad(470f, 675f, 118f)) + face(1375f, 400f, 58f, 94f) + listOf(
|
||||
Spec(InputControl.RS, 1130f, 690f, 104f), Spec(InputControl.L3, 385f, 290f, 42f, ax = 235f, ay = 400f), Spec(InputControl.R3, 1290f, 790f, 42f, ax = 1130f, ay = 690f),
|
||||
Spec(InputControl.SELECT, 690f, 850f, 38f), Spec(InputControl.GUIDE, 800f, 162f, 54f), Spec(InputControl.START, 910f, 850f, 38f),
|
||||
Spec(InputControl.SELECT, 690f, 162f, 38f), Spec(InputControl.GUIDE, 800f, 162f, 54f), Spec(InputControl.START, 910f, 162f, 38f),
|
||||
Spec(InputControl.QAM, 220f, 848f, 46f), keyboard(136f))
|
||||
}
|
||||
|
||||
/** The default controls for [kit] on a [width] × [height] screen. */
|
||||
fun elements(context: Context, kit: PadKit, width: Int, height: Int, inset: Rect = Rect(), scale: Float = 1f,
|
||||
cutouts: List<Rect> = emptyList(), rearButtons: Boolean = true, trackpads: Boolean = true,
|
||||
addedControls: List<InputSurfaceElement> = emptyList()): List<InputSurfaceElement> {
|
||||
fun elements(context: Context, kit: PadKit, width: Int, height: Int, inset: Rect = Rect(), scale: Float = 1f): List<InputSurfaceElement> {
|
||||
if (width <= 0 || height <= 0) return emptyList()
|
||||
// Insets stay as reported unless what's left is too small to keep every control above the minimum element size.
|
||||
val smallestUnit = InputSurfaceElement.MIN_SIZE * max(width, height) / (2 * SMALLEST_HALF)
|
||||
@@ -109,29 +100,6 @@ object KitLayout {
|
||||
val (top, bottom) = fit(inset.top, inset.bottom, height, REF_H)
|
||||
val safe = Rect(left, top, right, bottom)
|
||||
if (height > width) return portrait(context, kit, width, height, safe, scale)
|
||||
.filter { visibleOnOverlay(it.control, rearButtons, trackpads) }
|
||||
val controls = specs(kit).filter { visibleOnOverlay(it.control, rearButtons, trackpads) }
|
||||
val leftCutouts = cutouts.filter { inset.left > 0 && it.right <= inset.left }
|
||||
val rightCutouts = cutouts.filter { inset.right > 0 && it.left >= width - inset.right }
|
||||
if ((leftCutouts.isNotEmpty() || rightCutouts.isNotEmpty()) &&
|
||||
(left == 0 || leftCutouts.isNotEmpty()) && (right == 0 || rightCutouts.isNotEmpty())) {
|
||||
val corner = cornerInset(safe, cutouts, height, context.resources.displayMetrics.density)
|
||||
val fullWidth = landscape(context, kit, width, height, Rect(0, top, 0, bottom), scale, corner, controls)
|
||||
avoidSideCutouts(fullWidth, leftCutouts, rightCutouts, width, height, addedControls)?.let { return it }
|
||||
}
|
||||
return landscape(context, kit, width, height, safe, scale, left, controls)
|
||||
}
|
||||
|
||||
internal fun cornerInset(inset: Rect, cutouts: List<Rect>, height: Int, density: Float): Int {
|
||||
val leftCutouts = cutouts.filter { inset.left > 0 && it.right <= inset.left }
|
||||
val floor = height - inset.bottom
|
||||
return if (height <= 0 || leftCutouts.isEmpty() ||
|
||||
leftCutouts.any { it.top < floor && it.bottom > floor - CORNER_DP * density && it.left < CORNER_DP * density })
|
||||
inset.left else 0
|
||||
}
|
||||
|
||||
private fun landscape(context: Context, kit: PadKit, width: Int, height: Int, safe: Rect, scale: Float,
|
||||
cornerInset: Int, controls: List<Spec>): List<InputSurfaceElement> {
|
||||
val w = width.toFloat(); val h = height.toFloat()
|
||||
val unit = (min(w / REF_W, h / REF_H) * cap(context, min(width, height)) * scale).coerceAtMost(min((w - safe.left - safe.right).coerceAtLeast(1f) / MIN_SPAN, (h - safe.top - safe.bottom).coerceAtLeast(1f) / REF_H))
|
||||
fun x(ref: Float) = when {
|
||||
@@ -145,66 +113,22 @@ object KitLayout {
|
||||
else -> (h / 2f + (ref - REF_H / 2f) * unit).between(safe.top + ref * unit, h - safe.bottom - (REF_H - ref) * unit)
|
||||
}
|
||||
val density = context.resources.displayMetrics.density
|
||||
var edge = cornerInset + CORNER_DP * density
|
||||
val row = controls.filter { it.cy > REF_H * .88f && it.cx < REF_W / 3f }.sortedBy { it.cx }.associateWith { s ->
|
||||
var edge = safe.left + CORNER_DP * density
|
||||
val specs = specs(kit)
|
||||
val row = specs.filter { it.cy > REF_H * .88f && it.cx < REF_W / 3f }.sortedBy { it.cx }.associateWith { s ->
|
||||
val hw = s.hw * unit
|
||||
max(x(s.cx), edge + hw).also { edge = it + hw + GAP_DP * density }
|
||||
}
|
||||
return controls.map { s ->
|
||||
val cx = when (s.control) {
|
||||
InputControl.START, InputControl.SELECT -> (w + safe.left - safe.right) / 2f + (s.cx - REF_W / 2f) * unit
|
||||
else -> row[s] ?: (x(s.ax) + (s.cx - s.ax) * unit)
|
||||
}
|
||||
val cy = y(s.ay) + (s.cy - s.ay) * unit; val hw = s.hw * unit; val hh = s.hh * unit
|
||||
return specs.map { s ->
|
||||
val cx = row[s] ?: (x(s.ax) + (s.cx - s.ax) * unit); val cy = y(s.ay) + (s.cy - s.ay) * unit; val hw = s.hw * unit; val hh = s.hh * unit
|
||||
InputSurfaceElement(s.control, (cx - hw) / w, (cy - hh) / h, 2 * hw / w, 2 * hh / h, s.id, s.kind, if (s.name == s.control.label) kit.name(s.control) else s.name,
|
||||
floating = s.kind == InputElementKind.STICK, buttonShape = s.shape, icon = s.icon).bounded()
|
||||
}
|
||||
}
|
||||
|
||||
private fun avoidSideCutouts(elements: List<InputSurfaceElement>, leftCutouts: List<Rect>, rightCutouts: List<Rect>,
|
||||
width: Int, height: Int, addedControls: List<InputSurfaceElement>): List<InputSurfaceElement>? {
|
||||
fun bounds(e: InputSurfaceElement) = RectF(e.x * width, e.y * height, (e.x + e.width) * width, (e.y + e.height) * height)
|
||||
val boxes = elements.map(::bounds)
|
||||
val addedBoxes = addedControls.map(::bounds)
|
||||
// Move a face-button cross or a stick and its click button together.
|
||||
val groups = elements.indices.groupBy { index ->
|
||||
val element = elements[index]
|
||||
when (element.control) {
|
||||
InputControl.A, InputControl.B, InputControl.X, InputControl.Y -> if (element.id == KEYBOARD_ID) element.id else "face"
|
||||
InputControl.L3 -> "legacy:ls"
|
||||
InputControl.R3 -> "legacy:rs"
|
||||
else -> element.id
|
||||
}
|
||||
}.values
|
||||
val shifts = FloatArray(elements.size)
|
||||
val left = leftCutouts.map(::RectF)
|
||||
val right = rightCutouts.map(::RectF)
|
||||
val obstacles = left + right
|
||||
for (group in groups) {
|
||||
val leftEdge = left.filter { cutout -> group.any { RectF.intersects(boxes[it], cutout) } }.maxOfOrNull { it.right }
|
||||
val rightEdge = right.filter { cutout -> group.any { RectF.intersects(boxes[it], cutout) } }.minOfOrNull { it.left }
|
||||
val shift = when {
|
||||
leftEdge != null && rightEdge != null -> return null
|
||||
leftEdge != null -> leftEdge - group.minOf { boxes[it].left } + 1f
|
||||
rightEdge != null -> rightEdge - group.maxOf { boxes[it].right } - 1f
|
||||
else -> continue
|
||||
}
|
||||
for (index in group) shifts[index] = shift
|
||||
}
|
||||
val moved = boxes.mapIndexed { index, box -> RectF(box).apply { offset(shifts[index], 0f) } }
|
||||
for (i in moved.indices) {
|
||||
if (moved[i].left < 0f || moved[i].right > width || obstacles.any { RectF.intersects(moved[i], it) }) return null
|
||||
if (shifts[i] != 0f && addedBoxes.any { RectF.intersects(moved[i], it) }) return null
|
||||
for (j in 0 until i) {
|
||||
if (shifts[i] != shifts[j] && RectF.intersects(moved[i], moved[j]) && !RectF.intersects(boxes[i], boxes[j])) return null
|
||||
}
|
||||
}
|
||||
return elements.mapIndexed { index, e -> e.copy(x = e.x + shifts[index] / width).bounded() }
|
||||
}
|
||||
|
||||
/**
|
||||
* A portrait surface gets the same pad as the panel under the game, in the lower part of the screen, with the keyboard,
|
||||
* Steam, Quick Access, Start, Select and stick-click buttons in a row along the bottom edge.
|
||||
* Steam, Quick Access and stick-click buttons in a row along the bottom edge that starts after DroidDeck's corner button.
|
||||
*/
|
||||
private fun portrait(context: Context, kit: PadKit, width: Int, height: Int, safe: Rect, scale: Float): List<InputSurfaceElement> {
|
||||
val w = width.toFloat(); val h = height.toFloat()
|
||||
@@ -213,16 +137,15 @@ object KitLayout {
|
||||
val inner = (w - safe.left - safe.right).coerceAtLeast(1f)
|
||||
val area = (min(h * .6f, inner * 1.15f) * scale).coerceAtMost(h - safe.top - safe.bottom - row).coerceAtLeast(1f)
|
||||
val top = h - safe.bottom - row - area
|
||||
val pad = dock(context, kit, inner.toInt(), area.toInt(), true, InputControl.LS, InputControl.RS, upright = true)
|
||||
.filterNot { it.control == InputControl.SELECT || it.control == InputControl.START }.map { e ->
|
||||
val pad = dock(context, kit, inner.toInt(), area.toInt(), true, InputControl.LS, InputControl.RS, upright = true).map { e ->
|
||||
e.copy(x = (safe.left + e.x * inner) / w, y = (top + e.y * area) / h, width = e.width * inner / w, height = e.height * area / h,
|
||||
floating = e.kind == InputElementKind.STICK)
|
||||
}
|
||||
val specs = specs(kit)
|
||||
fun spec(control: InputControl, id: String = "legacy:${control.id}") = specs.firstOrNull { it.control == control && it.id == id }
|
||||
val gap = GAP_DP * density
|
||||
val leftRow = listOfNotNull(spec(InputControl.A, KEYBOARD_ID), spec(InputControl.GUIDE).takeIf { kit.steam }, spec(InputControl.L3), spec(InputControl.SELECT))
|
||||
val rightRow = listOfNotNull(spec(InputControl.QAM), spec(InputControl.GUIDE).takeIf { !kit.steam }, spec(InputControl.R3), spec(InputControl.START))
|
||||
val leftRow = listOfNotNull(spec(InputControl.A, KEYBOARD_ID), spec(InputControl.GUIDE).takeIf { kit.steam }, spec(InputControl.L3))
|
||||
val rightRow = listOfNotNull(spec(InputControl.QAM), spec(InputControl.GUIDE).takeIf { !kit.steam }, spec(InputControl.R3))
|
||||
val start = safe.left + CORNER_DP * density
|
||||
val span = (w - safe.right - gap - start - gap * (leftRow.size + rightRow.size - 1)).coerceAtLeast(1f)
|
||||
val size = min(BUTTON_DP * density, span / (leftRow + rightRow).sumOf { (it.hw / it.hh).toDouble() }.toFloat())
|
||||
|
||||
@@ -15,7 +15,6 @@ import android.view.View
|
||||
import android.view.ViewConfiguration
|
||||
import android.view.WindowInsets
|
||||
import android.widget.FrameLayout
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import com.droiddeck.launcher.ui.InputSurfaceView
|
||||
import com.droiddeck.launcher.ui.PadArt
|
||||
|
||||
@@ -26,7 +25,6 @@ class OnScreenControls(context: Context, pad: PadBridge?, val dock: OnScreenLayo
|
||||
private val surface = InputSurfaceView(context, pad, inputRole = InputRole.PRIMARY, haptics = dock != null)
|
||||
private var layout: SavedInputLayout? = null
|
||||
private val safe = Rect()
|
||||
private var cutouts = emptyList<Rect>()
|
||||
private var viewWidth = 0
|
||||
private var viewHeight = 0
|
||||
private val corner = CornerButton(context)
|
||||
@@ -64,22 +62,11 @@ class OnScreenControls(context: Context, pad: PadBridge?, val dock: OnScreenLayo
|
||||
}
|
||||
|
||||
private fun render() {
|
||||
val placed = OnScreenLayout.elements(context, layout, viewWidth, viewHeight, safe, dock, cutouts,
|
||||
rearButtons = SessionPrefs.oscRearButtons(context), trackpads = SessionPrefs.oscTrackpads(context))
|
||||
val placed = OnScreenLayout.elements(context, layout, viewWidth, viewHeight, safe, dock)
|
||||
surface.updateCustomLayout(if (hidden != null) placed.filter { it.alwaysShown } else placed)
|
||||
surface.updateStyle(layout?.style ?: InputSurfaceStyle())
|
||||
corner.visibility = if (layout == null || dock != null) GONE else VISIBLE
|
||||
corner.alpha = (layout?.style?.opacity ?: 100) / 100f
|
||||
val density = resources.displayMetrics.density
|
||||
val margin = (CORNER_MARGIN_DP * density).toInt()
|
||||
val params = corner.layoutParams as LayoutParams
|
||||
val leftInset = if (dock == null && viewWidth >= viewHeight && layout?.let(OnScreenLayout::generated) == true)
|
||||
KitLayout.cornerInset(safe, cutouts, viewHeight, density) else safe.left
|
||||
if (params.leftMargin != leftInset + margin || params.bottomMargin != safe.bottom + margin) {
|
||||
params.leftMargin = leftInset + margin
|
||||
params.bottomMargin = safe.bottom + margin
|
||||
corner.layoutParams = params
|
||||
}
|
||||
corner.invalidate()
|
||||
}
|
||||
|
||||
@@ -104,11 +91,18 @@ class OnScreenControls(context: Context, pad: PadBridge?, val dock: OnScreenLayo
|
||||
|
||||
override fun onApplyWindowInsets(insets: WindowInsets): WindowInsets {
|
||||
val cutout = if (Build.VERSION.SDK_INT >= 28) insets.displayCutout else null
|
||||
val margin = (CORNER_MARGIN_DP * resources.displayMetrics.density).toInt()
|
||||
val params = corner.layoutParams as LayoutParams
|
||||
val left = (cutout?.safeInsetLeft ?: 0) + margin
|
||||
val bottom = (cutout?.safeInsetBottom ?: 0) + margin
|
||||
if (params.leftMargin != left || params.bottomMargin != bottom) {
|
||||
params.leftMargin = left
|
||||
params.bottomMargin = bottom
|
||||
corner.layoutParams = params
|
||||
}
|
||||
val fresh = Rect(cutout?.safeInsetLeft ?: 0, if (dock == null) cutout?.safeInsetTop ?: 0 else 0, cutout?.safeInsetRight ?: 0, cutout?.safeInsetBottom ?: 0)
|
||||
val bounds = cutout?.boundingRects.orEmpty()
|
||||
if (fresh != safe || bounds != cutouts) {
|
||||
if (fresh != safe) {
|
||||
safe.set(fresh)
|
||||
cutouts = bounds
|
||||
render()
|
||||
}
|
||||
return super.onApplyWindowInsets(insets)
|
||||
|
||||
@@ -23,25 +23,19 @@ object OnScreenLayout {
|
||||
* The built-in gamepad keeps no kit positions until its kit is edited; until then the kit follows the virtual controller and
|
||||
* the layout stores only the keys and controls the player added on top.
|
||||
*/
|
||||
fun generated(layout: SavedInputLayout) = hasBuiltInKit(layout) && layout.elements.none { KitLayout.isKit(it.id) }
|
||||
fun generated(layout: SavedInputLayout) = (layout.id == InputLibraries.OVERLAY || layout.origin == InputLibraries.OVERLAY) &&
|
||||
!layout.kitless && layout.elements.none { KitLayout.isKit(it.id) }
|
||||
|
||||
fun hasBuiltInKit(layout: SavedInputLayout) =
|
||||
!layout.kitless && (layout.id == InputLibraries.OVERLAY || layout.origin == InputLibraries.OVERLAY)
|
||||
|
||||
fun elements(context: Context, layout: SavedInputLayout?, width: Int, height: Int, safe: Rect, dock: Dock? = null,
|
||||
cutouts: List<Rect> = emptyList(), rearButtons: Boolean = true, trackpads: Boolean = true): List<InputSurfaceElement> {
|
||||
fun elements(context: Context, layout: SavedInputLayout?, width: Int, height: Int, safe: Rect, dock: Dock? = null): List<InputSurfaceElement> {
|
||||
layout ?: return emptyList()
|
||||
if (width <= 0 || height <= 0) return layout.elements
|
||||
if (generated(layout)) {
|
||||
val kit = PadKit.current(context)
|
||||
val extras = if (layout.elements.isEmpty()) emptyList() else fit(layout.elements, aspect(context, layout), 1f, width, height, safe)
|
||||
return (if (dock != null) KitLayout.dock(context, kit, width, height, dock.portrait, dock.left, dock.right)
|
||||
else KitLayout.elements(context, kit, width, height, safe, layout.scale, cutouts, rearButtons, trackpads, addedControls = extras)) + extras
|
||||
else KitLayout.elements(context, kit, width, height, safe, layout.scale)) + extras
|
||||
}
|
||||
val elements = if (dock == null && hasBuiltInKit(layout)) layout.elements.filter { element ->
|
||||
!KitLayout.isKit(element.id) || KitLayout.visibleOnOverlay(element.control, rearButtons, trackpads)
|
||||
} else layout.elements
|
||||
return fit(elements, aspect(context, layout), 1f, width, height, safe)
|
||||
return fit(layout.elements, aspect(context, layout), 1f, width, height, safe)
|
||||
}
|
||||
|
||||
fun editorElements(context: Context, layout: SavedInputLayout, width: Int, height: Int, edited: Boolean = false): List<InputSurfaceElement> =
|
||||
|
||||
@@ -88,8 +88,8 @@ object ComponentUpdater {
|
||||
logLines(context).mapNotNull { STAMP.find(it)?.groupValues?.get(1) }.maxOrNull() ?: "0"
|
||||
|
||||
private fun lineOf(context: Context, state: JSONObject, p: ComponentsManager.Proton, comp: String): ComponentUpdates.Line? {
|
||||
if (!ComponentUpdates.follows(p) || !ComponentsManager.supports(p, comp)) return null
|
||||
if (comp == "fex") return ComponentUpdates.line("fex", false)
|
||||
if (!ComponentUpdates.autoFollows(p, comp) || !ComponentsManager.supports(p, comp)) return null
|
||||
if (comp == "fex") return ComponentUpdates.fexLine(p)
|
||||
val key = "${p.id}|${p.version}"
|
||||
val flavors = state.obj("flavors").obj(key)
|
||||
val arm64ec = if (flavors.has(comp)) flavors.optBoolean(comp) else ComponentsManager.arm64ec(context, p, comp)?.also { flavors.put(comp, it) }
|
||||
|
||||
@@ -13,7 +13,7 @@ object ComponentUpdates {
|
||||
const val BOOTED_SECONDS = 60L
|
||||
const val FAILED_BOOTS_BEFORE_ROLLBACK = 2
|
||||
|
||||
data class Line(val key: String, val comp: String, val prefix: String)
|
||||
data class Line(val key: String, val comp: String, val prefix: String, val release: String = ComponentsManager.DD_NIGHTLY)
|
||||
|
||||
val LINES = listOf(
|
||||
Line("dxvk", "dxvk", "DD-dxvk-"),
|
||||
@@ -21,12 +21,19 @@ object ComponentUpdates {
|
||||
Line("vkd3d", "vkd3d", "DD-vkd3d-proton-"),
|
||||
Line("vkd3d-arm64ec", "vkd3d", "DD-vkd3d-proton-arm64ec-"),
|
||||
Line("fex", "fex", "DD-FEXCore-"),
|
||||
Line("fex-bionic", "fex", "FEXCore-", ComponentsManager.DD_BIONIC),
|
||||
)
|
||||
|
||||
private val OWN_PREFIX = ProtonExtras.tools.first { it.id == ProtonExtras.OWN }.prefix
|
||||
|
||||
fun follows(p: ComponentsManager.Proton): Boolean = !p.valve && p.dir.name.startsWith(OWN_PREFIX)
|
||||
|
||||
fun autoFollows(p: ComponentsManager.Proton, comp: String): Boolean =
|
||||
follows(p) || (comp == "fex" && !p.valve && ComponentsManager.bionicTool(p.dir.name))
|
||||
|
||||
fun fexLine(p: ComponentsManager.Proton): Line =
|
||||
if (ComponentsManager.bionicTool(p.dir.name)) LINES.first { it.release == ComponentsManager.DD_BIONIC } else line("fex", false)
|
||||
|
||||
fun ownId(protonId: String): Boolean = protonId.startsWith(ComponentsManager.safeName(OWN_PREFIX))
|
||||
|
||||
fun strays(
|
||||
@@ -34,8 +41,8 @@ object ComponentUpdates {
|
||||
choices: Map<String, Map<String, ComponentsManager.Choice>>,
|
||||
placed: Set<String>,
|
||||
): List<Pair<ComponentsManager.Proton, String>> =
|
||||
protons.filterNot(::follows).flatMap { p ->
|
||||
choices[p.id].orEmpty().filter { (_, c) -> !c.auto && c.protonVersion == p.version && c.file in placed }.keys.map { p to it }
|
||||
protons.flatMap { p ->
|
||||
choices[p.id].orEmpty().filter { (comp, c) -> !autoFollows(p, comp) && !c.auto && c.protonVersion == p.version && c.file in placed }.keys.map { p to it }
|
||||
}
|
||||
|
||||
fun unseen(
|
||||
@@ -53,13 +60,14 @@ object ComponentUpdates {
|
||||
|
||||
fun pick(items: List<ComponentsManager.CatalogItem>, line: Line, bad: Set<String>): ComponentsManager.CatalogItem? {
|
||||
val newestBad = bad.filter { belongs(it, line) }.maxWithOrNull { a, b -> ProtonExtras.compareVersions(a, b) }
|
||||
return items.filter { it.release == ComponentsManager.DD_NIGHTLY && it.comp == line.comp && belongs(it.file, line) }
|
||||
return items.filter { it.release == line.release && it.comp == line.comp && belongs(it.file, line) }
|
||||
.filter { newestBad == null || ProtonExtras.compareVersions(it.file, newestBad) > 0 }
|
||||
.maxWithOrNull { a, b -> ProtonExtras.compareVersions(a.file, b.file) }
|
||||
}
|
||||
|
||||
fun belongs(file: String, line: Line): Boolean =
|
||||
file.startsWith(line.prefix) && file.removePrefix(line.prefix).firstOrNull()?.isDigit() == true
|
||||
file.startsWith(line.prefix) && file.removePrefix(line.prefix).firstOrNull()?.isDigit() == true &&
|
||||
(line.comp != "fex" || ComponentsManager.bionicFex(file) == (line.release == ComponentsManager.DD_BIONIC))
|
||||
|
||||
fun arm64ec(pe: ByteArray): Boolean? = runCatching {
|
||||
val b = ByteBuffer.wrap(pe).order(ByteOrder.LITTLE_ENDIAN)
|
||||
@@ -161,7 +169,7 @@ object ComponentUpdates {
|
||||
fun stale(line: Line?, owned: Set<String>, stored: List<String>, keep: Set<String>, current: String, bad: Set<String> = emptySet()): List<String> {
|
||||
val ranked = line?.takeIf { belongs(current, it) }
|
||||
fun newer(file: String) = ranked != null && belongs(file, ranked) && ProtonExtras.compareVersions(file, current) > 0
|
||||
return (owned + stored.filter { ranked != null && belongs(it, ranked) })
|
||||
return (owned + stored.filter { ranked != null && ranked.release == ComponentsManager.DD_NIGHTLY && belongs(it, ranked) })
|
||||
.filter { it !in keep && ((it in bad && it in owned) || !newer(it)) }.distinct()
|
||||
}
|
||||
}
|
||||
@@ -29,6 +29,7 @@ object ComponentsManager {
|
||||
private const val NIGHTLIES = "The412Banner/Nightlies"
|
||||
private const val DD_COMPONENTS = "Droid-Deck/DroidDeck-Components"
|
||||
internal const val DD_NIGHTLY = "linux-nightly"
|
||||
internal const val DD_BIONIC = "bionic-stable"
|
||||
private val RELEASES = linkedMapOf(
|
||||
"FexCore-Linux" to "fex",
|
||||
"Dxvk-Linux" to "dxvk",
|
||||
@@ -37,9 +38,9 @@ object ComponentsManager {
|
||||
"Vkd3d-proton-Linux" to "vkd3d",
|
||||
)
|
||||
private val NIGHTLY_PREFIXES = linkedMapOf("DD-dxvk-" to "dxvk", "DD-vkd3d-proton-" to "vkd3d", "DD-FEXCore-" to "fex")
|
||||
private val SOURCES = RELEASES.keys.map { NIGHTLIES to it } + (DD_COMPONENTS to DD_NIGHTLY)
|
||||
private val SOURCES = RELEASES.keys.map { NIGHTLIES to it } + (DD_COMPONENTS to DD_NIGHTLY) + (DD_COMPONENTS to DD_BIONIC)
|
||||
private val DOWNLOAD_REPOS = listOf(NIGHTLIES, DD_COMPONENTS)
|
||||
private val TYPES = mapOf("FEXCore-Linux" to "fex", "DXVK-Linux" to "dxvk", "VKD3D-Linux" to "vkd3d")
|
||||
private val TYPES = mapOf("FEXCore-Linux" to "fex", "FEXCore-Bionic" to "fex", "DXVK-Linux" to "dxvk", "VKD3D-Linux" to "vkd3d")
|
||||
private val TYPE_OF = mapOf("fex" to "FEXCore-Linux", "dxvk" to "DXVK-Linux", "vkd3d" to "VKD3D-Linux")
|
||||
val COMPONENTS = listOf("fex", "dxvk", "vkd3d")
|
||||
val LABEL = mapOf("fex" to "FEX", "dxvk" to "DXVK", "vkd3d" to "VKD3D-Proton")
|
||||
@@ -201,8 +202,26 @@ object ComponentsManager {
|
||||
COMPONENTS.mapNotNull { comp -> profile.optString(comp).takeIf(String::isNotEmpty)?.let { comp to it } }.toMap()
|
||||
}
|
||||
|
||||
fun setGameComponent(context: Context, scope: String, comp: String, file: String?) =
|
||||
fun setGameComponent(context: Context, scope: String, comp: String, file: String?) {
|
||||
setGameComponent(context, scope, comp, file) { runtimeManaged(context, it) }
|
||||
if (comp == "fex" && file != null) fetchFexTwin(context, safeName(file))
|
||||
}
|
||||
|
||||
private fun fetchFexTwin(context: Context, file: String) {
|
||||
val twin = fexTwin(file) ?: return
|
||||
if (isStored(context, twin) || protons(context).all { fexFits(it.dir.name, file) }) return
|
||||
val app = context.applicationContext
|
||||
Thread({
|
||||
runCatching {
|
||||
val item = catalogItem(app, twin, if (bionicFex(twin)) DD_BIONIC else "FexCore-Linux")
|
||||
if (item == null) Log.i(TAG, "$twin is not listed")
|
||||
else {
|
||||
download(app, item) {}
|
||||
republish(app)
|
||||
}
|
||||
}.onFailure { Log.w(TAG, "download $twin", it) }
|
||||
}, "fex-twin").start()
|
||||
}
|
||||
|
||||
internal fun setGameComponent(context: Context, scope: String, comp: String, file: String?, managed: (String) -> Boolean) = synchronized(lock) {
|
||||
require(scope.matches(Regex("[1-9][0-9]{0,9}")) && scope.toLong() <= 4294967295L)
|
||||
@@ -399,7 +418,7 @@ object ComponentsManager {
|
||||
}
|
||||
}
|
||||
require(File(staged, "files").isDirectory) { "${wcp.name} has no files/" }
|
||||
if (comp == "fex") FEX_FILES.filter { it.endsWith(".so") && !File(staged, it).isFile }.forEach { File(dir, it).delete() }
|
||||
if (comp == "fex" && !bionicTool(dir.name)) FEX_FILES.filter { it.endsWith(".so") && !File(staged, it).isFile }.forEach { File(dir, it).delete() }
|
||||
COMP_DIR[comp]?.let { compDir ->
|
||||
for (arch in PE_ARCHES) {
|
||||
val target = File(dir, "$compDir/$arch")
|
||||
@@ -587,7 +606,9 @@ object ComponentsManager {
|
||||
File(base, "files").walkTopDown().filter { it.isFile }.map { it.relativeTo(base).invariantSeparatorsPath }
|
||||
.filter { owned(comp, it) }.associateWith { File(base, it) }
|
||||
}
|
||||
for (rel in managed(comp) - files.keys) {
|
||||
// A bionic tool never loses a FEX file: its launch.sh would put the whole bundled FEX back.
|
||||
val removed = if (comp == "fex" && bionicTool(p.dir.name)) emptySet() else managed(comp) - files.keys
|
||||
for (rel in removed) {
|
||||
lines.append(scope).append('\t').append(p.dir.name).append('\t').append(p.version).append('\t').append(comp)
|
||||
.append('\t').append(rel).append("\t-\t-\n")
|
||||
}
|
||||
@@ -604,7 +625,8 @@ object ComponentsManager {
|
||||
val version = safeName(file.removePrefix("original "))
|
||||
"original-${p.id}-$version-$comp" to File(originalsDir(context), "${p.id}/$version/$comp.wcp")
|
||||
} else {
|
||||
safeName(file.removeSuffix(".wcp")) to File(packagesDir(context), file)
|
||||
val fit = (if (comp == "fex") launchFex(p.dir.name, file) { File(packagesDir(context), it).isFile } else file) ?: return null
|
||||
safeName(fit.removeSuffix(".wcp")) to File(packagesDir(context), fit)
|
||||
}.takeIf { it.second.isFile }
|
||||
}
|
||||
|
||||
@@ -635,12 +657,14 @@ object ComponentsManager {
|
||||
for (scope in profiles.keys()) {
|
||||
val profile = profiles.optJSONObject(scope) ?: continue
|
||||
for (comp in COMPONENTS) {
|
||||
val file = profile.optString(comp)
|
||||
if (file.isEmpty()) continue
|
||||
val wcp = File(packagesDir(context), file)
|
||||
if (!wcp.isFile) continue
|
||||
val key = safeName(file.removeSuffix(".wcp"))
|
||||
for (p in all) append(scope, p, comp, key, wcp)
|
||||
val chosen = profile.optString(comp)
|
||||
if (chosen.isEmpty()) continue
|
||||
for (p in all) {
|
||||
val file = (if (comp == "fex") launchFex(p.dir.name, chosen) { File(packagesDir(context), it).isFile } else chosen) ?: continue
|
||||
val wcp = File(packagesDir(context), file)
|
||||
if (!wcp.isFile) continue
|
||||
append(scope, p, comp, safeName(file.removeSuffix(".wcp")), wcp)
|
||||
}
|
||||
}
|
||||
}
|
||||
return PreparedLaunchState(lines.toString(), keep)
|
||||
@@ -661,6 +685,7 @@ object ComponentsManager {
|
||||
val wcp = File(packagesDir(context), safeName(file))
|
||||
val info = packageInfo(context, wcp)
|
||||
requireSelectable(context, info.comp)
|
||||
requireFits(p, info)
|
||||
val state = loadState(context)
|
||||
if (inUse(context, p)) {
|
||||
state.sub("queued").sub(p.id).put(info.comp, JSONObject().put("kind", "package").put("file", wcp.name).put("label", info.version)
|
||||
@@ -674,7 +699,11 @@ object ComponentsManager {
|
||||
context.getString(R.string.cmgr_swap_done, LABEL[info.comp], info.version, p.name)
|
||||
}
|
||||
|
||||
private fun requireFits(p: Proton, info: Package) =
|
||||
check(info.comp != "fex" || fexFits(p.dir.name, info.file)) { "${info.file} is not a FEX build for ${p.name}" }
|
||||
|
||||
private fun applyPackage(context: Context, p: Proton, info: Package, wcp: File, state: JSONObject, auto: Boolean = false) {
|
||||
requireFits(p, info)
|
||||
ensureOriginal(context, p, info.comp, state)
|
||||
val hashes = installFiles(context, p.dir, info.comp, wcp)
|
||||
state.sub("active").sub(p.id).put(info.comp, JSONObject()
|
||||
@@ -803,7 +832,11 @@ object ComponentsManager {
|
||||
val profiles = state.optJSONObject("profiles")
|
||||
for (scope in profiles?.keys() ?: emptyList<String>().iterator()) {
|
||||
val profile = profiles?.optJSONObject(scope) ?: continue
|
||||
COMPONENTS.forEach { comp -> profile.optString(comp).takeIf { it.isNotEmpty() }?.let(names::add) }
|
||||
COMPONENTS.forEach { comp ->
|
||||
val file = profile.optString(comp).takeIf { it.isNotEmpty() } ?: return@forEach
|
||||
names.add(file)
|
||||
if (comp == "fex" && installed.any { !fexFits(it.dir.name, file) }) fexTwin(file)?.let(names::add)
|
||||
}
|
||||
}
|
||||
return names
|
||||
}
|
||||
@@ -874,6 +907,7 @@ object ComponentsManager {
|
||||
val queued = state.sub("queued").sub(target.id)
|
||||
var changed = false
|
||||
wanted.forEach { (comp, entry) ->
|
||||
if (comp == "fex" && !fexFits(target.dir.name, entry.optString("file"))) return@forEach
|
||||
if (active?.has(comp) != true && !queued.has(comp)) {
|
||||
queued.put(comp, entry)
|
||||
changed = true
|
||||
@@ -1050,8 +1084,11 @@ object ComponentsManager {
|
||||
return Catalog(items, o.optLong("fetchedAt"))
|
||||
}
|
||||
|
||||
internal fun assetComp(release: String, name: String): String? =
|
||||
RELEASES[release] ?: if (release == DD_NIGHTLY) NIGHTLY_PREFIXES.entries.firstOrNull { name.startsWith(it.key) }?.value else null
|
||||
internal fun assetComp(release: String, name: String): String? = RELEASES[release] ?: when (release) {
|
||||
DD_NIGHTLY -> NIGHTLY_PREFIXES.entries.firstOrNull { name.startsWith(it.key) }?.value
|
||||
DD_BIONIC -> "fex"
|
||||
else -> null
|
||||
}
|
||||
|
||||
internal val CATALOG_ORDER: Comparator<CatalogItem> =
|
||||
compareBy<CatalogItem> { it.comp }.thenBy { it.release == DD_NIGHTLY }.then(newestFirst { it.file })
|
||||
@@ -1139,6 +1176,25 @@ object ComponentsManager {
|
||||
return runCatching { readWcpEntry(original, rel) }.getOrNull()
|
||||
}
|
||||
|
||||
// DroidDeck-Bionic loads only Android builds of FEX's unix libraries; other Protons only glibc builds.
|
||||
internal fun bionicTool(dirName: String?): Boolean = dirName?.startsWith("DroidDeck-Bionic") == true
|
||||
|
||||
internal fun bionicFex(file: String): Boolean = file.endsWith("-bionic.wcp", ignoreCase = true)
|
||||
|
||||
internal fun fexFits(toolDir: String?, file: String): Boolean = bionicTool(toolDir) == bionicFex(file)
|
||||
|
||||
internal fun fexTwin(file: String): String? = when {
|
||||
file.endsWith("-linux.wcp", ignoreCase = true) -> file.dropLast("-linux.wcp".length) + "-bionic.wcp"
|
||||
file.endsWith("-bionic.wcp", ignoreCase = true) -> file.dropLast("-bionic.wcp".length) + "-linux.wcp"
|
||||
else -> null
|
||||
}
|
||||
|
||||
internal fun launchFex(toolDir: String, file: String, stored: (String) -> Boolean): String? =
|
||||
if (fexFits(toolDir, file)) file else fexTwin(file)?.takeIf(stored)
|
||||
|
||||
internal fun <T> forTool(comp: String, toolDir: String?, items: List<T>, selected: String? = null, file: (T) -> String): List<T> =
|
||||
if (comp != "fex") items else items.filter { file(it) == selected || fexFits(toolDir, file(it)) }
|
||||
|
||||
fun supports(p: Proton, comp: String): Boolean =
|
||||
if (comp == "fex") File(p.dir, FEX_FILES.first()).isFile else File(p.dir, "${COMP_DIR.getValue(comp)}/aarch64-windows").isDirectory
|
||||
|
||||
|
||||
@@ -74,10 +74,16 @@ object ExperimentalProtons {
|
||||
return PREFIX + base + (tag?.let { "-$it" } ?: "")
|
||||
}
|
||||
|
||||
/** DroidDeck-Bionic test builds are prereleases of the same repository and have their own row in the Proton list. */
|
||||
internal fun listed(assets: List<ProtonExtras.Asset>): List<ProtonExtras.Asset> {
|
||||
val bionic = ProtonExtras.tools.first { it.id == ProtonExtras.BIONIC }
|
||||
return assets.filterNot { bionic.assetPattern.containsMatchIn(it.name) }
|
||||
}
|
||||
|
||||
fun refresh(context: Context): List<Release>? {
|
||||
val tool = ProtonExtras.tools.first { it.id == ProtonExtras.OWN }
|
||||
val fetched = ProtonExtras.releasesForRemoval(tool) ?: return null
|
||||
val assets = ProtonExtras.assets(tool, fetched.releases, prerelease = true)
|
||||
val assets = listed(ProtonExtras.assets(tool, fetched.releases, prerelease = true))
|
||||
val rows = assets.map { Release(it.tag, it.name, it.url, it.sha512, it.size, it.releaseName) }.distinctBy { it.tag }
|
||||
if (!SessionState.running) {
|
||||
reconcile(context, fetched)
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.app.Activity
|
||||
import android.app.ActivityOptions
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.hardware.display.DisplayManager
|
||||
import android.os.Bundle
|
||||
import android.os.SystemClock
|
||||
import android.util.Log
|
||||
import android.view.Display
|
||||
import android.view.MotionEvent
|
||||
import android.view.WindowManager
|
||||
|
||||
// While a session is on screen, sits invisibly on top of every other display, so that display's
|
||||
// home launcher is not its top activity. lmkd kills the launcher first; restarted as a top activity
|
||||
// it takes focus from the session, which then drops to adj 50 and is killed next.
|
||||
// Android gives a translucent activity alone in its task an input sink that eats every touch on the
|
||||
// display whatever its window flags say, so a touch makes the guard leave that display until the
|
||||
// session is back on top.
|
||||
class KeepTopActivity : Activity() {
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
@Suppress("DEPRECATION") overridePendingTransition(0, 0)
|
||||
if (intent.getBooleanExtra(EXTRA_BOUNCE, false)) {
|
||||
bounces++
|
||||
finish()
|
||||
return
|
||||
}
|
||||
if (intent.getIntExtra(EXTRA_GENERATION, -1) != generation) {
|
||||
finishAndRemoveTask()
|
||||
return
|
||||
}
|
||||
window.addFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE)
|
||||
val id = display?.displayId ?: Display.INVALID_DISPLAY
|
||||
starting.remove(id)
|
||||
if (id in yielded) {
|
||||
finishAndRemoveTask()
|
||||
return
|
||||
}
|
||||
guards[id]?.takeIf { it !== this && !it.isFinishing }?.finishAndRemoveTask()
|
||||
guards[id] = this
|
||||
}
|
||||
|
||||
override fun dispatchTouchEvent(event: MotionEvent): Boolean {
|
||||
if (event.actionMasked == MotionEvent.ACTION_DOWN && !isFinishing) {
|
||||
val id = display?.displayId ?: Display.INVALID_DISPLAY
|
||||
yielded.add(id)
|
||||
Log.i(TAG, "display $id touched, leaving it to the app below")
|
||||
finishAndRemoveTask()
|
||||
onYield?.invoke()
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
guards.values.remove(this)
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val TAG = "KeepTop"
|
||||
private const val EXTRA_BOUNCE = "bounce"
|
||||
private const val EXTRA_GENERATION = "generation"
|
||||
private var generation = 0
|
||||
var bounces = 0
|
||||
private set
|
||||
private val guards = HashMap<Int, KeepTopActivity>()
|
||||
private const val START_TIMEOUT_MS = 2_000L
|
||||
private val starting = HashMap<Int, Long>()
|
||||
private val yielded = HashSet<Int>()
|
||||
const val YIELD_GRACE_MS = 5_000L
|
||||
var onYield: (() -> Unit)? = null
|
||||
|
||||
fun rearm() = yielded.clear()
|
||||
|
||||
fun guardOtherDisplays(context: Context, sessionDisplay: Int): Boolean {
|
||||
val displays = context.getSystemService(DisplayManager::class.java)?.displays ?: return false
|
||||
var started = false
|
||||
for (display in displays) {
|
||||
val id = display.displayId
|
||||
if (id == sessionDisplay || id in yielded || display.state != Display.STATE_ON || guards[id]?.isFinishing == false ||
|
||||
starting[id]?.let { SystemClock.elapsedRealtime() - it < START_TIMEOUT_MS } == true) continue
|
||||
runCatching {
|
||||
launch(context, id, bounce = false)
|
||||
starting[id] = SystemClock.elapsedRealtime()
|
||||
started = true
|
||||
Log.i(TAG, "guarding display $id from a home launcher restart")
|
||||
}.onFailure { Log.w(TAG, "could not guard display $id", it) }
|
||||
}
|
||||
if (!started) return false
|
||||
return runCatching { launch(context, sessionDisplay, bounce = true) }
|
||||
.onFailure { Log.w(TAG, "could not return focus to display $sessionDisplay", it) }.isSuccess
|
||||
}
|
||||
|
||||
fun hasPendingStarts() = starting.isNotEmpty()
|
||||
|
||||
const val RETRY_MS = START_TIMEOUT_MS + 250
|
||||
|
||||
fun stepAside() {
|
||||
generation++
|
||||
guards.values.toList().forEach { it.finishAndRemoveTask() }
|
||||
guards.clear()
|
||||
starting.clear()
|
||||
}
|
||||
|
||||
fun release() {
|
||||
stepAside()
|
||||
yielded.clear()
|
||||
}
|
||||
|
||||
private fun launch(context: Context, displayId: Int, bounce: Boolean) {
|
||||
val intent = Intent(context, KeepTopActivity::class.java)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_MULTIPLE_TASK or Intent.FLAG_ACTIVITY_NO_ANIMATION)
|
||||
.putExtra(EXTRA_BOUNCE, bounce)
|
||||
.putExtra(EXTRA_GENERATION, generation)
|
||||
context.startActivity(intent, ActivityOptions.makeBasic().setLaunchDisplayId(displayId).toBundle())
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
// Tracks a pause that skipped the session's departure cleanup for the keep-top focus bounce.
|
||||
internal class LightPause {
|
||||
private var pending = false
|
||||
private var bouncesAtPause = 0
|
||||
|
||||
fun paused(bounces: Int) {
|
||||
pending = true
|
||||
bouncesAtPause = bounces
|
||||
}
|
||||
|
||||
// The bounce resumes the session within tens of milliseconds; still paused at the timeout means
|
||||
// something else holds the pause.
|
||||
fun timedOut(): Boolean = take()
|
||||
|
||||
fun stopped(): Boolean = take()
|
||||
|
||||
fun resumed(bounces: Int): Resume {
|
||||
if (!pending) return Resume.NORMAL
|
||||
pending = false
|
||||
return if (bounces != bouncesAtPause) Resume.LIGHT else Resume.CLEANUP_FIRST
|
||||
}
|
||||
|
||||
private fun take(): Boolean {
|
||||
val was = pending
|
||||
pending = false
|
||||
return was
|
||||
}
|
||||
|
||||
enum class Resume { NORMAL, LIGHT, CLEANUP_FIRST }
|
||||
}
|
||||
@@ -14,7 +14,8 @@ object ProtonDefault {
|
||||
|
||||
data class Tool(val name: String, val display: String, val dir: String, val valve: Boolean)
|
||||
data class Request(val seq: Long, val valve: Boolean, val dir: String)
|
||||
data class State(val default: String?, val applied: Long, val live: Boolean, val pending: String?, val tools: List<Tool>)
|
||||
data class State(val default: String?, val applied: Long, val live: Boolean, val pending: String?, val tools: List<Tool>,
|
||||
val source: String? = null)
|
||||
data class GameChoice(val valve: Boolean, val dir: String)
|
||||
|
||||
enum class Outcome { LIVE, NEXT_START, NOT_RUNNABLE }
|
||||
@@ -34,6 +35,7 @@ object ProtonDefault {
|
||||
Tool(t.optString("name"), t.optString("display"), t.optString("dir"), t.optBoolean("valve"))
|
||||
}?.takeIf { it.name.isNotEmpty() }
|
||||
},
|
||||
source = o.optString("source").ifEmpty { null },
|
||||
)
|
||||
}
|
||||
|
||||
@@ -99,7 +101,13 @@ object ProtonDefault {
|
||||
if (!runnable(state, proton)) return Outcome.NOT_RUNNABLE
|
||||
val d = dir(context)
|
||||
val seq = nextSeq(System.currentTimeMillis(), state, parseRequest(read(File(d, "request.json"))))
|
||||
val body = JSONObject().put("seq", seq).put("valve", proton.valve).put("dir", proton.dir.name).toString(1) + "\n"
|
||||
writeRequest(d, Request(seq, proton.valve, proton.dir.name))
|
||||
val tool = state.tools.firstOrNull { it.valve == proton.valve && it.dir == proton.dir.name }
|
||||
return if (SessionState.running && state.live && (tool == null || state.pending != tool.name)) Outcome.LIVE else Outcome.NEXT_START
|
||||
}
|
||||
|
||||
private fun writeRequest(d: File, request: Request) {
|
||||
val body = JSONObject().put("seq", request.seq).put("valve", request.valve).put("dir", request.dir).toString(1) + "\n"
|
||||
val staged = File(d, "request.json.staged")
|
||||
try {
|
||||
d.mkdirs()
|
||||
@@ -110,8 +118,45 @@ object ProtonDefault {
|
||||
Log.w(TAG, "could not write the Proton request", e)
|
||||
throw e
|
||||
}
|
||||
val tool = state.tools.firstOrNull { it.valve == proton.valve && it.dir == proton.dir.name }
|
||||
return if (SessionState.running && state.live && (tool == null || state.pending != tool.name)) Outcome.LIVE else Outcome.NEXT_START
|
||||
}
|
||||
|
||||
// The default that names a tool an update replaces moves to the new one, as the per-game picks do: otherwise the guest
|
||||
// no longer finds it and falls back to DroidDeck-Proton.
|
||||
internal fun movedDefault(state: State, request: Request?, from: Set<String>, to: String, now: Long): Request? {
|
||||
val (valve, dir) = chosen(state, request) ?: return null
|
||||
if (valve || dir !in from) return null
|
||||
return Request(nextSeq(now, state, request), false, to)
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun moveDefault(context: Context, from: Set<String>, to: String) {
|
||||
val d = dir(context)
|
||||
val moved = movedDefault(state(context), parseRequest(read(File(d, "request.json"))), from, to, System.currentTimeMillis()) ?: return
|
||||
writeRequest(d, moved)
|
||||
}
|
||||
|
||||
// DroidDeck-Bionic keeps one build. A default naming another one moves to the installed build: an app from before
|
||||
// updates carried the default over left it, or the guest fell back to its own tool when that build was gone (the
|
||||
// request the app last wrote still names it).
|
||||
internal fun bionicDefault(state: State, request: Request?, prefix: String, newest: String, now: Long): Request? {
|
||||
val current = chosen(state, request)
|
||||
val stale = when {
|
||||
current != null && !current.first && current.second.startsWith(prefix) -> current.second
|
||||
state.source == "fallback" && request != null && !request.valve && request.dir.startsWith(prefix) -> request.dir
|
||||
else -> return null
|
||||
}
|
||||
return if (stale == newest) null else Request(nextSeq(now, state, request), false, newest)
|
||||
}
|
||||
|
||||
/** The default and the per-game picks that name a DroidDeck-Bionic build other than [newest] move to it. */
|
||||
@Synchronized
|
||||
fun keepBionicCurrent(context: Context, prefix: String, newest: String) {
|
||||
val d = dir(context)
|
||||
bionicDefault(state(context), parseRequest(read(File(d, "request.json"))), prefix, newest, System.currentTimeMillis())
|
||||
?.let { writeRequest(d, it) }
|
||||
val games = parseGames(read(File(d, GAMES)))
|
||||
val stale = games.values.filterNotNull().filter { !it.valve && it.dir.startsWith(prefix) && it.dir != newest }.map { it.dir }.toSet()
|
||||
if (stale.isNotEmpty()) movedGames(games, stale, newest)?.let { writeGames(d, it) }
|
||||
}
|
||||
|
||||
internal fun movedGames(choices: Map<String, GameChoice?>, from: Set<String>, to: String): Map<String, GameChoice?>? {
|
||||
|
||||
@@ -8,6 +8,7 @@ import android.util.Log
|
||||
import com.droiddeck.launcher.core.Downloader
|
||||
import com.droiddeck.launcher.core.FileUtils
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import com.droiddeck.launcher.runtime.NativeGuest
|
||||
import java.io.File
|
||||
import java.util.Locale
|
||||
import org.json.JSONArray
|
||||
@@ -27,20 +28,27 @@ object ProtonExtras {
|
||||
@Volatile
|
||||
private var replacing = false
|
||||
|
||||
class Tool(val id: String, val name: String, val prefix: String, val repo: String, val assetPattern: Regex)
|
||||
class Tool(val id: String, val name: String, val prefix: String, val repo: String, val assetPattern: Regex,
|
||||
val prereleases: Boolean = false)
|
||||
|
||||
internal data class Asset(val tag: String, val name: String, val url: String, val sha512: String?, val size: Long,
|
||||
val sha256: String? = null, val releaseName: String = tag)
|
||||
internal data class ReleaseFetch(val releases: JSONArray, val complete: Boolean)
|
||||
|
||||
const val OWN = "droiddeck"
|
||||
const val BIONIC = "bionic"
|
||||
|
||||
val tools = listOf(
|
||||
Tool("ge", "GE-Proton", "GE-Proton", "GloriousEggroll/proton-ge-custom", Regex("aarch64\\.tar\\.(gz|xz)$")),
|
||||
Tool("cachyos", "proton-cachyos", "proton-cachyos", "CachyOS/proton-cachyos", Regex("arm64\\.tar\\.(gz|xz)$")),
|
||||
Tool("droiddeck", "DroidDeck-Proton", "DroidDeck-Proton", "Droid-Deck/DroidDeck-Proton", Regex("aarch64\\.tar\\.(gz|xz)$")),
|
||||
Tool("droiddeck", "DroidDeck-Proton", "DroidDeck-Proton", "Droid-Deck/DroidDeck-Proton", Regex("^DroidDeck-Proton-.*aarch64\\.tar\\.(gz|xz)$")),
|
||||
// Bionic (Android libc) Proton started outside the Linux userland; test builds are prereleases. No-proot only.
|
||||
Tool(BIONIC, "DroidDeck-Bionic", "DroidDeck-Bionic", "Droid-Deck/DroidDeck-Proton", Regex("^DroidDeck-Bionic-.*aarch64\\.tar\\.(gz|xz)$"), prereleases = true),
|
||||
)
|
||||
|
||||
/** The sources offered on this device: DroidDeck-Bionic only with Run without proot on. */
|
||||
fun offered(context: Context): List<Tool> = tools.filter { it.id != BIONIC || NativeGuest.enabled(context) }
|
||||
|
||||
private fun home(context: Context) = File(LinuxRuntime.rootDir(context), "root")
|
||||
private fun requests(context: Context) = File(home(context), ".dd-proton-extra")
|
||||
private fun toolsDir(context: Context) = File(home(context), ".local/share/Steam/compatibilitytools.d")
|
||||
@@ -115,10 +123,11 @@ object ProtonExtras {
|
||||
private var lastAttempt = 0L
|
||||
|
||||
fun checkLatest(context: Context, force: Boolean = false, now: Long = System.currentTimeMillis()): Boolean {
|
||||
keepBionicCurrent(context)
|
||||
synchronized(checkLock) {
|
||||
val file = latestFile(context)
|
||||
val cache = readJson(file)
|
||||
val due = tools.filter { tool ->
|
||||
val due = offered(context).filter { tool ->
|
||||
val at = cache.optJSONObject(tool.id)?.optLong("at", 0L) ?: 0L
|
||||
force || (now - at) !in 0 until CHECK_EVERY_MS
|
||||
}
|
||||
@@ -168,15 +177,32 @@ object ProtonExtras {
|
||||
|
||||
fun remove(context: Context, tool: Tool, dir: String? = null) {
|
||||
val name = if (dir != null) dir.takeIf { it in installedAll(context, tool) } ?: return else installed(context, tool) ?: return
|
||||
if (File(toolsDir(context), name).deleteRecursively()) ComponentsManager.forgetProton(context, name)
|
||||
if (deleteTool(context, name)) ComponentsManager.forgetProton(context, name)
|
||||
}
|
||||
|
||||
// A tool folder can hold links that point out of it (a prefix template's dosdevices/z: -> /), and
|
||||
// File.deleteRecursively() follows links into directories: remove each link itself, never what it points to.
|
||||
private fun deleteTool(context: Context, name: String): Boolean {
|
||||
val dir = File(toolsDir(context), name)
|
||||
FileUtils.delete(dir)
|
||||
return !dir.exists() && !java.nio.file.Files.isSymbolicLink(dir.toPath())
|
||||
}
|
||||
|
||||
fun removeOlder(context: Context, tool: Tool) {
|
||||
installedAll(context, tool).dropLast(1).forEach {
|
||||
if (File(toolsDir(context), it).deleteRecursively()) ComponentsManager.forgetProton(context, it)
|
||||
if (deleteTool(context, it)) ComponentsManager.forgetProton(context, it)
|
||||
}
|
||||
}
|
||||
|
||||
// DroidDeck-Bionic: the default and the game picks name the installed build, also when they were left on one an
|
||||
// older app deleted without moving them.
|
||||
private fun keepBionicCurrent(context: Context) {
|
||||
if (SessionState.running) return
|
||||
val tool = tools.firstOrNull { it.id == BIONIC } ?: return
|
||||
val newest = installedAll(context, tool).lastOrNull() ?: return
|
||||
runCatching { ProtonDefault.keepBionicCurrent(context, tool.prefix, newest) }.onFailure { Log.w(TAG, "bionic default and picks", it) }
|
||||
}
|
||||
|
||||
private fun replaceOlder(context: Context, tool: Tool) {
|
||||
val all = installedAll(context, tool)
|
||||
val newest = all.lastOrNull() ?: return
|
||||
@@ -189,7 +215,9 @@ object ProtonExtras {
|
||||
if (runCatching { ComponentsManager.carryOver(context, old, newest) }.onFailure { Log.w(TAG, "components of $old", it) }.isFailure) continue
|
||||
if (runCatching { keepUserSettings(context, old, newest) }.onFailure { Log.w(TAG, "user settings of $old", it) }.isFailure) continue
|
||||
if (runCatching { ProtonDefault.moveGames(context, setOf(old), newest) }.onFailure { Log.w(TAG, "per-game picks of $old", it) }.isFailure) continue
|
||||
if (File(toolsDir(context), old).deleteRecursively()) ComponentsManager.forgetProton(context, old)
|
||||
// DroidDeck-Bionic only: the guest finds no default for a deleted Bionic build and falls back to DroidDeck-Proton
|
||||
if (tool.id == BIONIC && runCatching { ProtonDefault.moveDefault(context, setOf(old), newest) }.onFailure { Log.w(TAG, "default pick of $old", it) }.isFailure) continue
|
||||
if (deleteTool(context, old)) ComponentsManager.forgetProton(context, old)
|
||||
else Log.w(TAG, "could not remove $old")
|
||||
}
|
||||
} finally {
|
||||
@@ -308,7 +336,7 @@ object ProtonExtras {
|
||||
archive.delete()
|
||||
unqueue(context, tool)
|
||||
record(context, tool, placed, asset.tag)
|
||||
if (tool.id == OWN) replaceOlder(context, tool)
|
||||
if (tool.id == OWN || tool.id == BIONIC) replaceOlder(context, tool)
|
||||
if (EsyncPacks.enabled(context)) {
|
||||
onProgress(context.getString(R.string.esync_fetching), -1)
|
||||
try {
|
||||
@@ -393,7 +421,7 @@ object ProtonExtras {
|
||||
internal fun pickAsset(tool: Tool, array: JSONArray): Asset? {
|
||||
val candidates = (0 until array.length()).asSequence()
|
||||
.mapNotNull { array.optJSONObject(it) }
|
||||
.filter { !it.optBoolean("draft", false) && !it.optBoolean("prerelease", false) }
|
||||
.filter { !it.optBoolean("draft", false) && (tool.prereleases || !it.optBoolean("prerelease", false)) }
|
||||
return candidates.firstNotNullOfOrNull { assetOf(tool, it) }
|
||||
}
|
||||
|
||||
|
||||
@@ -678,18 +678,6 @@ object SessionPrefs {
|
||||
editor.putString("osc", mode).apply()
|
||||
}
|
||||
|
||||
fun oscRearButtons(context: Context): Boolean = prefs(context).getBoolean("oscRearButtons", false)
|
||||
|
||||
fun setOscRearButtons(context: Context, shown: Boolean) {
|
||||
prefs(context).edit().putBoolean("oscRearButtons", shown).apply()
|
||||
}
|
||||
|
||||
fun oscTrackpads(context: Context): Boolean = prefs(context).getBoolean("oscTrackpads", false)
|
||||
|
||||
fun setOscTrackpads(context: Context, shown: Boolean) {
|
||||
prefs(context).edit().putBoolean("oscTrackpads", shown).apply()
|
||||
}
|
||||
|
||||
/** Draw Steam's touch layout for the game instead of DroidDeck's own. */
|
||||
fun steamTouchLayout(context: Context): Boolean =
|
||||
prefs(context).getBoolean("steamTouchLayout", prefs(context).getString("osc", null) == OSC_STEAM_TOUCH)
|
||||
|
||||
@@ -1027,6 +1027,9 @@ class SessionService : Service() {
|
||||
}
|
||||
(if (bridge || venus) null else LinuxVulkanDriver.resolveIcdPath(this, linuxDriverId))
|
||||
?.let { guest.add(LinuxVulkanDriver.ENV + "=" + it) }
|
||||
// DroidDeck-Bionic games load an Android driver build; this is the one the display uses, for a runtime driver
|
||||
// that has none.
|
||||
guest.add("DROIDDECK_DISPLAY_DRIVER=" + com.droiddeck.launcher.gpu.TurnipDriver(this).effectiveId())
|
||||
if (!com.droiddeck.launcher.core.DeviceSupport.adreno() && lastXwaylandCrashed()) {
|
||||
guest.add("XWAYLAND_NO_GLAMOR=1")
|
||||
Log.w(TAG, "xwayland: the last session's Xwayland crashed; glamor off for this one (XWAYLAND_NO_GLAMOR=1)")
|
||||
@@ -1613,11 +1616,6 @@ class SessionService : Service() {
|
||||
return
|
||||
}
|
||||
val accepted = gameId!!
|
||||
if (pendingSteamGameId == null && SteamGameProcess.alreadyRunning(accepted, SessionState.gameId)) {
|
||||
Log.i(TAG, "game $accepted is already running; resuming it instead of launching it again")
|
||||
if (SessionState.suspended || SessionState.suspending) resumeSession()
|
||||
return
|
||||
}
|
||||
if (!pendingSteamPreviousGamePending) {
|
||||
pendingSteamPreviousGameId = SessionState.gameId
|
||||
pendingSteamPreviousGamePending = true
|
||||
@@ -2399,7 +2397,8 @@ class SessionService : Service() {
|
||||
override fun onTaskRemoved(rootIntent: Intent?) {
|
||||
if (rootIntent?.component?.className in setOf(
|
||||
com.droiddeck.launcher.ui.DualScreenActivity::class.java.name,
|
||||
com.droiddeck.launcher.ui.SessionTypingActivity::class.java.name)) return
|
||||
com.droiddeck.launcher.ui.SessionTypingActivity::class.java.name,
|
||||
KeepTopActivity::class.java.name)) return
|
||||
if (pipTask || xrActivityVisible) {
|
||||
Log.i(TAG, "panel task dismissed - retaining the session under its active surface policy")
|
||||
activityVisible = false
|
||||
|
||||
@@ -61,11 +61,4 @@ object SteamGameProcess {
|
||||
runCatching { File(p, "cmdline").readBytes() }
|
||||
.getOrNull()?.let { matches(it, gameId) } == true
|
||||
} == true
|
||||
|
||||
// A front end that resumes a player by launching the same game again would otherwise have Steam
|
||||
// start it a second time, which Steam answers with "Game already running".
|
||||
fun alreadyRunning(requested: String, current: String?, proc: File = File("/proc")): Boolean {
|
||||
val appId = steamAppIdForGameId(requested) ?: return false
|
||||
return appId == steamAppIdForGameId(current.orEmpty()) && running(requested, proc)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.content.ComponentCallbacks2
|
||||
|
||||
internal object TopUnderPressure {
|
||||
const val WINDOW_MS = 5_000L
|
||||
|
||||
fun isPressure(level: Int) =
|
||||
level == ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL || level == ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW
|
||||
|
||||
fun shouldReclaim(nowMs: Long, pressureAtMs: Long, sessionRunning: Boolean, finishing: Boolean) =
|
||||
sessionRunning && !finishing && pressureAtMs > 0 && nowMs - pressureAtMs in 0..WINDOW_MS
|
||||
}
|
||||
@@ -90,8 +90,6 @@ object StoreLaunchRequests {
|
||||
lastLaunched = Store.ROCKSTAR to request.optString("id")
|
||||
com.droiddeck.launcher.stores.rockstar.RockstarLaunch.prepare(app, request.optString("id"))
|
||||
}.getOrElse { JSONObject().put("ok", false).put("reason", "error-" + it.javaClass.simpleName) }
|
||||
"rockstar-sdk" -> runCatching { com.droiddeck.launcher.stores.rockstar.RockstarLaunch.sdkInstaller(app, request.optString("id")) }
|
||||
.getOrElse { JSONObject().put("ok", false).put("reason", "error-" + it.javaClass.simpleName) }
|
||||
"store-service" -> runCatching {
|
||||
val root = com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(app)
|
||||
if (com.droiddeck.launcher.session.SessionFiles.awaitStoreService(app, request.optString("store"), root)) JSONObject().put("ok", true)
|
||||
|
||||
@@ -99,11 +99,6 @@ internal object RockstarManifest {
|
||||
}
|
||||
|
||||
fun key(file: RockstarFile, chunk: RockstarChunk) = "${file.versionId}:${chunk.chunkId}"
|
||||
|
||||
fun sdkInstaller(build: RockstarBuild): RockstarFile? {
|
||||
val name = RockstarLaunch.SDK_INSTALLER.substringAfterLast('/')
|
||||
return build.files.filter { it.path.substringAfterLast('/').equals(name, ignoreCase = true) }.minByOrNull { it.path.length }
|
||||
}
|
||||
}
|
||||
|
||||
internal class RockstarInstaller(
|
||||
@@ -165,7 +160,7 @@ internal class RockstarInstaller(
|
||||
for (c in batch) {
|
||||
if (cancelled.get()) break
|
||||
val f = fileOf.getValue("${c.fileEntryId}:${c.chunkId}")
|
||||
fetch(cancelled::get, { retry -> (if (retry) null else urls[c.chunkId]) ?: chunkUrls(ticket, branch.accessToken, listOf(c)).getValue(c.chunkId) }, RockstarManifest.inside(folder, f.path), c, progress) {
|
||||
fetch({ retry -> (if (retry) null else urls[c.chunkId]) ?: chunkUrls(ticket, branch.accessToken, listOf(c)).getValue(c.chunkId) }, RockstarManifest.inside(folder, f.path), c, progress) {
|
||||
handle.progress(progress.get(), total, "Downloading (${build.files.size} files)")
|
||||
}
|
||||
synchronized(ledgerLock) { ledger.appendText(RockstarManifest.key(f, c) + "\n") }
|
||||
@@ -196,6 +191,58 @@ internal class RockstarInstaller(
|
||||
return folder.path
|
||||
}
|
||||
|
||||
private fun chunkUrls(ticket: String, branchToken: String, batch: List<RockstarChunk>): Map<String, String> {
|
||||
val csv = batch.joinToString(",") { "${it.fileEntryId}:${it.chunkId}" }
|
||||
val root = RockstarRos.result("app.asmx/RetrieveFileChunkMulti", listOf("ticket" to ticket, "branchAccessToken" to branchToken, "fileEntryAndChunkIdCsv" to csv))
|
||||
return RockstarRos.all(root, "Chunk").mapNotNull { c -> RockstarRos.text(c, "RedirectUrl")?.let { c.getAttribute("FileChunkId") to it } }.toMap()
|
||||
}
|
||||
|
||||
private fun fetch(url: (Boolean) -> String, target: File, chunk: RockstarChunk, progress: AtomicLong, report: () -> Unit) {
|
||||
var lastError: Exception? = null
|
||||
for (attempt in 0 until 3) {
|
||||
if (cancelled.get()) return
|
||||
val written = AtomicLong(0)
|
||||
try {
|
||||
val c = URL(url(attempt > 0)).openConnection() as HttpURLConnection
|
||||
c.connectTimeout = 20_000
|
||||
c.readTimeout = 60_000
|
||||
try {
|
||||
if (c.responseCode != 200) throw java.io.IOException("chunk ${chunk.chunkId}: HTTP ${c.responseCode}")
|
||||
val digest = MessageDigest.getInstance("SHA-256")
|
||||
RandomAccessFile(target, "rw").use { out ->
|
||||
out.seek(chunk.offset)
|
||||
c.inputStream.use { input ->
|
||||
val buf = ByteArray(256 * 1024)
|
||||
var last = 0L
|
||||
while (true) {
|
||||
if (cancelled.get()) { progress.addAndGet(-written.get()); return }
|
||||
val n = input.read(buf)
|
||||
if (n < 0) break
|
||||
if (written.get() + n > chunk.size) throw java.io.IOException("chunk ${chunk.chunkId} is longer than the manifest says")
|
||||
out.write(buf, 0, n)
|
||||
digest.update(buf, 0, n)
|
||||
written.addAndGet(n.toLong())
|
||||
progress.addAndGet(n.toLong())
|
||||
val now = System.currentTimeMillis()
|
||||
if (now - last > 400) { last = now; report() }
|
||||
}
|
||||
}
|
||||
}
|
||||
val hex = digest.digest().joinToString("") { "%02x".format(it) }
|
||||
if (written.get() != chunk.size || hex != chunk.sha256) throw java.io.IOException("chunk ${chunk.chunkId} failed its check")
|
||||
report()
|
||||
return
|
||||
} finally {
|
||||
c.disconnect()
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
progress.addAndGet(-written.get())
|
||||
lastError = e
|
||||
}
|
||||
}
|
||||
throw lastError ?: java.io.IOException("chunk ${chunk.chunkId} failed")
|
||||
}
|
||||
|
||||
override fun cancel(deleteFiles: Boolean) {
|
||||
cancelled.set(true)
|
||||
if (deleteFiles) StoreInstalls.discard(app, folder, emptyList())
|
||||
@@ -205,58 +252,6 @@ internal class RockstarInstaller(
|
||||
const val LEDGER = ".droiddeck-rockstar-chunks"
|
||||
private const val WORKERS = 4
|
||||
|
||||
fun chunkUrls(ticket: String, branchToken: String, batch: List<RockstarChunk>): Map<String, String> {
|
||||
val csv = batch.joinToString(",") { "${it.fileEntryId}:${it.chunkId}" }
|
||||
val root = RockstarRos.result("app.asmx/RetrieveFileChunkMulti", listOf("ticket" to ticket, "branchAccessToken" to branchToken, "fileEntryAndChunkIdCsv" to csv))
|
||||
return RockstarRos.all(root, "Chunk").mapNotNull { c -> RockstarRos.text(c, "RedirectUrl")?.let { c.getAttribute("FileChunkId") to it } }.toMap()
|
||||
}
|
||||
|
||||
fun fetch(cancelled: () -> Boolean, url: (Boolean) -> String, target: File, chunk: RockstarChunk, progress: AtomicLong, report: () -> Unit) {
|
||||
var lastError: Exception? = null
|
||||
for (attempt in 0 until 3) {
|
||||
if (cancelled()) return
|
||||
val written = AtomicLong(0)
|
||||
try {
|
||||
val c = URL(url(attempt > 0)).openConnection() as HttpURLConnection
|
||||
c.connectTimeout = 20_000
|
||||
c.readTimeout = 60_000
|
||||
try {
|
||||
if (c.responseCode != 200) throw java.io.IOException("chunk ${chunk.chunkId}: HTTP ${c.responseCode}")
|
||||
val digest = MessageDigest.getInstance("SHA-256")
|
||||
RandomAccessFile(target, "rw").use { out ->
|
||||
out.seek(chunk.offset)
|
||||
c.inputStream.use { input ->
|
||||
val buf = ByteArray(256 * 1024)
|
||||
var last = 0L
|
||||
while (true) {
|
||||
if (cancelled()) { progress.addAndGet(-written.get()); return }
|
||||
val n = input.read(buf)
|
||||
if (n < 0) break
|
||||
if (written.get() + n > chunk.size) throw java.io.IOException("chunk ${chunk.chunkId} is longer than the manifest says")
|
||||
out.write(buf, 0, n)
|
||||
digest.update(buf, 0, n)
|
||||
written.addAndGet(n.toLong())
|
||||
progress.addAndGet(n.toLong())
|
||||
val now = System.currentTimeMillis()
|
||||
if (now - last > 400) { last = now; report() }
|
||||
}
|
||||
}
|
||||
}
|
||||
val hex = digest.digest().joinToString("") { "%02x".format(it) }
|
||||
if (written.get() != chunk.size || hex != chunk.sha256) throw java.io.IOException("chunk ${chunk.chunkId} failed its check")
|
||||
report()
|
||||
return
|
||||
} finally {
|
||||
c.disconnect()
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
progress.addAndGet(-written.get())
|
||||
lastError = e
|
||||
}
|
||||
}
|
||||
throw lastError ?: java.io.IOException("chunk ${chunk.chunkId} failed")
|
||||
}
|
||||
|
||||
fun resolve(folder: File, configured: String): String? {
|
||||
var at = folder
|
||||
for (part in configured.replace('\\', '/').split('/').filter { it.isNotEmpty() }) {
|
||||
|
||||
@@ -10,10 +10,6 @@ import java.security.MessageDigest
|
||||
import java.util.Base64
|
||||
|
||||
object RockstarLaunch {
|
||||
internal const val SDK_INSTALLER = "Redistributables/Social-Club-Setup.exe"
|
||||
private const val LAUNCHER_APP = "launcher"
|
||||
private val sdkLock = Any()
|
||||
|
||||
internal val pipes = mapOf("gta3" to "GTA3_Pipe", "gtavc" to "GTA-VC_Pipe", "gtasa" to "GTA_SA_Pipe", "gta4" to "GTAIV_Pipe", "lanoire" to "LANOIRE_Pipe")
|
||||
|
||||
fun usesClassicLauncher(id: String) = id in pipes
|
||||
@@ -26,47 +22,10 @@ object RockstarLaunch {
|
||||
}
|
||||
}
|
||||
|
||||
private fun installedFolder(app: Context, id: String) = StoreInstallRoot.gameFolders(app).firstOrNull { folder ->
|
||||
StoreGameSidecar.read(folder)?.let { it.store == Store.ROCKSTAR && it.id == id && it.isInstalled } == true
|
||||
}
|
||||
|
||||
fun sdkInstaller(app: Context, id: String): JSONObject = synchronized(sdkLock) { downloadSdkInstaller(app, id) }
|
||||
|
||||
private fun downloadSdkInstaller(app: Context, id: String): JSONObject {
|
||||
val folder = installedFolder(app, id) ?: return failure("not-installed")
|
||||
val target = RockstarManifest.inside(folder, SDK_INSTALLER)
|
||||
if (target.isFile) return JSONObject().put("ok", true)
|
||||
val ticket = RockstarAuth.ticket(app) ?: RockstarAuth.ticket(app, fresh = true) ?: return failure("signed-out")
|
||||
val branch = RockstarApps.fetch(ticket.ticket) {}.apps.firstOrNull { it.name == LAUNCHER_APP }?.let(RockstarApps::branch)
|
||||
?: return failure("no-launcher-build")
|
||||
val build = RockstarManifest.parse(RockstarRos.result("app.asmx/GetBuildManifestFull",
|
||||
listOf("ticket" to ticket.ticket, "branchAccessToken" to branch.accessToken)))
|
||||
val file = RockstarManifest.sdkInstaller(build) ?: return failure("no-sdk-installer")
|
||||
if (file.chunks.sumOf { it.size } != file.size) return failure("invalid-sdk-installer")
|
||||
val part = RockstarManifest.inside(folder, "$SDK_INSTALLER.part")
|
||||
part.parentFile?.mkdirs()
|
||||
try {
|
||||
java.io.RandomAccessFile(part, "rw").use { it.setLength(file.size) }
|
||||
for (batch in RockstarManifest.batches(file.chunks)) {
|
||||
val urls = RockstarInstaller.chunkUrls(ticket.ticket, branch.accessToken, batch)
|
||||
for (chunk in batch) {
|
||||
RockstarInstaller.fetch({ false }, { retry ->
|
||||
(if (retry) null else urls[chunk.chunkId]) ?: RockstarInstaller.chunkUrls(ticket.ticket, branch.accessToken, listOf(chunk)).getValue(chunk.chunkId)
|
||||
}, part, chunk, java.util.concurrent.atomic.AtomicLong()) {}
|
||||
}
|
||||
}
|
||||
if (file.sha256.isNotEmpty() && !RockstarManifest.verified(part, RockstarChunk(file.entryId, "", file.sha256, 0, file.size))) {
|
||||
return failure("invalid-sdk-installer")
|
||||
}
|
||||
if (!part.renameTo(target)) return failure("sdk-installer-unwritable")
|
||||
} finally {
|
||||
part.delete()
|
||||
}
|
||||
return JSONObject().put("ok", true)
|
||||
}
|
||||
|
||||
fun prepare(app: Context, id: String): JSONObject {
|
||||
val folder = installedFolder(app, id) ?: return failure("not-installed")
|
||||
val folder = StoreInstallRoot.gameFolders(app).firstOrNull { folder ->
|
||||
StoreGameSidecar.read(folder)?.let { it.store == Store.ROCKSTAR && it.id == id && it.isInstalled } == true
|
||||
} ?: return failure("not-installed")
|
||||
val installed = StoreGameSidecar.read(folder) ?: return failure("not-installed")
|
||||
val exe = installed.exeFile(folder).canonicalFile
|
||||
if (!exe.path.startsWith(folder.canonicalPath + java.io.File.separator) || !exe.isFile) return failure("missing-game-files")
|
||||
|
||||
@@ -526,11 +526,11 @@ fun ComponentsPage(
|
||||
val availableTitle: @Composable (String) -> String = { l ->
|
||||
when (l) {
|
||||
PROTON_TAB -> stringResource(R.string.comp_available_count, protons.rows.count(ProtonRow::available))
|
||||
else -> stringResource(R.string.comp_nightlies_count, availableRows(l, catalog, snapshot).size)
|
||||
else -> stringResource(R.string.comp_nightlies_count, availableRows(l, catalog, snapshot, view?.proton?.dir?.name).size)
|
||||
}
|
||||
}
|
||||
val followed = view?.proton?.let(ComponentUpdates::follows) == true
|
||||
val moded: (String) -> Boolean = { followed && it in compModes && it !in compAutoHeld && !ComponentsManager.runtimeManaged(it, gpu.systemPowerVr) }
|
||||
val followed: (String) -> Boolean = { l -> view?.proton?.let { ComponentUpdates.autoFollows(it, l) } == true }
|
||||
val moded: (String) -> Boolean = { followed(it) && it in compModes && it !in compAutoHeld && !ComponentsManager.runtimeManaged(it, gpu.systemPowerVr) }
|
||||
val automatic: (String) -> Boolean = { moded(it) && compModes[it] == ComponentUpdates.AUTO }
|
||||
val installedRows: @Composable ColumnScope.(String, Boolean) -> Unit = { l, right ->
|
||||
when (l) {
|
||||
@@ -614,7 +614,7 @@ fun ComponentsPage(
|
||||
}
|
||||
}
|
||||
else -> {
|
||||
val available = availableRows(l, catalog, snapshot)
|
||||
val available = availableRows(l, catalog, snapshot, view?.proton?.dir?.name)
|
||||
if (available.isEmpty()) EmptyLine(if (catalogAt == 0L) stringResource(R.string.comp_refresh_to_list) else stringResource(R.string.comp_nothing_new))
|
||||
for ((stable, nightly) in available) {
|
||||
val d = if (nightly != null && nightlyPicked[stable.file] == true) nightly else stable
|
||||
@@ -974,18 +974,18 @@ private fun installedFor(l: String, view: ComponentsManager.ProtonView?, snapsho
|
||||
o.label.substringAfterLast(" · ", "").ifEmpty { o.label }.let { if (isCurrent) stringResource(R.string.comp_this_build, it) else stringResource(R.string.comp_earlier_build, it) },
|
||||
"ORIGINAL", activeIsOriginal && isCurrent, !isCurrent, null, o.protonVersion,
|
||||
)
|
||||
} + (snapshot?.packages ?: emptyList()).filter { it.comp == l }.map { s ->
|
||||
} + ComponentsManager.forTool(l, view.proton.dir.name, (snapshot?.packages ?: emptyList()).filter { it.comp == l }, st.activeFile) { it.file }.map { s ->
|
||||
InstalledItem(s.version, stringResource(R.string.common_size_mb, s.size / 1048576.0), "STORED", !runtimeManaged && s.file == st.activeFile, true, s.file, null)
|
||||
}
|
||||
}
|
||||
|
||||
private fun availableFor(l: String, catalog: List<CatalogItem>, snapshot: Snapshot?): List<CatalogItem> {
|
||||
private fun availableFor(l: String, catalog: List<CatalogItem>, snapshot: Snapshot?, toolDir: String?): List<CatalogItem> {
|
||||
val stored = (snapshot?.packages ?: emptyList()).map { it.file }.toSet()
|
||||
return catalog.filter { it.comp == l && ComponentsManager.safeName(it.file) !in stored }
|
||||
return ComponentsManager.forTool(l, toolDir, catalog.filter { it.comp == l && ComponentsManager.safeName(it.file) !in stored }) { it.file }
|
||||
}
|
||||
|
||||
private fun availableRows(l: String, catalog: List<CatalogItem>, snapshot: Snapshot?): List<Pair<CatalogItem, CatalogItem?>> {
|
||||
val available = availableFor(l, catalog, snapshot)
|
||||
private fun availableRows(l: String, catalog: List<CatalogItem>, snapshot: Snapshot?, toolDir: String?): List<Pair<CatalogItem, CatalogItem?>> {
|
||||
val available = availableFor(l, catalog, snapshot, toolDir)
|
||||
val pairs = ComponentsManager.nightlyPairs(available)
|
||||
val paired = pairs.values.toSet()
|
||||
return available.filter { it !in paired }.map { it to pairs[it] }
|
||||
@@ -1201,7 +1201,7 @@ private fun GameComponentOverrides(
|
||||
}
|
||||
GamePackageRow(
|
||||
comp = "fex",
|
||||
packages = packages,
|
||||
packages = ComponentsManager.forTool("fex", protonChoice?.dir ?: generalProton?.dir?.name, packages, componentChoices["fex"]) { it.file },
|
||||
selectedFile = componentChoices["fex"],
|
||||
open = componentMenu == "fex",
|
||||
busy = busy,
|
||||
|
||||
@@ -199,9 +199,9 @@ private fun DefaultControlsGroup(host: MenuHost, revision: Int, onEdit: (Triple<
|
||||
var touch by remember { mutableStateOf(SessionPrefs.touchMode(context)) }
|
||||
var below by remember { mutableStateOf(SessionPrefs.unfoldedControls(context)) }
|
||||
SettingsGroup(stringResource(R.string.osc_group_for, stringResource(R.string.osc_default))) {
|
||||
LayoutChoiceRow(host, "osc-layout", options, choice, onPick = { id ->
|
||||
ChoiceRow(host, "osc-layout", stringResource(R.string.osc_layout), null, options, choice) { id ->
|
||||
runCatching { ControlsChoice.choose(context, null, id, desktop = false) }.onSuccess { onChanged() }.onFailure(onFailure)
|
||||
}, onDelete = { id -> runCatching { ControlsChoice.delete(context, id) }.onSuccess { onChanged() }.onFailure(onFailure) })
|
||||
}
|
||||
if (choice != GameControls.STEAM) ActionRow(stringResource(R.string.osc_edit_layout), null, stringResource(R.string.ctrl_edit), {
|
||||
host.open = null
|
||||
ControlsChoice.editTarget(context, null, desktop = false)?.let(onEdit)
|
||||
|
||||
@@ -1,87 +0,0 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.hoverable
|
||||
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||
import androidx.compose.foundation.interaction.collectIsFocusedAsState
|
||||
import androidx.compose.foundation.interaction.collectIsHoveredAsState
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.outlined.Delete
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.platform.testTag
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.semantics.Role
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.input.ControlsChoice
|
||||
|
||||
/** The on-screen controls layout menu: each option with what it is, and a delete button on saved layouts nothing uses. */
|
||||
@Composable
|
||||
fun LayoutChoiceRow(
|
||||
host: MenuHost, key: String, options: List<ControlsChoice.Option>, selected: String, hint: String? = null,
|
||||
chipModifier: Modifier = Modifier, onPick: (String) -> Unit, onDelete: (String) -> Unit,
|
||||
) {
|
||||
val label = stringResource(R.string.osc_layout)
|
||||
val open = host.open == key
|
||||
var deleting by remember { mutableStateOf<ControlsChoice.Option?>(null) }
|
||||
SettingsRow(label, hint, highlighted = open) {
|
||||
Box {
|
||||
ValueChip(options.firstOrNull { it.id == selected }?.name ?: "-", open,
|
||||
modifier = chipModifier.testTag("setting-$key")) { host.open = if (open) null else key }
|
||||
AnchoredMenu(open, onDismiss = { if (host.open == key) host.open = null }, title = label) { firstItemFocus ->
|
||||
options.forEachIndexed { index, option ->
|
||||
MenuItem(option.name, checked = option.id == selected, detail = option.detail,
|
||||
focusRequester = if (index == 0) firstItemFocus else null,
|
||||
trailing = if (option.deletable) ({ DeleteButton(option.id, option.name) { host.open = null; deleting = option } }) else null) {
|
||||
onPick(option.id)
|
||||
host.open = null
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
deleting?.let { option ->
|
||||
AlertDialog(onDismissRequest = { deleting = null },
|
||||
title = { Text(stringResource(R.string.osc_delete_layout)) },
|
||||
text = { Text(stringResource(R.string.input_delete_layout_detail, option.name)) },
|
||||
confirmButton = { PadTextButton(onClick = { deleting = null; onDelete(option.id) }, modifier = Modifier.testTag("osc-delete-confirm")) {
|
||||
Text(stringResource(R.string.common_delete))
|
||||
} },
|
||||
dismissButton = { PadTextButton(onClick = { deleting = null }) { Text(stringResource(R.string.common_cancel)) } })
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun DeleteButton(id: String, name: String, onClick: () -> Unit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val source = remember { MutableInteractionSource() }
|
||||
val hot = source.collectIsFocusedAsState().value || source.collectIsHoveredAsState().value
|
||||
Box(
|
||||
contentAlignment = Alignment.Center,
|
||||
modifier = Modifier.size(36.dp).clip(RoundedCornerShape(8.dp))
|
||||
.background(if (hot) colors.error.copy(alpha = 0.16f) else Color.Transparent)
|
||||
.glideBorder(hot, RoundedCornerShape(8.dp), colors.error)
|
||||
.hoverable(source).clickable(role = Role.Button, interactionSource = source, indication = null, onClick = onClick)
|
||||
.controllerConfirm(onClick = onClick)
|
||||
.testTag("osc-delete-$id"),
|
||||
) {
|
||||
Icon(Icons.Outlined.Delete, contentDescription = stringResource(R.string.common_delete_named, name),
|
||||
tint = if (hot) colors.error else colors.onSurfaceVariant, modifier = Modifier.size(19.dp))
|
||||
}
|
||||
}
|
||||
@@ -291,16 +291,10 @@ class DrawerActions(
|
||||
val achievementsProgress: Pair<Int, Int>? = null,
|
||||
val onOsc: (String) -> Unit,
|
||||
val layoutGame: String? = null,
|
||||
val layoutOptions: List<com.droiddeck.launcher.input.ControlsChoice.Option> = emptyList(),
|
||||
val layoutOptions: List<Pair<String, String>> = emptyList(),
|
||||
val layoutChoice: String = "",
|
||||
val layoutHint: String? = null,
|
||||
val onLayout: (String) -> Unit = {},
|
||||
val onDeleteLayout: (String) -> Unit = {},
|
||||
val onEditLayout: (() -> Unit)? = null,
|
||||
val oscRearButtons: Boolean? = null,
|
||||
val oscTrackpads: Boolean = false,
|
||||
val onOscRearButtons: (Boolean) -> Unit = {},
|
||||
val onOscTrackpads: (Boolean) -> Unit = {},
|
||||
val controller: com.droiddeck.launcher.input.ControllerPrefs.Settings? = null,
|
||||
val onRumble: (Boolean) -> Unit = {},
|
||||
val onSuspendPolicy: (String) -> Unit,
|
||||
@@ -671,8 +665,8 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
|
||||
}
|
||||
SessionDrawerPage.CONTROLLER -> {
|
||||
SettingsGroup(a.layoutGame?.let { stringResource(R.string.osc_group_for, it) } ?: stringResource(R.string.mode_osc)) {
|
||||
if (a.layoutOptions.isNotEmpty()) LayoutChoiceRow(host, "osc-layout", a.layoutOptions, a.layoutChoice, a.layoutHint,
|
||||
chipModifier = focus.track(page, "osc-layout"), onPick = a.onLayout, onDelete = a.onDeleteLayout)
|
||||
if (a.layoutOptions.isNotEmpty()) ChoiceRow(host, "osc-layout", stringResource(R.string.osc_layout), null,
|
||||
a.layoutOptions, a.layoutChoice, chipModifier = focus.track(page, "osc-layout"), onPick = a.onLayout)
|
||||
a.onEditLayout?.let { edit ->
|
||||
ActionRow(stringResource(R.string.osc_edit_layout), null, stringResource(R.string.ctrl_edit), { host.open = null; edit() },
|
||||
modifier = focus.track(page, "osc-edit"))
|
||||
@@ -682,12 +676,6 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
|
||||
SessionPrefs.OSC_NEVER to stringResource(R.string.common_never)), a.oscMode,
|
||||
tabModifier = { focus.track(page, "osc-$it") }, onPick = a.onOsc)
|
||||
}
|
||||
a.oscRearButtons?.let { rearButtons ->
|
||||
ToggleRow(host, "osc-rear-buttons", stringResource(R.string.osc_rear_buttons), null, rearButtons,
|
||||
chipModifier = focus.track(page, "osc-rear-buttons"), onChange = a.onOscRearButtons)
|
||||
ToggleRow(host, "osc-trackpads", stringResource(R.string.osc_trackpads), null, a.oscTrackpads,
|
||||
chipModifier = focus.track(page, "osc-trackpads"), onChange = a.onOscTrackpads)
|
||||
}
|
||||
ChoiceRow(host, "touch", stringResource(R.string.input_touches), null,
|
||||
listOf(SessionPrefs.TOUCH_AUTO to stringResource(R.string.drawer_touch_auto, a.touchAuto), SessionPrefs.TOUCH_DIRECT to stringResource(R.string.mode_touch_mouse),
|
||||
SessionPrefs.TOUCH_PAD to stringResource(R.string.mode_touch_touchpad), SessionPrefs.TOUCH_GESTURES to stringResource(R.string.mode_touch_gestures),
|
||||
@@ -1560,12 +1548,15 @@ private fun ComponentsDrawerPage(host: MenuHost, a: DrawerActions, track: (Strin
|
||||
chipModifier = track("cmp-proton"),
|
||||
onPick = { id -> a.onGameProton(gameProfile.appId, id) },
|
||||
)
|
||||
val gameTool = snap.protons.firstOrNull { it.proton.id == gameProfile.protonId }?.proton?.dir?.name
|
||||
for (comp in ComponentsManager.COMPONENTS) {
|
||||
val value = gameProfile.components.getValue(comp)
|
||||
val managedDxvk = ComponentsManager.runtimeManaged(comp, a.systemPowerVr)
|
||||
val options: List<Pair<String?, String>> =
|
||||
listOf(null to stringResource(R.string.comp_game_use_general)) +
|
||||
if (managedDxvk) emptyList() else snap.packages.filter { it.comp == comp }.map { it.file to it.version }
|
||||
if (managedDxvk) emptyList() else ComponentsManager.forTool(
|
||||
comp, gameTool, snap.packages.filter { it.comp == comp }, gameProfile.componentFiles[comp],
|
||||
) { it.file }.map { it.file to it.version }
|
||||
DrawerStackedChoice(
|
||||
host = host,
|
||||
key = "game-cmp-$comp",
|
||||
@@ -1648,7 +1639,7 @@ private fun ComponentsDrawerPage(host: MenuHost, a: DrawerActions, track: (Strin
|
||||
val managedDxvk = ComponentsManager.runtimeManaged(comp, a.systemPowerVr)
|
||||
val originals = view.originals.filter { it.comp == comp }
|
||||
val options = originals.map { "orig:${it.protonVersion}" to (if (it.protonVersion == build) originalLabel else stringResource(R.string.comp_original, it.protonVersion)) } +
|
||||
snap.packages.filter { it.comp == comp }.map { it.file to it.version }
|
||||
ComponentsManager.forTool(comp, p.dir.name, snap.packages.filter { it.comp == comp }, st.activeFile) { it.file }.map { it.file to it.version }
|
||||
if (options.isEmpty() && !managedDxvk) continue
|
||||
val current = st.activeFile ?: "orig:$build"
|
||||
val shown = options.firstOrNull { it.first == current }?.second
|
||||
|
||||
@@ -326,17 +326,10 @@
|
||||
<string name="mode_osc_note">Auto shows the controls when no controller is connected.</string>
|
||||
<string name="osc_group_for">On-screen controls · %1$s</string>
|
||||
<string name="osc_layout">Layout</string>
|
||||
<string name="osc_layout_gamepad">DroidDeck controls</string>
|
||||
<string name="osc_layout_gamepad_detail">Works in every game. Edit them here.</string>
|
||||
<string name="osc_layout_steam">Steam touch controls</string>
|
||||
<string name="osc_layout_steam_detail">Each game\'s touch controls from Steam. Steam games only; edit them in Steam.</string>
|
||||
<string name="osc_layout_steam_unavailable">Steam touch controls only work in games launched through Steam, so these are shown instead.</string>
|
||||
<string name="osc_layout_detail_game">Just for %1$s</string>
|
||||
<string name="osc_delete_layout">Delete layout</string>
|
||||
<string name="osc_layout_gamepad">Gamepad</string>
|
||||
<string name="osc_layout_steam">Steam layout</string>
|
||||
<string name="osc_edit_layout">Edit layout</string>
|
||||
<string name="osc_show">Show</string>
|
||||
<string name="osc_rear_buttons">Rear buttons</string>
|
||||
<string name="osc_trackpads">Trackpads</string>
|
||||
<string name="osc_more">More controller settings</string>
|
||||
<string name="osc_more_detail">Shortcuts, latency and the PC keyboard</string>
|
||||
<string name="input_touches">Touches elsewhere</string>
|
||||
|
||||
@@ -89,10 +89,10 @@ class ControlsChoiceTest {
|
||||
}
|
||||
|
||||
@Test fun newIsOfferedOnlyForAGame() {
|
||||
assertTrue(ControlsChoice.options(context, null, steamMode = true).none { it.id == ControlsChoice.NEW })
|
||||
val last = ControlsChoice.options(context, 7, steamMode = true, gameName = "Castle Crashers").last()
|
||||
assertEquals(ControlsChoice.NEW to context.getString(R.string.osc_layout_new_for, "Castle Crashers"), last.id to last.name)
|
||||
assertEquals(listOf(InputLibraries.OVERLAY, GameControls.STEAM), ControlsChoice.options(context, null, steamMode = true).map { it.id })
|
||||
assertTrue(ControlsChoice.options(context, null, steamMode = true).none { it.first == ControlsChoice.NEW })
|
||||
assertEquals(ControlsChoice.NEW to context.getString(R.string.osc_layout_new_for, "Castle Crashers"),
|
||||
ControlsChoice.options(context, 7, steamMode = true, gameName = "Castle Crashers").last())
|
||||
assertEquals(listOf(InputLibraries.OVERLAY, GameControls.STEAM), ControlsChoice.options(context, null, steamMode = true).map { it.first }.take(2))
|
||||
}
|
||||
|
||||
@Test fun newForTheGameInTheControllerPageCopiesTheLayoutAndOpensTheEditorOnIt() {
|
||||
@@ -101,8 +101,8 @@ class ControlsChoiceTest {
|
||||
ReflectionHelpers.getField<MutableState<Long?>>(activity, "frameGenActiveGameId\$delegate").value = 77L
|
||||
ReflectionHelpers.getField<MutableState<String?>>(activity, "frameGenActiveGameName\$delegate").value = "Castle Crashers"
|
||||
ReflectionHelpers.callInstanceMethod<Any?>(activity, "refreshInputProfile")
|
||||
val options = ReflectionHelpers.getField<MutableState<List<ControlsChoice.Option>>>(activity, "layoutOptions\$delegate").value
|
||||
assertEquals(ControlsChoice.NEW to "+ New for Castle Crashers", options.last().let { it.id to it.name })
|
||||
val options = ReflectionHelpers.getField<MutableState<List<Pair<String, String>>>>(activity, "layoutOptions\$delegate").value
|
||||
assertEquals(ControlsChoice.NEW to "+ New for Castle Crashers", options.last())
|
||||
ReflectionHelpers.callInstanceMethod<Any?>(activity, "chooseLayout", ReflectionHelpers.ClassParameter.from(String::class.java, ControlsChoice.NEW))
|
||||
val editor = ReflectionHelpers.getField<MutableState<Triple<String, String, String>?>>(activity, "layoutEditor\$delegate").value!!
|
||||
assertEquals(GameControls.bindings(activity, 77), editor.third)
|
||||
@@ -115,87 +115,11 @@ class ControlsChoiceTest {
|
||||
}
|
||||
|
||||
@Test fun aGameWithItsOwnLayoutCanGoBackToTheDefault() {
|
||||
assertTrue(ControlsChoice.options(context, 42L, steamMode = true, gameName = "Game").none { it.id == ControlsChoice.DEFAULT })
|
||||
assertTrue(ControlsChoice.options(context, 42L, steamMode = true, gameName = "Game").none { it.first == ControlsChoice.DEFAULT })
|
||||
ControlsChoice.newForGame(context, 42L, "Game", desktop = false)
|
||||
assertTrue(ControlsChoice.options(context, 42L, steamMode = true, gameName = "Game").first().id == ControlsChoice.DEFAULT)
|
||||
assertTrue(ControlsChoice.options(context, 42L, steamMode = true, gameName = "Game").first().first == ControlsChoice.DEFAULT)
|
||||
ControlsChoice.choose(context, 42L, ControlsChoice.DEFAULT, desktop = false)
|
||||
assertFalse(ControlsChoice.hasOwn(context, 42L))
|
||||
assertTrue(ControlsChoice.options(context, 42L, steamMode = true, gameName = "Game").none { it.id == ControlsChoice.DEFAULT })
|
||||
}
|
||||
|
||||
@Test fun aLayoutMadeForOneGameIsListedOnlyForThatGame() {
|
||||
val (layoutId, _) = ControlsChoice.newForGame(context, 7, "Castle Crashers", desktop = false)
|
||||
val mine = ControlsChoice.options(context, 7, steamMode = true, gameName = "Castle Crashers").first { it.id == layoutId }
|
||||
assertEquals(context.getString(R.string.osc_layout_detail_game, "Castle Crashers"), mine.detail)
|
||||
assertFalse(mine.deletable)
|
||||
assertTrue(ControlsChoice.options(context, 8, steamMode = true, gameName = "Portal").none { it.id == layoutId })
|
||||
assertTrue(ControlsChoice.options(context, null, steamMode = true).none { it.id == layoutId })
|
||||
ControlsChoice.useDefault(context, 7)
|
||||
assertTrue(ControlsChoice.options(context, 8, steamMode = true, gameName = "Portal").none { it.id == layoutId })
|
||||
assertTrue(ControlsChoice.options(context, 7, steamMode = true, gameName = "Castle Crashers").first { it.id == layoutId }.deletable)
|
||||
}
|
||||
|
||||
@Test fun anUnusedLayoutCanBeDeletedButNotOneInUse() {
|
||||
val source = bigSticks()
|
||||
assertTrue(ControlsChoice.options(context, null, steamMode = true).first { it.id == source }.deletable)
|
||||
ControlsChoice.choose(context, null, source, desktop = false)
|
||||
assertFalse(ControlsChoice.options(context, null, steamMode = true).first { it.id == source }.deletable)
|
||||
ControlsChoice.choose(context, null, InputLibraries.OVERLAY, desktop = false)
|
||||
ControlsChoice.choose(context, 7, source, desktop = false, gameName = "Castle Crashers")
|
||||
assertFalse(ControlsChoice.options(context, null, steamMode = true).first { it.id == source }.deletable)
|
||||
assertNull(ControlsChoice.options(context, 8, steamMode = true, gameName = "Portal").first { it.id == source }.detail)
|
||||
ControlsChoice.useDefault(context, 7)
|
||||
ControlsChoice.delete(context, source)
|
||||
val library = InputLibraries.read(context)
|
||||
assertTrue(library.layouts.none { it.id == source })
|
||||
assertTrue(library.bindings.none { it.layoutId == source })
|
||||
assertTrue(ControlsChoice.options(context, null, steamMode = true).none { it.id == source })
|
||||
}
|
||||
|
||||
@Test fun deletingALayoutAlsoRemovesAProfileThatCanNoLongerBeChosen() {
|
||||
InputLibraries.update(context) { it.duplicateProfile(InputProfile.GAME, "Game2") }
|
||||
val profile = InputLibraries.read(context).profiles.first { it.name == "Game2" }
|
||||
val layout = InputLibraries.read(context).layout(profile.id, InputRole.PRIMARY)!!
|
||||
assertEquals("Game2 / primary", layout.name)
|
||||
assertTrue(ControlsChoice.options(context, null, steamMode = true).first { it.id == layout.id }.deletable)
|
||||
ControlsChoice.delete(context, layout.id)
|
||||
val library = InputLibraries.read(context)
|
||||
assertTrue(library.profiles.none { it.id == profile.id })
|
||||
assertTrue(library.layouts.none { it.id == layout.id })
|
||||
assertTrue(profile.parts.values.none { part -> library.bindings.any { it.id == part.bindings } })
|
||||
assertEquals(InputLibraries.OVERLAY, ControlsChoice.current(context, null, steamMode = true))
|
||||
}
|
||||
|
||||
@Test fun steamTouchSavedForAGameFallsBackOutsideSteamWithANote() {
|
||||
ControlsChoice.choose(context, 7, GameControls.STEAM, desktop = false, gameName = "Portal")
|
||||
assertEquals(GameControls.STEAM, ControlsChoice.current(context, 7, steamMode = true))
|
||||
assertFalse(ControlsChoice.steamUnavailable(context, 7, steamMode = true))
|
||||
assertEquals(InputLibraries.OVERLAY, ControlsChoice.current(context, 7, steamMode = false))
|
||||
assertTrue(ControlsChoice.steamUnavailable(context, 7, steamMode = false))
|
||||
assertFalse(ControlsChoice.steamUnavailable(context, 8, steamMode = false))
|
||||
assertTrue(ControlsChoice.options(context, 7, steamMode = false, gameName = "Portal").none { it.id == GameControls.STEAM })
|
||||
}
|
||||
|
||||
@Test fun aLayoutNamedAfterTheGameThatDrawsItCountsAsThatGamesOwn() {
|
||||
val source = bigSticks()
|
||||
InputLibraries.update(context) { it.withLayout(it.layouts.first { l -> l.id == source }.copy(name = "ARMSX1")) }
|
||||
ControlsChoice.choose(context, 7, source, desktop = false, gameName = "ARMSX1")
|
||||
assertTrue(ControlsChoice.options(context, 8, steamMode = true, gameName = "Portal").none { it.id == source })
|
||||
assertEquals(context.getString(R.string.osc_layout_detail_game, "ARMSX1"),
|
||||
ControlsChoice.options(context, 7, steamMode = true, gameName = "ARMSX1").first { it.id == source }.detail)
|
||||
}
|
||||
|
||||
@Test fun aLayoutTheGameProfileStillListsCanBeDeletedOnceAnotherIsChosen() {
|
||||
val source = bigSticks()
|
||||
InputLibraries.update(context) { it.chooseLayout(InputProfile.GAME, InputRole.PRIMARY, source) }
|
||||
assertEquals(source, ControlsChoice.current(context, null, steamMode = true))
|
||||
assertFalse(ControlsChoice.options(context, null, steamMode = true).first { it.id == source }.deletable)
|
||||
ControlsChoice.choose(context, null, InputLibraries.OVERLAY, desktop = false)
|
||||
assertTrue(ControlsChoice.options(context, null, steamMode = true).first { it.id == source }.deletable)
|
||||
ControlsChoice.delete(context, source)
|
||||
val library = InputLibraries.read(context)
|
||||
assertTrue(library.layouts.none { it.id == source })
|
||||
assertEquals(InputLibraries.OVERLAY, library.profile(InputProfile.GAME).parts.getValue(InputRole.PRIMARY).layout)
|
||||
assertEquals(InputLibraries.OVERLAY, ControlsChoice.current(context, null, steamMode = true))
|
||||
assertTrue(ControlsChoice.options(context, 42L, steamMode = true, gameName = "Game").none { it.first == ControlsChoice.DEFAULT })
|
||||
}
|
||||
}
|
||||
@@ -113,56 +113,6 @@ class KitLayoutTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun aSideCutoutOnlyMovesTheOverlappingCluster() {
|
||||
val w = 2400
|
||||
val h = 1080
|
||||
val plain = KitLayout.elements(context, PadKit.STEAM_DECK, w, h, rearButtons = false, trackpads = false)
|
||||
val left = Rect(10, 380, 120, 480)
|
||||
val right = Rect(w - 120, 380, w, 480)
|
||||
val adjusted = KitLayout.elements(context, PadKit.STEAM_DECK, w, h, Rect(120, 0, 120, 0),
|
||||
cutouts = listOf(left, right), rearButtons = false, trackpads = false)
|
||||
val face = setOf("legacy:a", "legacy:b", "legacy:x", "legacy:y")
|
||||
val xOffsets = plain.zip(adjusted).associate { (before, after) ->
|
||||
assertEquals(before.id, after.id)
|
||||
assertEquals(before.y, after.y, .00001f)
|
||||
assertEquals(before.width, after.width, .00001f)
|
||||
assertEquals(before.height, after.height, .00001f)
|
||||
assertTrue(after.x * w >= left.right || (after.x + after.width) * w <= left.left ||
|
||||
after.y * h >= left.bottom || (after.y + after.height) * h <= left.top)
|
||||
assertTrue(after.x * w >= right.right || (after.x + after.width) * w <= right.left ||
|
||||
after.y * h >= right.bottom || (after.y + after.height) * h <= right.top)
|
||||
before.id to (after.x - before.x) * w
|
||||
}
|
||||
assertTrue(xOffsets.getValue(KitLayout.DPAD_ID) in 1f..100f)
|
||||
assertTrue(xOffsets.getValue("legacy:b") in -100f..-1f)
|
||||
for ((id, offset) in xOffsets) if (id in face) assertEquals(xOffsets.getValue("legacy:b"), offset, .01f)
|
||||
else if (id != KitLayout.DPAD_ID) assertEquals(id, 0f, offset, .01f)
|
||||
assertTrue(overlapping(adjusted, w, h).isEmpty())
|
||||
}
|
||||
|
||||
@Test fun aCutoutShiftDoesNotCoverAnAddedControl() {
|
||||
val w = 2400
|
||||
val h = 1080
|
||||
val safe = Rect(120, 0, 0, 0)
|
||||
val extra = InputSurfaceElement(InputControl.B, .05f, .4f, .025f, .06f, id = "added")
|
||||
val layout = SavedInputLayout(InputLibraries.OVERLAY, "Gamepad", listOf(extra), aspect = w.toFloat() / h)
|
||||
val fallback = OnScreenLayout.elements(context, layout, w, h, safe, rearButtons = false, trackpads = false)
|
||||
val placed = OnScreenLayout.elements(context, layout, w, h, safe, cutouts = listOf(Rect(0, 380, 120, 480)),
|
||||
rearButtons = false, trackpads = false)
|
||||
assertEquals(fallback, placed)
|
||||
assertTrue(overlapping(placed, w, h).isEmpty())
|
||||
}
|
||||
|
||||
@Test fun startAndSelectAreOnTheFloatingOverlayBottomRow() {
|
||||
for (kit in PadKit.entries) for ((w, h) in sizes) {
|
||||
val buttons = KitLayout.elements(context, kit, w, h)
|
||||
val keyboard = buttons.single { it.id == KitLayout.KEYBOARD_ID }
|
||||
for (button in buttons.filter { it.control == InputControl.SELECT || it.control == InputControl.START }) {
|
||||
assertTrue("$kit $w x $h ${button.id}", button.y + button.height / 2 in keyboard.y..(keyboard.y + keyboard.height))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun widerScreensSpreadTheControlsInsteadOfStretchingThem() {
|
||||
for (kit in PadKit.entries) {
|
||||
val narrow = KitLayout.elements(context, kit, 1920, 1080).associateBy { it.id }
|
||||
|
||||
@@ -32,36 +32,6 @@ class ShowLayoutTest {
|
||||
view.releaseInputs()
|
||||
}
|
||||
|
||||
@Test fun overlayExtrasAreIndependentAndKeepTheirPreferencesWhenRecreated() {
|
||||
SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_DECK)
|
||||
val kit = SavedInputLayout(InputLibraries.OVERLAY, "Gamepad")
|
||||
val grips = setOf(InputControl.L4, InputControl.L5, InputControl.R4, InputControl.R5)
|
||||
val trackpads = setOf(InputControl.LEFT_PAD, InputControl.RIGHT_PAD)
|
||||
fun controls(dock: OnScreenLayout.Dock? = null, layout: SavedInputLayout = kit): OnScreenControls =
|
||||
OnScreenControls(context, null, dock).also { it.updateLayout(layout); sized(it, 1920, 1080) }
|
||||
fun shown(view: OnScreenControls) = view.inputSurface.shownElements.map { it.control }.toSet()
|
||||
val overlay = controls()
|
||||
assertTrue(shown(overlay).intersect(grips + trackpads).isEmpty())
|
||||
SessionPrefs.setOscRearButtons(context, true)
|
||||
overlay.reload()
|
||||
assertTrue(shown(overlay).containsAll(grips))
|
||||
assertTrue(shown(overlay).intersect(trackpads).isEmpty())
|
||||
SessionPrefs.setOscTrackpads(context, true)
|
||||
SessionPrefs.setOscRearButtons(context, false)
|
||||
assertTrue(shown(controls()).containsAll(trackpads))
|
||||
assertTrue(shown(controls()).intersect(grips).isEmpty())
|
||||
|
||||
SessionPrefs.setOscTrackpads(context, false)
|
||||
val customPad = InputSurfaceElement(InputControl.LEFT_PAD, .4f, .4f, .15f, .15f, id = "custom-pad")
|
||||
val edited = kit.copy(elements = listOf(customPad,
|
||||
InputSurfaceElement(InputControl.RIGHT_PAD, .6f, .4f, .15f, .15f, id = "legacy:right-pad")))
|
||||
assertEquals(listOf(customPad.id), controls(layout = edited).inputSurface.shownElements.map { it.id })
|
||||
|
||||
val dock = OnScreenLayout.Dock(portrait = true, grips = true)
|
||||
val panel = OnScreenControls(context, null, dock).also { it.updateLayout(kit); sized(it, 1080, 1300) }
|
||||
assertTrue(shown(panel).containsAll(grips + trackpads))
|
||||
}
|
||||
|
||||
@Test fun aSavedLayoutIsDrawnAsSaved() {
|
||||
val saved = listOf(InputSurfaceElement(InputControl.A, .4f, .4f, .1f, .1f))
|
||||
val view = InputSurfaceView(context)
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import org.json.JSONObject
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.annotation.Config
|
||||
import java.io.File
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [28], manifest = Config.NONE)
|
||||
class ComponentsBionicFexTest {
|
||||
private val bionicTool = "DroidDeck-Bionic-12.8-r24"
|
||||
private val ownTool = "DroidDeck-Proton-11-12.8"
|
||||
|
||||
private fun proton(dir: String, valve: Boolean = false) =
|
||||
ComponentsManager.Proton(dir, dir, File("/steam/compatibilitytools.d/$dir"), "/p/$dir", "$dir-1", valve)
|
||||
|
||||
private fun item(file: String, release: String) = ComponentsManager.CatalogItem(file, "fex", release, "", 1, "")
|
||||
|
||||
@Test fun onlyBionicNamedPackagesFitDroidDeckBionic() {
|
||||
assertTrue(ComponentsManager.bionicFex("FEXCore-2611.1-bionic.wcp"))
|
||||
assertTrue(ComponentsManager.bionicFex("FEXCore-2611.1-PPA-BIONIC.WCP"))
|
||||
assertFalse(ComponentsManager.bionicFex("FEXCore-2611.1-linux.wcp"))
|
||||
assertFalse(ComponentsManager.bionicFex("DD-FEXCore-2611+51-nightly.wcp"))
|
||||
assertFalse(ComponentsManager.bionicFex("bionic-FEXCore-2611.wcp"))
|
||||
assertTrue(ComponentsManager.bionicTool(bionicTool))
|
||||
assertFalse(ComponentsManager.bionicTool(ownTool))
|
||||
assertFalse(ComponentsManager.bionicTool("GE-Proton10-25"))
|
||||
assertFalse(ComponentsManager.bionicTool(null))
|
||||
assertTrue(ComponentsManager.fexFits(bionicTool, "FEXCore-2611-bionic.wcp"))
|
||||
assertFalse(ComponentsManager.fexFits(bionicTool, "FEXCore-2611-linux.wcp"))
|
||||
assertFalse(ComponentsManager.fexFits(bionicTool, "DD-FEXCore-2611+51-nightly.wcp"))
|
||||
assertTrue(ComponentsManager.fexFits(ownTool, "DD-FEXCore-2611+51-nightly.wcp"))
|
||||
assertTrue(ComponentsManager.fexFits(ownTool, "FEXCore-2611-linux.wcp"))
|
||||
assertFalse(ComponentsManager.fexFits(ownTool, "FEXCore-2611-bionic.wcp"))
|
||||
assertFalse(ComponentsManager.fexFits(null, "FEXCore-2611-bionic.wcp"))
|
||||
}
|
||||
|
||||
@Test fun aTwinSwapsTheLinuxAndBionicEnding() {
|
||||
assertEquals("FEXCore-2611.1-bionic.wcp", ComponentsManager.fexTwin("FEXCore-2611.1-linux.wcp"))
|
||||
assertEquals("FEXCore-2611.1-linux.wcp", ComponentsManager.fexTwin("FEXCore-2611.1-bionic.wcp"))
|
||||
assertEquals("FEXCore-2611-PPA-bionic.wcp", ComponentsManager.fexTwin("FEXCore-2611-PPA-linux.wcp"))
|
||||
assertNull(ComponentsManager.fexTwin("DD-FEXCore-2611+51-nightly.wcp"))
|
||||
assertNull(ComponentsManager.fexTwin("my-fex.wcp"))
|
||||
}
|
||||
|
||||
@Test fun aLaunchTakesTheChoiceOrItsStoredTwinForEachFlavor() {
|
||||
val stored = setOf("FEXCore-2611.1-linux.wcp", "FEXCore-2611.1-bionic.wcp", "FEXCore-2610-linux.wcp")
|
||||
val has: (String) -> Boolean = { it in stored }
|
||||
assertEquals("FEXCore-2611.1-bionic.wcp", ComponentsManager.launchFex(bionicTool, "FEXCore-2611.1-linux.wcp", has))
|
||||
assertEquals("FEXCore-2611.1-bionic.wcp", ComponentsManager.launchFex(bionicTool, "FEXCore-2611.1-bionic.wcp", has))
|
||||
assertEquals("FEXCore-2611.1-linux.wcp", ComponentsManager.launchFex(ownTool, "FEXCore-2611.1-bionic.wcp", has))
|
||||
assertEquals("FEXCore-2610-linux.wcp", ComponentsManager.launchFex(ownTool, "FEXCore-2610-linux.wcp", has))
|
||||
assertEquals("DD-FEXCore-2611+51-nightly.wcp", ComponentsManager.launchFex(ownTool, "DD-FEXCore-2611+51-nightly.wcp", has))
|
||||
assertNull(ComponentsManager.launchFex(bionicTool, "FEXCore-2610-linux.wcp", has))
|
||||
assertNull(ComponentsManager.launchFex(bionicTool, "DD-FEXCore-2611+51-nightly.wcp", has))
|
||||
}
|
||||
|
||||
@Test fun fexListsShowTheProtonsFlavorAndTheCurrentChoice() {
|
||||
val files = listOf("FEXCore-2611.1-linux.wcp", "FEXCore-2611.1-bionic.wcp", "DD-FEXCore-2611+51-nightly.wcp", "FEXCore-2610-bionic.wcp")
|
||||
assertEquals(listOf("FEXCore-2611.1-bionic.wcp", "FEXCore-2610-bionic.wcp"), ComponentsManager.forTool("fex", bionicTool, files) { it })
|
||||
assertEquals(listOf("FEXCore-2611.1-linux.wcp", "DD-FEXCore-2611+51-nightly.wcp"), ComponentsManager.forTool("fex", ownTool, files) { it })
|
||||
assertEquals(listOf("FEXCore-2611.1-linux.wcp", "DD-FEXCore-2611+51-nightly.wcp"), ComponentsManager.forTool("fex", null, files) { it })
|
||||
assertEquals(listOf("FEXCore-2611.1-linux.wcp", "FEXCore-2611.1-bionic.wcp", "FEXCore-2610-bionic.wcp"),
|
||||
ComponentsManager.forTool("fex", bionicTool, files, selected = "FEXCore-2611.1-linux.wcp") { it })
|
||||
assertEquals(files, ComponentsManager.forTool("dxvk", bionicTool, files) { it })
|
||||
}
|
||||
|
||||
@Test fun bionicStableAssetsAreFex() {
|
||||
assertEquals("fex", ComponentsManager.assetComp(ComponentsManager.DD_BIONIC, "FEXCore-2611.1-bionic.wcp"))
|
||||
assertEquals("fex", ComponentsManager.assetComp(ComponentsManager.DD_BIONIC, "FEXCore-2610-PPA-bionic.wcp"))
|
||||
assertEquals("fex", ComponentsManager.assetComp("FexCore-Linux", "FEXCore-2611.1-linux.wcp"))
|
||||
}
|
||||
|
||||
@Test fun aGameFexChoiceKeepsItsTwinInUseWhileTheOtherFlavorIsInstalled() {
|
||||
val state = JSONObject().put("profiles", JSONObject().put("42", JSONObject().put("fex", "FEXCore-2611.1-linux.wcp")))
|
||||
assertEquals(setOf("FEXCore-2611.1-linux.wcp"), ComponentsManager.packagesInUse(state, listOf(proton(ownTool))))
|
||||
assertEquals(setOf("FEXCore-2611.1-linux.wcp", "FEXCore-2611.1-bionic.wcp"),
|
||||
ComponentsManager.packagesInUse(state, listOf(proton(ownTool), proton(bionicTool))))
|
||||
}
|
||||
|
||||
@Test fun droidDeckBionicFollowsTheNewestBionicFexAndNothingElse() {
|
||||
val bionic = proton(bionicTool)
|
||||
val own = proton(ownTool)
|
||||
assertTrue(ComponentUpdates.autoFollows(bionic, "fex"))
|
||||
assertFalse(ComponentUpdates.autoFollows(bionic, "dxvk"))
|
||||
assertFalse(ComponentUpdates.autoFollows(bionic, "vkd3d"))
|
||||
assertFalse(ComponentUpdates.autoFollows(proton(bionicTool, valve = true), "fex"))
|
||||
assertFalse(ComponentUpdates.follows(bionic))
|
||||
assertTrue(ComponentUpdates.autoFollows(own, "dxvk"))
|
||||
assertFalse(ComponentUpdates.autoFollows(proton("GE-Proton10-25"), "fex"))
|
||||
assertEquals("fex-bionic", ComponentUpdates.fexLine(bionic).key)
|
||||
assertEquals("fex", ComponentUpdates.fexLine(own).key)
|
||||
assertEquals("fex", ComponentUpdates.line("fex", false).key)
|
||||
|
||||
val catalog = listOf(
|
||||
item("DD-FEXCore-2611+51-nightly.wcp", ComponentsManager.DD_NIGHTLY),
|
||||
item("DD-FEXCore-2611+52-bionic.wcp", ComponentsManager.DD_NIGHTLY),
|
||||
item("FEXCore-2611.1-linux.wcp", "FexCore-Linux"),
|
||||
item("FEXCore-2610-bionic.wcp", ComponentsManager.DD_BIONIC),
|
||||
item("FEXCore-2611-PPA-bionic.wcp", ComponentsManager.DD_BIONIC),
|
||||
item("FEXCore-2611.1-bionic.wcp", ComponentsManager.DD_BIONIC),
|
||||
)
|
||||
assertEquals("FEXCore-2611.1-bionic.wcp", ComponentUpdates.pick(catalog, ComponentUpdates.fexLine(bionic), emptySet())?.file)
|
||||
assertNull(ComponentUpdates.pick(catalog, ComponentUpdates.fexLine(bionic), setOf("FEXCore-2611.1-bionic.wcp")))
|
||||
assertEquals("DD-FEXCore-2611+51-nightly.wcp", ComponentUpdates.pick(catalog, ComponentUpdates.fexLine(own), emptySet())?.file)
|
||||
}
|
||||
|
||||
@Test fun pruningTheBionicLineKeepsBionicPackagesTheUserDownloaded() {
|
||||
val line = ComponentUpdates.fexLine(proton(bionicTool))
|
||||
val current = "FEXCore-2611.1-bionic.wcp"
|
||||
val stored = listOf("FEXCore-2610-bionic.wcp", "FEXCore-2611-PPA-bionic.wcp", current, "FEXCore-2610-linux.wcp")
|
||||
assertEquals(listOf("FEXCore-2610-bionic.wcp"),
|
||||
ComponentUpdates.stale(line, setOf("FEXCore-2610-bionic.wcp", current), stored, setOf(current), current))
|
||||
}
|
||||
|
||||
@Test fun aBionicProtonsOwnFexChoiceIsNotHandedBack() {
|
||||
val bionic = proton(bionicTool)
|
||||
val choices = mapOf(bionic.id to mapOf(
|
||||
"fex" to ComponentsManager.Choice("FEXCore-2611.1-bionic.wcp", false, bionic.version),
|
||||
"dxvk" to ComponentsManager.Choice("DD-dxvk-3.1.1+190-nightly.wcp", false, bionic.version),
|
||||
))
|
||||
assertEquals(listOf(bionic to "dxvk"),
|
||||
ComponentUpdates.strays(listOf(bionic), choices, setOf("FEXCore-2611.1-bionic.wcp", "DD-dxvk-3.1.1+190-nightly.wcp")))
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream
|
||||
import org.json.JSONObject
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertThrows
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
@@ -23,6 +24,7 @@ class ComponentsRepublishTest {
|
||||
private val fex = "FEXCore-2610-d2rfix28-linux.wcp"
|
||||
private val scope = "2596113170"
|
||||
private val dll = "files/lib/wine/aarch64-windows/libwow64fex.dll"
|
||||
private val so = "files/lib/wine/aarch64-unix/libwow64fex.so"
|
||||
private lateinit var context: Context
|
||||
|
||||
@Before fun setUp() {
|
||||
@@ -48,6 +50,61 @@ class ComponentsRepublishTest {
|
||||
assertEquals(fex, ComponentsManager.gameComponents(context, scope)["fex"])
|
||||
}
|
||||
|
||||
@Test fun aGlibcGameFexChoiceWithoutItsTwinLeavesDroidDeckBionicOnItsOwnFex() {
|
||||
proton("DroidDeck-Proton 11-12.8", "DroidDeck-Proton-11-12.8")
|
||||
proton("DroidDeck-Bionic-12.8-r6", "DroidDeck-Bionic-12.8-r6")
|
||||
packageFile()
|
||||
ComponentsManager.setGameComponent(context, scope, "fex", fex) { false }
|
||||
assertEquals(setOf("DroidDeck-Proton 11-12.8"), scopedTools())
|
||||
val bionic = rows().filter { it[1] == "DroidDeck-Bionic-12.8-r6" && it[3] == "fex" }
|
||||
assertTrue(bionic.isNotEmpty())
|
||||
assertTrue(bionic.all { it[0] == "*" && "/store/original-DroidDeck-Bionic-12.8-r6-" in it[6] })
|
||||
}
|
||||
|
||||
@Test fun aGameFexChoiceReachesEachProtonAsTheBuildOfItsFlavor() {
|
||||
proton("DroidDeck-Proton-11-12.8", "DroidDeck-Proton-11-12.8")
|
||||
proton("DroidDeck-Bionic-12.8-r24", "DroidDeck-Bionic-12.8-r24")
|
||||
val linux = "FEXCore-2611.1-linux.wcp"
|
||||
val bionic = "FEXCore-2611.1-bionic.wcp"
|
||||
packageFile(linux, "FEXCore-Linux", "glibc wow64")
|
||||
packageFile(bionic, "FEXCore-Bionic", "android wow64")
|
||||
|
||||
for (choice in listOf(linux, bionic)) {
|
||||
ComponentsManager.setGameComponent(context, scope, "fex", choice) { false }
|
||||
val scoped = rows().filter { it[0] == scope && it[3] == "fex" }
|
||||
val own = scoped.single { it[1] == "DroidDeck-Proton-11-12.8" && it[4] == dll }
|
||||
val android = scoped.single { it[1] == "DroidDeck-Bionic-12.8-r24" && it[4] == dll }
|
||||
assertEquals("glibc wow64", File(LinuxRuntime.rootDir(context), own[6].removePrefix("/")).readText())
|
||||
assertEquals("android wow64", File(LinuxRuntime.rootDir(context), android[6].removePrefix("/")).readText())
|
||||
assertTrue(scoped.any { it[1] == "DroidDeck-Proton-11-12.8" && it[6] == "-" })
|
||||
assertTrue(scoped.none { it[1] == "DroidDeck-Bionic-12.8-r24" && it[6] == "-" })
|
||||
assertEquals(choice, ComponentsManager.gameComponents(context, scope)["fex"])
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun aProtonsFexIsOnlyEverSwappedToABuildOfItsFlavor() {
|
||||
proton("DroidDeck-Proton-11-12.8", "DroidDeck-Proton-11-12.8")
|
||||
proton("DroidDeck-Bionic-12.8-r24", "DroidDeck-Bionic-12.8-r24")
|
||||
val linux = "FEXCore-2611.1-linux.wcp"
|
||||
val bionic = "FEXCore-2611.1-bionic.wcp"
|
||||
packageFile(linux, "FEXCore-Linux", "glibc wow64")
|
||||
packageFile(bionic, "FEXCore-Bionic", "android wow64")
|
||||
val bionicDll = File(protonDir("DroidDeck-Bionic-12.8-r24"), dll)
|
||||
val ownDll = File(protonDir("DroidDeck-Proton-11-12.8"), dll)
|
||||
|
||||
assertThrows(IllegalStateException::class.java) { ComponentsManager.swap(context, "DroidDeck-Bionic-12.8-r24", linux) }
|
||||
assertThrows(IllegalStateException::class.java) { ComponentsManager.swap(context, "DroidDeck-Proton-11-12.8", bionic) }
|
||||
assertEquals("bundled FEX DroidDeck-Bionic-12.8-r24", bionicDll.readText())
|
||||
assertEquals("bundled FEX DroidDeck-Proton-11-12.8", ownDll.readText())
|
||||
|
||||
ComponentsManager.swap(context, "DroidDeck-Bionic-12.8-r24", bionic)
|
||||
ComponentsManager.swap(context, "DroidDeck-Proton-11-12.8", linux)
|
||||
assertEquals("android wow64", bionicDll.readText())
|
||||
assertEquals("glibc wow64", ownDll.readText())
|
||||
assertTrue(File(protonDir("DroidDeck-Bionic-12.8-r24"), so).isFile)
|
||||
assertTrue(rows().none { it[1] == "DroidDeck-Bionic-12.8-r24" && it[3] == "fex" && it[6] == "-" })
|
||||
}
|
||||
|
||||
@Test fun nothingIsRewrittenWhileTheToolsAreUnchanged() {
|
||||
proton("DroidDeck-Proton 11-11.8", "DroidDeck-Proton-11-11.8")
|
||||
packageFile()
|
||||
@@ -86,18 +143,21 @@ class ComponentsRepublishTest {
|
||||
|
||||
private fun launchState() = File(LinuxRuntime.rootDir(context), "root/.local/share/droiddeck-components/desired.tsv")
|
||||
|
||||
private fun protonDir(name: String) = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/steamapps/common/$name")
|
||||
|
||||
private fun proton(name: String, version: String) {
|
||||
val dir = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/steamapps/common/$name")
|
||||
val dir = protonDir(name)
|
||||
File(dir, "files/lib/wine").mkdirs()
|
||||
File(dir, "proton").writeText("#!/bin/sh\n")
|
||||
File(dir, "version").writeText("1 $version\n")
|
||||
File(dir, dll).apply { parentFile!!.mkdirs(); writeText("bundled FEX $version") }
|
||||
File(dir, so).apply { parentFile!!.mkdirs(); writeText("bundled unix FEX $version") }
|
||||
}
|
||||
|
||||
private fun packageFile() {
|
||||
val out = File(context.filesDir, "components/packages/$fex").apply { parentFile!!.mkdirs() }
|
||||
val profile = JSONObject().put("type", "FEXCore-Linux").put("versionName", "2610-d2rfix28").toString().toByteArray()
|
||||
val body = "d2rfix28 wow64".toByteArray()
|
||||
private fun packageFile(name: String = fex, type: String = "FEXCore-Linux", text: String = "d2rfix28 wow64") {
|
||||
val out = File(context.filesDir, "components/packages/$name").apply { parentFile!!.mkdirs() }
|
||||
val profile = JSONObject().put("type", type).put("versionName", name.removeSuffix(".wcp")).toString().toByteArray()
|
||||
val body = text.toByteArray()
|
||||
TarArchiveOutputStream(ZstdOutputStream(out.outputStream())).use { tar ->
|
||||
tar.putArchiveEntry(TarArchiveEntry("profile.json").apply { size = profile.size.toLong() })
|
||||
tar.write(profile)
|
||||
|
||||
@@ -68,6 +68,19 @@ class ExperimentalProtonsTest {
|
||||
assertEquals(listOf("pre"), ProtonExtras.assets(tool, releases, true).map { it.tag })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun bionicBuildsKeepTheirOwnRow() {
|
||||
val tool = ProtonExtras.tools.first { it.id == ProtonExtras.OWN }
|
||||
val releases = JSONArray("""
|
||||
[{"tag_name":"DroidDeck-Proton-11-12.8","prerelease":false,"published_at":"2026-11-14T00:00:00Z","assets":[{"name":"DroidDeck-Proton-11-12.8-aarch64.tar.gz","browser_download_url":"https://example/stable"}]},
|
||||
{"tag_name":"DroidDeck-Bionic-12.8-r37","prerelease":true,"published_at":"2026-11-19T00:00:00Z","assets":[{"name":"DroidDeck-Bionic-12.8-r37-aarch64.tar.xz","browser_download_url":"https://example/bionic"}]},
|
||||
{"tag_name":"DroidDeck-Proton-11-12.9-test1","prerelease":true,"published_at":"2026-11-19T01:00:00Z","assets":[{"name":"DroidDeck-Proton-11-12.9-test1-aarch64.tar.xz","browser_download_url":"https://example/test"}]}]
|
||||
""".trimIndent())
|
||||
val assets = ProtonExtras.assets(tool, releases, true)
|
||||
assertEquals(listOf("DroidDeck-Bionic-12.8-r37", "DroidDeck-Proton-11-12.9-test1"), assets.map { it.tag })
|
||||
assertEquals(listOf("DroidDeck-Proton-11-12.9-test1"), ExperimentalProtons.listed(assets).map { it.tag })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun markerRoundTripKeepsReleaseTag() {
|
||||
val dir = File(com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(activity), "root/.local/share/Steam/compatibilitytools.d/Experimental-pre").apply { mkdirs() }
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class LightPauseTest {
|
||||
@Test
|
||||
fun theBounceAloneResumesLight() {
|
||||
val pause = LightPause()
|
||||
pause.paused(bounces = 3)
|
||||
assertEquals(LightPause.Resume.LIGHT, pause.resumed(bounces = 4))
|
||||
assertFalse(pause.timedOut())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun anUnrelatedPauseWithoutABounceCleansUpAtTheTimeout() {
|
||||
val pause = LightPause()
|
||||
pause.paused(bounces = 3)
|
||||
assertTrue(pause.timedOut())
|
||||
assertEquals(LightPause.Resume.NORMAL, pause.resumed(bounces = 3))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aBounceWhileAnotherActivityHoldsThePauseStillCleansUpAtTheTimeout() {
|
||||
val pause = LightPause()
|
||||
pause.paused(bounces = 3)
|
||||
assertTrue(pause.timedOut())
|
||||
assertEquals(LightPause.Resume.NORMAL, pause.resumed(bounces = 4))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aResumeBeforeTheTimeoutWithoutABounceCleansUpFirst() {
|
||||
val pause = LightPause()
|
||||
pause.paused(bounces = 3)
|
||||
assertEquals(LightPause.Resume.CLEANUP_FIRST, pause.resumed(bounces = 3))
|
||||
assertFalse(pause.timedOut())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aStopAfterALightPauseCleansUpOnce() {
|
||||
val pause = LightPause()
|
||||
pause.paused(bounces = 3)
|
||||
assertTrue(pause.stopped())
|
||||
assertFalse(pause.timedOut())
|
||||
assertEquals(LightPause.Resume.NORMAL, pause.resumed(bounces = 4))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aNormalPauseIsUntouched() {
|
||||
val pause = LightPause()
|
||||
assertFalse(pause.stopped())
|
||||
assertEquals(LightPause.Resume.NORMAL, pause.resumed(bounces = 0))
|
||||
}
|
||||
}
|
||||
@@ -127,4 +127,90 @@ class ProtonDefaultTest {
|
||||
assertTrue(games.containsKey("43"))
|
||||
assertNull(games["43"])
|
||||
}
|
||||
|
||||
@Test
|
||||
fun anUpdateMovesTheDefaultThatNamesTheReplacedTool() {
|
||||
val bionic = """
|
||||
{"default": "DroidDeck-Bionic-12.8-r30-Proton", "applied": 7, "live": false,
|
||||
"tools": [{"name": "DroidDeck-Bionic-12.8-r30-Proton", "display": "r30", "dir": "DroidDeck-Bionic-12.8-r30", "valve": false},
|
||||
{"name": "DroidDeck-Proton-11-12.8", "display": "DD", "dir": "DroidDeck-Proton 11-12.8", "valve": false}]}
|
||||
""".trimIndent()
|
||||
val parsed = ProtonDefault.parseState(bionic)
|
||||
val from = setOf("DroidDeck-Bionic-12.8-r30")
|
||||
// applied default, no request yet
|
||||
assertEquals(ProtonDefault.Request(100, false, "DroidDeck-Bionic-12.8-r31"),
|
||||
ProtonDefault.movedDefault(parsed, null, from, "DroidDeck-Bionic-12.8-r31", 100))
|
||||
// a pending request for the replaced tool wins over the applied default and the new seq is above both
|
||||
assertEquals(ProtonDefault.Request(51, false, "DroidDeck-Bionic-12.8-r31"),
|
||||
ProtonDefault.movedDefault(parsed, ProtonDefault.Request(50, false, "DroidDeck-Bionic-12.8-r30"), from, "DroidDeck-Bionic-12.8-r31", 3))
|
||||
// a default on another tool stays as it is
|
||||
assertNull(ProtonDefault.movedDefault(parsed, ProtonDefault.Request(50, false, "DroidDeck-Proton 11-12.8"), from, "DroidDeck-Bionic-12.8-r31", 100))
|
||||
assertNull(ProtonDefault.movedDefault(ProtonDefault.parseState(state), null, from, "DroidDeck-Bionic-12.8-r31", 100))
|
||||
// an applied request (seq not above "applied") no longer decides: the applied default does
|
||||
assertEquals("DroidDeck-Bionic-12.8-r31",
|
||||
ProtonDefault.movedDefault(parsed, ProtonDefault.Request(7, false, "DroidDeck-Proton 11-12.8"), from, "DroidDeck-Bionic-12.8-r31", 1)?.dir)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aBionicDefaultOnAnotherBuildMovesToTheInstalledOne() {
|
||||
val r37 = "DroidDeck-Bionic-12.8-r37"
|
||||
val applied = ProtonDefault.parseState("""{"default": "DroidDeck-Bionic-12.8-r30-Proton", "applied": 7,
|
||||
"tools": [{"name": "DroidDeck-Bionic-12.8-r30-Proton", "display": "r30", "dir": "DroidDeck-Bionic-12.8-r30", "valve": false},
|
||||
{"name": "droiddeck-proton-arm64", "display": "Proton ARM64", "dir": "Proton Experimental (ARM64)", "valve": true}]}""")
|
||||
// the applied default is an older build
|
||||
assertEquals(ProtonDefault.Request(100, false, r37), ProtonDefault.bionicDefault(applied, null, "DroidDeck-Bionic", r37, 100))
|
||||
// the guest fell back to its own tool because the requested build was gone: the request still names it
|
||||
val fallback = ProtonDefault.parseState("""{"default": "droiddeck-proton-arm64", "applied": 50, "source": "fallback",
|
||||
"tools": [{"name": "droiddeck-proton-arm64", "display": "Proton ARM64", "dir": "Proton Experimental (ARM64)", "valve": true}]}""")
|
||||
assertEquals(ProtonDefault.Request(51, false, r37),
|
||||
ProtonDefault.bionicDefault(fallback, ProtonDefault.Request(50, false, "DroidDeck-Bionic-12.8-r24"), "DroidDeck-Bionic", r37, 3))
|
||||
// already the installed build, another tool, or a fallback the request did not cause: left as it is
|
||||
assertNull(ProtonDefault.bionicDefault(fallback, ProtonDefault.Request(50, false, r37), "DroidDeck-Bionic", r37, 3))
|
||||
assertNull(ProtonDefault.bionicDefault(fallback, ProtonDefault.Request(50, false, "DroidDeck-Proton 11-12.8"), "DroidDeck-Bionic", r37, 3))
|
||||
assertNull(ProtonDefault.bionicDefault(ProtonDefault.parseState(state), null, "DroidDeck-Bionic", r37, 100))
|
||||
val steam = ProtonDefault.parseState("""{"default": "droiddeck-proton-arm64", "applied": 50, "source": "steam",
|
||||
"tools": [{"name": "droiddeck-proton-arm64", "display": "Proton ARM64", "dir": "Proton Experimental (ARM64)", "valve": true}]}""")
|
||||
assertNull(ProtonDefault.bionicDefault(steam, ProtonDefault.Request(50, false, "DroidDeck-Bionic-12.8-r24"), "DroidDeck-Bionic", r37, 3))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun keepingBionicCurrentRewritesTheDefaultAndThePicks() {
|
||||
val context = RuntimeEnvironment.getApplication()
|
||||
val d = File(LinuxRuntime.rootDir(context), "root/.local/share/droiddeck-compat").apply { deleteRecursively(); mkdirs() }
|
||||
File(d, "state.json").writeText("""{"default": "droiddeck-proton-arm64", "applied": 9, "source": "fallback",
|
||||
"tools": [{"name": "droiddeck-proton-arm64", "display": "Proton ARM64", "dir": "Proton Experimental (ARM64)", "valve": true}]}""")
|
||||
File(d, "request.json").writeText("""{"seq": 9, "valve": false, "dir": "DroidDeck-Bionic-12.8-r24"}""")
|
||||
ProtonDefault.requestGame(context, "42", proton("DroidDeck-Bionic-12.8-r29", false))
|
||||
ProtonDefault.requestGame(context, "43", proton("DroidDeck-Proton 11-12.8", false))
|
||||
ProtonDefault.requestGame(context, "44", null)
|
||||
ProtonDefault.keepBionicCurrent(context, "DroidDeck-Bionic", "DroidDeck-Bionic-12.8-r37")
|
||||
val request = ProtonDefault.parseRequest(File(d, "request.json").readText())
|
||||
assertEquals("DroidDeck-Bionic-12.8-r37", request?.dir)
|
||||
assertTrue(request!!.seq > 9)
|
||||
val games = ProtonDefault.parseGames(File(d, "games.json").readText())
|
||||
assertEquals(ProtonDefault.GameChoice(false, "DroidDeck-Bionic-12.8-r37"), games["42"])
|
||||
assertEquals(ProtonDefault.GameChoice(false, "DroidDeck-Proton 11-12.8"), games["43"])
|
||||
assertTrue(games.containsKey("44"))
|
||||
assertNull(games["44"])
|
||||
val before = File(d, "request.json").readText() + File(d, "games.json").readText()
|
||||
ProtonDefault.keepBionicCurrent(context, "DroidDeck-Bionic", "DroidDeck-Bionic-12.8-r37")
|
||||
assertEquals(before, File(d, "request.json").readText() + File(d, "games.json").readText())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun moveDefaultRewritesTheRequestFile() {
|
||||
val context = RuntimeEnvironment.getApplication()
|
||||
val d = File(LinuxRuntime.rootDir(context), "root/.local/share/droiddeck-compat").apply { mkdirs() }
|
||||
File(d, "state.json").writeText("""{"default": "DroidDeck-Bionic-12.8-r30-Proton", "applied": 7,
|
||||
"tools": [{"name": "DroidDeck-Bionic-12.8-r30-Proton", "display": "r30", "dir": "DroidDeck-Bionic-12.8-r30", "valve": false}]}""")
|
||||
File(d, "request.json").delete()
|
||||
ProtonDefault.moveDefault(context, setOf("DroidDeck-Bionic-12.8-r30"), "DroidDeck-Bionic-12.8-r31")
|
||||
val written = ProtonDefault.parseRequest(File(d, "request.json").readText())
|
||||
assertEquals("DroidDeck-Bionic-12.8-r31", written?.dir)
|
||||
assertFalse(written!!.valve)
|
||||
assertTrue(written.seq > 7)
|
||||
val before = File(d, "request.json").readText()
|
||||
ProtonDefault.moveDefault(context, setOf("DroidDeck-Bionic-12.8-r29"), "DroidDeck-Bionic-12.8-r31")
|
||||
assertEquals(before, File(d, "request.json").readText())
|
||||
}
|
||||
}
|
||||
@@ -77,8 +77,8 @@ class ProtonExtrasTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
fun theThreeSourcesInOrder() {
|
||||
assertEquals(listOf("ge", "cachyos", "droiddeck"), ProtonExtras.tools.map { it.id })
|
||||
fun theSourcesInOrder() {
|
||||
assertEquals(listOf("ge", "cachyos", "droiddeck", "bionic"), ProtonExtras.tools.map { it.id })
|
||||
val droiddeck = tool("droiddeck")
|
||||
assertEquals("DroidDeck-Proton", droiddeck.name)
|
||||
assertEquals("DroidDeck-Proton", droiddeck.prefix)
|
||||
@@ -90,6 +90,29 @@ class ProtonExtrasTest {
|
||||
assertFalse(tool("cachyos").assetPattern.containsMatchIn("proton-cachyos-11.0-20261005-slr-x86_64.tar.xz"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun bionicAndDroidDeckProtonShareTheReleasesButNotTheirArchives() {
|
||||
val bionic = tool("bionic")
|
||||
assertEquals("DroidDeck-Bionic", bionic.prefix)
|
||||
assertEquals("Droid-Deck/DroidDeck-Proton", bionic.repo)
|
||||
assertTrue(bionic.assetPattern.containsMatchIn("DroidDeck-Bionic-12.8-r3-aarch64.tar.xz"))
|
||||
assertFalse(bionic.assetPattern.containsMatchIn("DroidDeck-Proton-11-12.8-aarch64.tar.gz"))
|
||||
assertFalse(bionic.assetPattern.containsMatchIn("DroidDeck-Bionic-12.8-r3-aarch64.sha512sum"))
|
||||
assertFalse(tool("droiddeck").assetPattern.containsMatchIn("DroidDeck-Bionic-12.8-r3-aarch64.tar.xz"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun bionicTakesItsPrereleaseAndDroidDeckProtonSkipsIt() {
|
||||
val releases = JSONArray()
|
||||
.put(release("DroidDeck-Bionic-12.8-r3", asset("DroidDeck-Bionic-12.8-r3-aarch64.sha512sum"),
|
||||
asset("DroidDeck-Bionic-12.8-r3-aarch64.tar.xz"), prerelease = true))
|
||||
.put(droiddeckRelease("11-12.8"))
|
||||
val bionic = ProtonExtras.pickAsset(tool("bionic"), releases)!!
|
||||
assertEquals("DroidDeck-Bionic-12.8-r3-aarch64.tar.xz", bionic.name)
|
||||
assertTrue(bionic.sha512!!.endsWith("DroidDeck-Bionic-12.8-r3-aarch64.sha512sum"))
|
||||
assertEquals("DroidDeck-Proton-11-12.8-aarch64.tar.gz", ProtonExtras.pickAsset(tool("droiddeck"), releases)!!.name)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun theTarballAndItsSha512FileArePicked() {
|
||||
val picked = ProtonExtras.pickAsset(tool("droiddeck"), JSONArray().put(droiddeckRelease("11-7.5")))!!
|
||||
@@ -206,6 +229,22 @@ class ProtonExtrasTest {
|
||||
assertNull(ProtonExtras.update(context, tool("droiddeck")))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun removingDeletesLinksButNeverWhatTheyPointTo() {
|
||||
val context = RuntimeEnvironment.getApplication()
|
||||
val tools = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/compatibilitytools.d")
|
||||
val outside = temp.newFolder("outside").apply { File(this, "keep.txt").writeText("x") }
|
||||
for (name in listOf("DroidDeck-Bionic-12.8-r3", "DroidDeck-Bionic-12.8-r5")) {
|
||||
val dosdevices = File(installTool(tools, name), "files/default_pfx/dosdevices").apply { mkdirs() }
|
||||
java.nio.file.Files.createSymbolicLink(File(dosdevices, "z:").toPath(), outside.toPath())
|
||||
}
|
||||
ProtonExtras.removeOlder(context, tool("bionic"))
|
||||
ProtonExtras.remove(context, tool("bionic"), "DroidDeck-Bionic-12.8-r5")
|
||||
assertFalse(File(tools, "DroidDeck-Bionic-12.8-r3").exists())
|
||||
assertFalse(File(tools, "DroidDeck-Bionic-12.8-r5").exists())
|
||||
assertTrue(File(outside, "keep.txt").isFile)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun removingDeletesOneBuildOrEveryOlderOne() {
|
||||
val context = RuntimeEnvironment.getApplication()
|
||||
|
||||
@@ -88,17 +88,4 @@ class SteamGameProcessTest {
|
||||
process("301", "reaper", "SteamLaunch", "AppId=351710", "--", "proton", "waitforexitandrun", "game.exe")
|
||||
assertTrue(SteamGameProcess.running("351710", proc))
|
||||
}
|
||||
|
||||
@Test fun onlyTheRunningCurrentGameCountsAsAlreadyRunning() {
|
||||
val proc = tmp.newFolder("proc-relaunch")
|
||||
File(proc, "200").apply { mkdirs() }.resolve("cmdline")
|
||||
.writeBytes(cmdline("reaper", "SteamLaunch", "AppId=584400", "--", "proton", "waitforexitandrun", "SonicMania.exe"))
|
||||
assertTrue(SteamGameProcess.alreadyRunning("584400", "584400", proc))
|
||||
assertFalse(SteamGameProcess.alreadyRunning("584400", "311340", proc))
|
||||
assertFalse(SteamGameProcess.alreadyRunning("311340", "311340", proc))
|
||||
assertFalse(SteamGameProcess.alreadyRunning("584400", null, proc))
|
||||
val shortcutId = ((584400uL shl 32) or 0x02000000uL).toString()
|
||||
assertTrue(SteamGameProcess.alreadyRunning(shortcutId, "584400", proc))
|
||||
assertTrue(SteamGameProcess.alreadyRunning("584400", shortcutId, proc))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.content.ComponentCallbacks2
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class TopUnderPressureTest {
|
||||
@Test
|
||||
fun onlyRunningLevelsCountAsPressure() {
|
||||
assertTrue(TopUnderPressure.isPressure(ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL))
|
||||
assertTrue(TopUnderPressure.isPressure(ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW))
|
||||
assertFalse(TopUnderPressure.isPressure(ComponentCallbacks2.TRIM_MEMORY_RUNNING_MODERATE))
|
||||
assertFalse(TopUnderPressure.isPressure(ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun reclaimsOnlyDuringASessionShortlyAfterPressure() {
|
||||
assertTrue(TopUnderPressure.shouldReclaim(10_000, 9_500, sessionRunning = true, finishing = false))
|
||||
assertFalse(TopUnderPressure.shouldReclaim(20_000, 9_500, sessionRunning = true, finishing = false))
|
||||
assertFalse(TopUnderPressure.shouldReclaim(10_000, 0, sessionRunning = true, finishing = false))
|
||||
assertFalse(TopUnderPressure.shouldReclaim(10_000, 9_500, sessionRunning = false, finishing = false))
|
||||
assertFalse(TopUnderPressure.shouldReclaim(10_000, 9_500, sessionRunning = true, finishing = true))
|
||||
}
|
||||
}
|
||||
@@ -315,15 +315,6 @@ class RockstarTest {
|
||||
assertEquals("ThirdParty/Steam/steam_api64.dll", build.files[1].path)
|
||||
}
|
||||
|
||||
@Test fun theSocialClubInstallerIsTakenFromTheLauncherBuild() {
|
||||
fun file(path: String) = RockstarFile("1", "1", path, 1, "", emptyList())
|
||||
val launcher = RockstarBuild("1", "1", false, listOf(file("Launcher.exe"),
|
||||
file("Redistributables/SocialClub/old/social-club-setup.exe"), file("Redistributables/SocialClub/Social-Club-Setup.exe")))
|
||||
assertEquals("Redistributables/SocialClub/Social-Club-Setup.exe", RockstarManifest.sdkInstaller(launcher)?.path)
|
||||
assertNull(RockstarManifest.sdkInstaller(RockstarBuild("1", "1", false, listOf(file("Launcher.exe"), file("Social-Club-Setup.exe.sig")))))
|
||||
assertEquals("Redistributables/Social-Club-Setup.exe", RockstarLaunch.SDK_INSTALLER)
|
||||
}
|
||||
|
||||
@Test fun pathsThatLeaveTheInstallAreRefused() {
|
||||
assertNull(RockstarManifest.safePath("..\\..\\Windows\\x.dll"))
|
||||
assertNull(RockstarManifest.safePath("C:\\x.dll"))
|
||||
|
||||
@@ -156,20 +156,6 @@ class InputSettingsTest {
|
||||
compose.runOnIdle { assertEquals(SessionPrefs.OSC_NEVER, SessionPrefs.oscMode(context)) }
|
||||
}
|
||||
|
||||
@Test fun theLayoutMenuDescribesEachChoiceAndDeletesAnUnusedLayout() {
|
||||
InputLibraries.update(context) { it.copyLayout(InputLibraries.OVERLAY, "Big sticks", "big-sticks") }
|
||||
compose.setContent { DroidDeckTheme { InputSettingsPage({}) } }
|
||||
compose.onNodeWithTag("setting-osc-layout").performScrollTo().performClick()
|
||||
compose.onNodeWithText(context.getString(R.string.osc_layout_gamepad_detail)).assertExists()
|
||||
compose.onNodeWithText(context.getString(R.string.osc_layout_steam_detail)).assertExists()
|
||||
compose.onNodeWithTag("osc-delete-${InputLibraries.OVERLAY}").assertDoesNotExist()
|
||||
compose.onNodeWithTag("osc-delete-big-sticks").performClick()
|
||||
compose.onNodeWithTag("osc-delete-confirm").performClick()
|
||||
compose.runOnIdle { assertTrue(InputLibraries.read(context).layouts.none { it.id == "big-sticks" }) }
|
||||
compose.onNodeWithTag("setting-osc-layout").performScrollTo().performClick()
|
||||
compose.onNodeWithText("Big sticks").assertDoesNotExist()
|
||||
}
|
||||
|
||||
@Test fun choosingTheDefaultLayoutAppliesToGamesWithoutTheirOwn() {
|
||||
InputLibraries.update(context) { it.copyLayout(InputLibraries.OVERLAY, "Big sticks", "big-sticks") }
|
||||
ControlsChoice.newForGame(context, 7, "Castle Crashers", desktop = false)
|
||||
|
||||
@@ -1,24 +1,20 @@
|
||||
# Keep-top guard A/B on dual screens
|
||||
|
||||
`KeepTopActivity` (#2763, removed in the change that added this section) covered every other
|
||||
display while a session was on top, so that display's home was not its top activity. The
|
||||
reasoning: on the Thor, lmkd kills the bottom home under memory pressure, Android relaunches it
|
||||
to the front, the session loses the top spot, drops to adj 50 and is killed next.
|
||||
`KeepTopActivity` (#2763) covers every other display while a session is on top, so that
|
||||
display's home is not its top activity. On the Thor, lmkd kills the bottom home under memory
|
||||
pressure, Android relaunches it to the front (`wm_task_to_front`), the session loses the top
|
||||
spot, drops to adj 50 and is killed in lmkd's next pass.
|
||||
|
||||
It had three side effects:
|
||||
Android gives a translucent activity that is alone in its task an `ActivityRecordInputSink`
|
||||
that consumes every touch inside the task bounds, whatever the window's flags say
|
||||
(`ENABLE_TOUCH_OPAQUE_ACTIVITIES`, on for DroidDeck's target SDK; see
|
||||
`services/core/java/com/android/server/wm/ActivityRecordInputSink.java`). The guard's
|
||||
`FLAG_NOT_TOUCHABLE` therefore did nothing: with the dual-screen panel closed, the bottom
|
||||
screen took no touch until the session ended, and the guard also stayed over it after Home.
|
||||
|
||||
- Android gives a translucent activity alone in its task an `ActivityRecordInputSink` that
|
||||
consumes every touch in the task bounds whatever the window's flags say
|
||||
(`ENABLE_TOUCH_OPAQUE_ACTIVITIES`), so the bottom screen took no touch (#2910 worked around it).
|
||||
- Cocoon tracks the top activity of each display; with a DroidDeck activity on the bottom it
|
||||
could not suspend or resume DroidDeck properly.
|
||||
- The Thor's `com.odin.gameassistant` gives every app with an activity on top of the bottom
|
||||
display that display's volume (`secondary_screen_volume_level`). With the guard up, all of
|
||||
DroidDeck's audio played at the bottom screen's volume (AudioFlinger track gain -37, -13 and
|
||||
-2.6 dB at levels 3, 8 and 13; -7.4 dB, the top level, once the guard was removed).
|
||||
|
||||
The A/B below found no case on either device where the guard kept the session alive, so it was
|
||||
removed.
|
||||
The guard now takes touches itself. A touch removes it from that display. It comes back when
|
||||
the session is top-resumed again, or after 5 s if the session kept the top spot (one touch on
|
||||
the bottom screen, then back to the game). Stopping or entering PiP removes the guards.
|
||||
|
||||
## Tool
|
||||
|
||||
@@ -29,7 +25,6 @@ build that has the debugging tools:
|
||||
python3 tools/memory_guard_ab.py --label main --apk main.apk states
|
||||
python3 tools/memory_guard_ab.py --label fix --apk fix.apk states
|
||||
python3 tools/memory_guard_ab.py --label fix pressure --stop-mb 650 --hold 30 --runs 3
|
||||
python3 tools/memory_guard_ab.py --label fix pressure --burst --stop-mb 1500 --hold 20 --runs 3
|
||||
python3 tools/memory_guard_ab.py --label fix summarize ~/.cache/droiddeck-memory-guard-ab/fix-stop650-1-events.txt
|
||||
```
|
||||
|
||||
@@ -44,13 +39,6 @@ event log of every probe.
|
||||
`--stop-mb`, holds it, and releases it. zram cannot compress that data and no app owns it,
|
||||
so lmkd keeps killing by adj. It records lmkd's `killinfo`, process deaths, focus loss and
|
||||
whether DroidDeck survived.
|
||||
- `pressure --burst` takes everything above `--stop-mb` at once instead: it copies a 256 MiB
|
||||
random file into the tmpfs with all copies running in parallel (about 5 GiB in 2 to 3 s on a
|
||||
Thor), the way a game's GPU allocation burst lands on lmkd.
|
||||
- `oom_score_adj` is read without `su`. Under pressure lmkd keeps killing the root manager app,
|
||||
and a `su` call can then open its request screen on top of the game.
|
||||
- If the bottom display has no home (a killed home is not always restarted), the visible app on
|
||||
top of it stands in.
|
||||
- `--bottom-tap` must point at an inert spot of the bottom home; `--panel-close` at the
|
||||
panel's close button. Both are fractions of the bottom display.
|
||||
- `am start` of `SessionActivity` needs `--display 0`; without it, it creates a second
|
||||
@@ -100,24 +88,3 @@ moves it to the front, even with no guard. The Thor's focus steal does not happe
|
||||
Duo shows that the guard covers the same states as before, not that it saves the session. That
|
||||
needs a Thor: run `states` and `pressure --stop-mb` near its adj-50 level on `main` and on the
|
||||
fix, and look for `task_to_front` and `session_top_lost` before `droiddeck_died_at_adj` 50.
|
||||
|
||||
## Results: AYN Thor (12 GB), Android 13
|
||||
|
||||
Builds: `main` (56986b5, guard with the #2910 touch yield) and `no-guard` (`main` with
|
||||
`guardOtherDisplays` returning at once). The game was focused on the top screen in every run.
|
||||
|
||||
| Pressure | Bottom app | no-guard | main |
|
||||
| --- | --- | --- | --- |
|
||||
| Fill to 650 MB free, hold 30 s | stock launcher | survived 1/1 usable run (launcher not reached) | survived 3/3 (launcher killed 80, 25, 0 times) |
|
||||
| Fill to 550 MB free, hold 30 s | Cocoon as home | survived 3/3, Cocoon killed 387, 400, 84 times | survived 3/3, Cocoon killed 384, 127, 338 times |
|
||||
| Burst to 400 MB free (about 5 GB in 2.5 to 3.4 s) | stock launcher | killed at adj 0 in 3/3 | killed at adj 0 in 3/3 |
|
||||
| Burst to 1500 MB free (2.0 to 2.4 s) | stock launcher | survived 1/2, killed at adj 0 in 1/2 | killed at adj 0 in 2/2 |
|
||||
|
||||
No run on either build lost the top spot (`wm_on_top_resumed_lost_called` for
|
||||
`SessionActivity`), moved a task to the front, or killed DroidDeck at adj 50. A killed bottom
|
||||
home is either restarted in place or its task disappears and the next app shows on the bottom
|
||||
screen, without taking focus. A burst big enough to matter makes lmkd kill the foreground
|
||||
session at adj 0, which no activity on another display can prevent.
|
||||
|
||||
`kill -9` of the bottom app (`states`) is noisy on a Thor with many recent apps: each kill
|
||||
surfaces the next app on the bottom screen, and every tap the tool sends there moves focus.
|
||||
@@ -0,0 +1,45 @@
|
||||
DroidDeck bionic runtime pack: sources, credits and licences
|
||||
|
||||
Built by DroidDeck's CI with tools/bionic-runtime/build.sh (GPL-3.0, like DroidDeck). Exact pins and the
|
||||
sha256 of every file are in MANIFEST.txt.
|
||||
|
||||
Built from source in this pack:
|
||||
- layer/libVkLayer_FROG_gamescope_wsi_aarch64.so: gamescope's Vulkan WSI layer (Valve Corporation, BSD-2-Clause,
|
||||
https://github.com/ValveSoftware/gamescope) at the pinned tag with DroidDeck's patches 0117 and 0119
|
||||
(tools/gamescope/patches), using vkroots by Joshua Ashton (vkroots.h: Apache-2.0 OR MIT,
|
||||
https://github.com/Joshua-Ashton/vkroots) and the Khronos Vulkan-Headers (Apache-2.0 / MIT).
|
||||
- preload/libfakeinput.so: DroidDeck's app/src/main/cpp/fakeinput_steam.cpp, taken from WinNative by maxjivi05
|
||||
(GPL-3.0, https://github.com/WinNative-Emu/WinNative), mmap ring controller input by ribbit384 (WinNative #345).
|
||||
- preload/libnotag.so, bin/gstag: DroidDeck (GPL-3.0).
|
||||
- layer/libVkLayer_droiddeck_gpuload.so: DroidDeck's HUD GPU-load Vulkan layer (tools/gpuload, GPL-3.0), built for the
|
||||
bionic userland.
|
||||
|
||||
Taken unchanged from The412Banner's Bannerlator (GPL-3.0, https://github.com/The412Banner/Bannerlator):
|
||||
- lib/: Android builds of open-source libraries from Bannerlator's base imagefs
|
||||
(https://github.com/The412Banner/winlator-contents, release base-assets-v1), among them X.Org libX11/libXext/...
|
||||
and libxcb (MIT/X11), Wayland (MIT), SDL2 (zlib), GStreamer and its plugins, GLib, PulseAudio, GnuTLS, libsndfile,
|
||||
alsa-lib, libiconv (LGPL-2.1 or later), FreeType (FTL or GPL-2.0), Fontconfig (MIT), libxml2 (MIT), libffi (MIT),
|
||||
PCRE2 (BSD-3-Clause), zlib (zlib), and FFmpeg 8 libraries (LGPL-2.1 or later) from Bannerlator's ffmpeg8.tzst.
|
||||
share/X11 and etc/ (fonts, tls) come from the same imagefs.
|
||||
|
||||
From The412Banner/Banners-Turnip (https://github.com/The412Banner/Banners-Turnip, release
|
||||
fastgl-x11egl-mesa-d8cfbe8-r1):
|
||||
- egl/: Mesa (MIT, https://gitlab.freedesktop.org/mesa/mesa) EGL, GLX and Gallium with Zink at Mesa main d8cfbe82766,
|
||||
built for the bionic userland with the x11 and wayland platforms (branch fix/fastgl-zink-readback, the
|
||||
exp/egl-x11-platform recipe that builds Bannerlator's Fast OpenGL set), with libwayland-client (MIT) and libarchive
|
||||
(BSD-2-Clause); egl/x11egl.json records the build. Newer Mesa brings Zink's kopper front-buffer readback fixes by
|
||||
Mike Blumenkrantz.
|
||||
|
||||
From The412Banner/bionic-vulkan-wrapper (https://github.com/The412Banner/bionic-vulkan-wrapper, release
|
||||
wayland-adapter-placed-export-r1):
|
||||
- adapter/libvulkan_wrapper.so: the Wayland adapter Bannerlator ships (branch banner/wayland-wsi-bgra-native) plus
|
||||
placed-mapping fixes for 32-bit OpenGL / WineD3D (branch banner/wayland-wsi-placed-export), a Mesa tree (MIT) in
|
||||
the line of Pipetto-crypto's wrapper and leegao's bionic Vulkan wrapper. adapter/adapter.json records the build.
|
||||
|
||||
Taken unchanged from DroidDeck-Proton (https://github.com/Droid-Deck/DroidDeck-Proton, release DroidDeck-Proton-11-12.8):
|
||||
- d7vk/ddraw.dll: D7VK by WinterSnowfall (zlib, https://github.com/WinterSnowfall/d7vk, commit 06656b9e), Direct3D 7
|
||||
and older on Vulkan, based on DXVK by Philip Rebohle and contributors (zlib, https://github.com/doitsujin/dxvk);
|
||||
32-bit build from DroidDeck-Proton's CI.
|
||||
|
||||
Not in this pack: the bionic DroidDeck-Proton layer (The412Banner/proton-wine releases), GPU drivers, DXVK/VKD3D
|
||||
and FEX (DroidDeck components).
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"file_format_version" : "1.0.0",
|
||||
"layer" : {
|
||||
"name": "VK_LAYER_FROG_gamescope_wsi_aarch64",
|
||||
"type": "GLOBAL",
|
||||
"api_version": "1.3.221",
|
||||
"library_path": "./libVkLayer_FROG_gamescope_wsi_aarch64.so",
|
||||
"implementation_version": "1",
|
||||
"description": "Gamescope WSI (XWayland Bypass) Layer (aarch64), bionic build",
|
||||
"functions": { "vkNegotiateLoaderLayerInterfaceVersion": "vkNegotiateLoaderLayerInterfaceVersion" },
|
||||
"enable_environment": { "ENABLE_GAMESCOPE_WSI": "1" },
|
||||
"disable_environment": { "DISABLE_GAMESCOPE_WSI": "1" }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
// glibc's program_invocation_name is __progname in Android's libc (exported, set from argv[0]).
|
||||
#pragma once
|
||||
#ifdef __cplusplus
|
||||
extern "C" char *__progname;
|
||||
#else
|
||||
extern char *__progname;
|
||||
#endif
|
||||
#define program_invocation_name __progname
|
||||
#define program_invocation_short_name __progname
|
||||
Executable
+272
@@ -0,0 +1,272 @@
|
||||
#!/usr/bin/env bash
|
||||
# Builds DroidDeck's bionic runtime pack: the Android-side (bionic libc) pieces a bionic DroidDeck-Proton layer
|
||||
# needs inside DroidDeck's gamescope session. The Proton layer itself comes from The412Banner/proton-wine releases;
|
||||
# GPU drivers, DXVK/VKD3D and FEX stay app options. Binaries target Android 11+ (API 30: the fake-input
|
||||
# library hooks statx).
|
||||
#
|
||||
# usage: NDK=<Android NDK root> tools/bionic-runtime/build.sh <work dir> <out dir>
|
||||
# host needs: curl git tar zstd python3, wayland-scanner, and the X11/xcb/wayland/glm headers
|
||||
# (Debian/Ubuntu: libwayland-bin libwayland-dev libx11-dev libx11-xcb-dev libxcb1-dev libxcb-composite0-dev libglm-dev)
|
||||
set -euo pipefail
|
||||
|
||||
HERE=$(cd "$(dirname "$0")" && pwd)
|
||||
ROOT=$(cd "$HERE/../.." && pwd)
|
||||
WORK=${1:?usage: build.sh <work dir> <out dir>}
|
||||
OUT=${2:?usage: build.sh <work dir> <out dir>}
|
||||
: "${NDK:?set NDK to the Android NDK root}"
|
||||
API=30
|
||||
|
||||
# Pinned inputs (bump together with their sha256).
|
||||
IMAGEFS_URL=https://github.com/The412Banner/winlator-contents/releases/download/base-assets-v1/imagefs.tar.zst
|
||||
IMAGEFS_SHA256=7838756e6a05c91afff68f4bf12aa2780f815877753f8dd354e203e99b9caf8a # same pin as Bannerlator app/build.gradle
|
||||
BL_COMMIT=410c969dfe37ed0c687d6a5ee3327ea21a53e0f8 # The412Banner/Bannerlator
|
||||
BL_ASSETS=https://raw.githubusercontent.com/The412Banner/Bannerlator/$BL_COMMIT/app/src/main/assets
|
||||
# The Wayland adapter: Bannerlator's (bionic-vulkan-wrapper banner/wayland-wsi-bgra-native f970b6c) plus the placed-
|
||||
# mapping fixes 32-bit OpenGL / WineD3D need (branch banner/wayland-wsi-placed-export), from that repository's release.
|
||||
ADAPTER_URL=https://github.com/The412Banner/bionic-vulkan-wrapper/releases/download/wayland-adapter-placed-export-r1
|
||||
ADAPTER_SHA256=653791c2c2ea904a5122909f01d26689553e91cc4dc7a981478c1303adc96ea5 # libvulkan_wrapper.so
|
||||
ADAPTER_JSON_SHA256=5448fd64f15fa13ca3c805967c2b4788eb5f86d29a2d2755e15498130cdef9b3
|
||||
# OpenGL: the Fast OpenGL Mesa set (EGL + GLX + Zink) rebuilt from Mesa main d8cfbe82766 for Zink's kopper readback
|
||||
# fixes (Banners-Turnip fix/fastgl-zink-readback e07e94d0, run 44232301491); Bannerlator's copy is the 7cda7850 build.
|
||||
FASTGL_URL=https://github.com/The412Banner/Banners-Turnip/releases/download/fastgl-x11egl-mesa-d8cfbe8-r1
|
||||
FFMPEG8_SHA256=34ca9076b6b69bc96ee0d53fcb7b9d0d8df869b9f1255dd686bf89cc590b1b08 # ffmpeg8.tzst
|
||||
GAMESCOPE_TAG=3.16.29
|
||||
GAMESCOPE_COMMIT=8f212644c46460549035971ab914421180f61a7c
|
||||
GAMESCOPE_PATCHES="0117-wsi-cache-present-bypass-check.patch 0119-wsi-default-images-under-limiter.patch"
|
||||
VULKAN_HEADERS_TAG=v1.4.341
|
||||
# The bionic DroidDeck-Proton layer the pack is made for: linked against (libwayland-client) and checked against, not packed.
|
||||
# Layer v16 (067c719d) plus the ARM64EC code-map fix for 39-bit hosts (d4c9ffa7, run 44291095238).
|
||||
LAYER_URL=https://github.com/The412Banner/proton-wine/releases/download/build-bionic-layers-20261118-v16-unwind/DroidDeck-Proton-11.0-12.8-arm64ec.wcp
|
||||
LAYER_SHA256=3cc74b877bc8707d75aa2cc22e335373b6a6c0b6b1937c7b3c2cd98e55de2e89 # proton-wine d48e30a1 (a188791d + fecf7376 on d4c9ffa7)
|
||||
LAYER_VERSION=12.8
|
||||
# Packed into the DroidDeck-Bionic tool next to the layer: FEX with Android-built unix libraries, and default
|
||||
# DXVK / VKD3D-Proton (DroidDeck components can swap these in files/lib/wine/{dxvk,vkd3d-proton} later).
|
||||
FEX_URL=https://github.com/The412Banner/Nightlies/releases/download/FEXCore-2611.1/FEXCore-2611.1-unix.wcp
|
||||
FEX_SHA256=caca997e5e077feb5d9b7cf0f2c680cd93b442278903e3f3e7b1bd9cd544770c
|
||||
DXVK_URL=https://github.com/The412Banner/Nightlies/releases/download/Dxvk-gplasync-Linux/dxvk-gplasync-2.4.1-1-pre-reg-linux.wcp
|
||||
DXVK_SHA256=379b5dcde331de45a5f0ac7775d2c657c9c1510616afb9143ab8cdfbfa8e5342
|
||||
# VKD3D-Proton from DroidDeck-Components' stable release: the linux-nightly files are replaced as nightlies land.
|
||||
VKD3D_URL=https://github.com/Droid-Deck/DroidDeck-Components/releases/download/linux-stable/DD-vkd3d-proton-arm64ec-3.1.wcp
|
||||
VKD3D_SHA256=bd458d8adb08631d7d5da93c51ad02ce224178127d3408ca693b2947bf85bdd0
|
||||
# D7VK's 32-bit ddraw.dll (PROTON_USE_D7VK): the same file DroidDeck-Proton 11-12.8 ships, built there from
|
||||
# WinterSnowfall/d7vk; only that file is taken out of the release archive.
|
||||
D7VK_FROM=https://github.com/Droid-Deck/DroidDeck-Proton/releases/download/DroidDeck-Proton-11-12.8/DroidDeck-Proton-11-12.8-aarch64.tar.gz
|
||||
D7VK_MEMBER="DroidDeck-Proton 11-12.8/files/lib/wine/d7vk/i386-windows/ddraw.dll"
|
||||
D7VK_SHA256=aaf28d3dee147fd359d14bb08228f9d21335fb5fec334415e396353a967574aa
|
||||
D7VK_COMMIT=06656b9e94bf275854e3d83d6426517253937738
|
||||
|
||||
case "$(uname -s):$(uname -m)" in
|
||||
Linux:x86_64) NDK_HOST=linux-x86_64 ;;
|
||||
Linux:aarch64|Linux:arm64) NDK_HOST=linux-aarch64 ;;
|
||||
Darwin:arm64) NDK_HOST=darwin-arm64 ;;
|
||||
Darwin:x86_64) NDK_HOST=darwin-x86_64 ;;
|
||||
*) echo "unsupported host $(uname -s):$(uname -m)" >&2; exit 1 ;;
|
||||
esac
|
||||
TC="$NDK/toolchains/llvm/prebuilt/$NDK_HOST/bin"
|
||||
[[ -d "$TC" ]] || TC="$NDK/toolchains/llvm/prebuilt/linux-x86_64/bin"
|
||||
CC="$TC/aarch64-linux-android${API}-clang"
|
||||
CXX="$TC/aarch64-linux-android${API}-clang++"
|
||||
READELF="$TC/llvm-readelf"
|
||||
STRIP="$TC/llvm-strip"
|
||||
[[ -x "$CC" && -x "$CXX" ]] || { echo "no NDK clang under $TC" >&2; exit 1; }
|
||||
|
||||
fetch() { # url sha256 dest
|
||||
curl -fsSL --retry 5 --retry-delay 3 --retry-connrefused -o "$3" "$1"
|
||||
echo "$2 $3" | sha256sum -c -
|
||||
}
|
||||
|
||||
rm -rf "$WORK"; mkdir -p "$WORK" "$OUT"
|
||||
PACK="$WORK/droiddeck-bionic-runtime"
|
||||
mkdir -p "$PACK"/{lib,layer,preload,bin,adapter,share,etc}
|
||||
|
||||
echo "== imagefs (Bannerlator base, pinned)"
|
||||
fetch "$IMAGEFS_URL" "$IMAGEFS_SHA256" "$WORK/imagefs.tar.zst"
|
||||
mkdir -p "$WORK/imagefs"
|
||||
tar --zstd -xf "$WORK/imagefs.tar.zst" -C "$WORK/imagefs"
|
||||
IMG="$WORK/imagefs/usr/lib"
|
||||
[[ -d "$IMG" ]] || { echo "imagefs has no usr/lib" >&2; exit 1; }
|
||||
|
||||
echo "== bionic DroidDeck-Proton layer (pinned; its lib/ is on the library path at run time)"
|
||||
fetch "$LAYER_URL" "$LAYER_SHA256" "$WORK/layer.wcp"
|
||||
mkdir -p "$WORK/layer"
|
||||
tar --zstd -xf "$WORK/layer.wcp" -C "$WORK/layer" lib
|
||||
LAYERLIB="$WORK/layer/lib"
|
||||
|
||||
echo "== Wayland adapter (pinned release)"
|
||||
fetch "$ADAPTER_URL/libvulkan_wrapper.so" "$ADAPTER_SHA256" "$PACK/adapter/libvulkan_wrapper.so"
|
||||
fetch "$ADAPTER_URL/adapter.json" "$ADAPTER_JSON_SHA256" "$PACK/adapter/adapter.json"
|
||||
echo "== Bannerlator assets (pinned): FFmpeg 8"
|
||||
fetch "$BL_ASSETS/ffmpeg8.tzst" "$FFMPEG8_SHA256" "$WORK/ffmpeg8.tzst"
|
||||
|
||||
echo "== D7VK ddraw.dll (DroidDeck-Proton 11-12.8 release, that file only)"
|
||||
mkdir -p "$PACK/d7vk"
|
||||
curl -fsSL --retry 5 --retry-delay 3 --retry-connrefused "$D7VK_FROM" | tar -xzO -f - "$D7VK_MEMBER" > "$PACK/d7vk/ddraw.dll"
|
||||
echo "$D7VK_SHA256 $PACK/d7vk/ddraw.dll" | sha256sum -c -
|
||||
# OpenGL: bionic Mesa (EGL + GLX + Zink, x11 and wayland platforms) for winex11's EGL backend, the set Bannerlator's
|
||||
# Fast OpenGL uses, from the newer Mesa build pinned in FASTGL_URL
|
||||
mkdir -p "$PACK/egl"
|
||||
for e in libEGL.so.1:7d1febabcb0cb6348128bc44885886fba6a2edc103fcfc91f5f858e460b33fd6 \
|
||||
libGL.so.1:8de5c26d4de6dcac4dd2605d8742622711adcdb76d9fe5f5848894e439bb3826 \
|
||||
libGLESv2.so.2:2136442182ed8d724f80b2d69ee89f654694fd84439fdeb14010034c14f57658 \
|
||||
libgallium-27.0.0-devel.so:392ca9d6d3127b2ac5fc232d25830111c759dc672f437794731fc2778ff0eb34 \
|
||||
libwayland-client.so:fa49c2f119b84a0cf54669de1706a6bc427bb8a7f147c977328575ccbb920126 \
|
||||
libarchive.so:eb3b13634bd2c188d71e886f8c690ef32f6b4a2a0e8a7197a7f974b2d341b7ab \
|
||||
x11egl.json:90c1dcebb746625b81b4cf5335e177a4b7cbe608b359c9be5eaa43d8f0de499b; do
|
||||
fetch "$FASTGL_URL/${e%%:*}" "${e#*:}" "$PACK/egl/${e%%:*}"
|
||||
done
|
||||
cp "$HERE/icd.json" "$PACK/adapter/icd.json"
|
||||
|
||||
echo "== libraries from the imagefs"
|
||||
copy_lib() { # name: copies the file and every link on the way to it, as links (Android's own libraries are skipped)
|
||||
local name=$1 src=$IMG/$1 target
|
||||
[[ -e "$src" || -L "$src" ]] || { echo "missing in imagefs: $name" >&2; return 1; }
|
||||
[[ -L "$src" && "$(readlink "$src")" == /* ]] && return 0
|
||||
while [[ -L "$src" ]]; do
|
||||
target=$(readlink "$src")
|
||||
[[ -e "$PACK/lib/$(basename "$src")" || -L "$PACK/lib/$(basename "$src")" ]] || ln -s "$(basename "$target")" "$PACK/lib/$(basename "$src")"
|
||||
src="$(dirname "$src")/$target"
|
||||
done
|
||||
[[ -e "$PACK/lib/$(basename "$src")" ]] || cp "$src" "$PACK/lib/"
|
||||
}
|
||||
grep -v -e '^#' -e '^$' "$HERE/runtime-libs.txt" | while read -r name; do copy_lib "$name"; done
|
||||
[[ -e "$PACK/lib/libSDL2-2.0.so.0" ]] || ln -s libSDL2-2.0.so "$PACK/lib/libSDL2-2.0.so.0"
|
||||
mkdir -p "$PACK/lib/gstreamer-1.0"
|
||||
grep -v -e '^#' -e '^$' "$HERE/gst-plugins.txt" | while read -r p; do cp "$IMG/gstreamer-1.0/libgst$p.so" "$PACK/lib/gstreamer-1.0/"; done
|
||||
tar --zstd -xf "$WORK/ffmpeg8.tzst" -C "$PACK/lib"
|
||||
for f in "$PACK"/lib/libav*.so.* "$PACK"/lib/libsw*.so.*; do # soname links for the FFmpeg 8 files
|
||||
[[ -L "$f" ]] && continue
|
||||
so=$("$READELF" -d "$f" | sed -n 's/.*(SONAME).*\[\(.*\)\]/\1/p')
|
||||
[[ -n "$so" && ! -e "$PACK/lib/$so" ]] && ln -s "$(basename "$f")" "$PACK/lib/$so"
|
||||
done
|
||||
# GStreamer plugins: add the libraries they need from the imagefs; drop plugins needing something it lacks
|
||||
python3 "$HERE/check-needed.py" "$READELF" "$PACK" --available "$LAYERLIB" --fill "$IMG" --prune lib/gstreamer-1.0
|
||||
cp -a "$WORK/imagefs/usr/share/X11" "$PACK/share/"
|
||||
cp -a "$WORK/imagefs/etc/fonts" "$WORK/imagefs/etc/tls" "$PACK/etc/"
|
||||
|
||||
echo "== gamescope $GAMESCOPE_TAG WSI layer (+ DroidDeck patches: $GAMESCOPE_PATCHES)"
|
||||
GS="$WORK/gamescope"
|
||||
git clone -q --depth 1 --branch "$GAMESCOPE_TAG" https://github.com/ValveSoftware/gamescope "$GS"
|
||||
[[ "$(git -C "$GS" rev-parse HEAD)" == "$GAMESCOPE_COMMIT" ]] || { echo "gamescope $GAMESCOPE_TAG is not $GAMESCOPE_COMMIT" >&2; exit 1; }
|
||||
git -C "$GS" submodule update -q --init --depth 1 subprojects/vkroots || git -C "$GS" submodule update -q --init subprojects/vkroots
|
||||
for p in $GAMESCOPE_PATCHES; do git -C "$GS" apply "$ROOT/tools/gamescope/patches/$p"; done
|
||||
git clone -q --depth 1 --branch "$VULKAN_HEADERS_TAG" https://github.com/KhronosGroup/Vulkan-Headers "$WORK/vulkan-headers"
|
||||
INC="$WORK/inc"; GEN="$WORK/gen"; mkdir -p "$INC" "$GEN"
|
||||
cp -r "$WORK/vulkan-headers/include/vulkan" "$WORK/vulkan-headers/include/vk_video" "$INC/"
|
||||
cp -r /usr/include/X11 /usr/include/xcb /usr/include/glm "$INC/"
|
||||
cp /usr/include/wayland-*.h "$INC/"
|
||||
for p in gamescope-swapchain gamescope-limiter; do
|
||||
wayland-scanner client-header "$GS/protocol/$p.xml" "$GEN/$p-client-protocol.h"
|
||||
wayland-scanner private-code "$GS/protocol/$p.xml" "$GEN/$p-protocol.c"
|
||||
"$CC" -O2 -fPIC -c -I"$INC" "$GEN/$p-protocol.c" -o "$GEN/$p-protocol.o"
|
||||
done
|
||||
LINK=(-L"$PACK/lib" -Wl,-rpath-link,"$PACK/lib" -L"$LAYERLIB" -Wl,-rpath-link,"$LAYERLIB")
|
||||
"$CXX" -std=c++20 -O2 -fPIC -shared -DWLR_USE_UNSTABLE -D_GNU_SOURCE -include "$HERE/bionic_compat.h" \
|
||||
-I"$GS/subprojects/vkroots" -I"$GEN" -I"$INC" -I"$GS/layer" -I"$GS/src" \
|
||||
"$GS/layer/VkLayer_FROG_gamescope_wsi.cpp" "$GEN"/*.o "${LINK[@]}" \
|
||||
-lwayland-client -lX11-xcb -lX11 -lxcb -lxcb-composite -static-libstdc++ -Wl,--no-undefined \
|
||||
-o "$PACK/layer/libVkLayer_FROG_gamescope_wsi_aarch64.so"
|
||||
cp "$HERE/VkLayer_FROG_gamescope_wsi.aarch64.json" "$PACK/layer/"
|
||||
|
||||
echo "== DroidDeck GPU-load layer (tools/gpuload), off unless its DroidDeck variables are set"
|
||||
for l in gpuload; do
|
||||
"$CC" -std=c11 -shared -fPIC -O2 -Wall -Wno-unused-parameter -Wno-missing-field-initializers -fvisibility=hidden \
|
||||
-pthread -Wl,-z,defs -include "$HERE/bionic_compat.h" -I"$INC" -I"$ROOT/tools/gpuload/src" \
|
||||
"$ROOT/tools/gpuload/src/vk_layer_droiddeck_$l.c" -o "$PACK/layer/libVkLayer_droiddeck_$l.so"
|
||||
done
|
||||
for j in gpu_load:gpuload; do
|
||||
sed 's#"library_path": *"[^"]*"#"library_path": "./libVkLayer_droiddeck_'"${j#*:}"'.so"#' \
|
||||
"$ROOT/tools/gpuload/layer/VK_LAYER_DROIDDECK_${j%%:*}.json" > "$PACK/layer/VK_LAYER_DROIDDECK_${j%%:*}.json"
|
||||
grep -q '"library_path": "./libVkLayer_droiddeck_' "$PACK/layer/VK_LAYER_DROIDDECK_${j%%:*}.json"
|
||||
done
|
||||
|
||||
echo "== DroidDeck fake input (app/src/main/cpp/fakeinput_steam.cpp), heap-tagging off, window tagger"
|
||||
"$CXX" -shared -fPIC -O2 -Wall -Wno-attributes -pthread -std=c++17 "$ROOT/app/src/main/cpp/fakeinput_steam.cpp" \
|
||||
-ldl -static-libstdc++ -o "$PACK/preload/libfakeinput.so"
|
||||
"$CC" -shared -fPIC -O2 -Wall "$HERE/notag.c" -ldl -o "$PACK/preload/libnotag.so"
|
||||
"$CC" -shared -fPIC -O2 -Wall "$HERE/execshim.c" -ldl -o "$PACK/preload/libexecshim.so"
|
||||
"$CC" -shared -fPIC -O2 -Wall -Wextra -fvisibility=hidden "$HERE/steamshm.c" -ldl -o "$PACK/preload/libsteamshm.so"
|
||||
"$CC" -O2 -Wall "$HERE/gstag.c" -o "$PACK/bin/gstag"
|
||||
"$STRIP" --strip-unneeded "$PACK/layer/"*.so "$PACK/preload/"*.so "$PACK/bin/gstag"
|
||||
|
||||
echo "== every library a pack file needs must be in the pack or on Android"
|
||||
python3 "$HERE/check-needed.py" "$READELF" "$PACK" --available "$LAYERLIB"
|
||||
|
||||
echo "== manifest"
|
||||
REV=$(git -C "$ROOT" rev-parse --short=8 HEAD)
|
||||
cp "$HERE/NOTICE" "$PACK/NOTICE"
|
||||
{
|
||||
echo "droiddeck-bionic-runtime $REV ($(date -u +%Y-%m-%dT%H:%M:%SZ), Android API $API, NDK $(basename "$NDK"))"
|
||||
echo "imagefs $IMAGEFS_URL sha256 $IMAGEFS_SHA256"
|
||||
echo "bannerlator $BL_COMMIT (ffmpeg8.tzst)"
|
||||
echo "fastgl $FASTGL_URL (egl/: Mesa EGL + GLX + Zink, Mesa main d8cfbe82766)"
|
||||
echo "adapter $ADAPTER_URL (libvulkan_wrapper.so sha256 $ADAPTER_SHA256)"
|
||||
echo "layer $LAYER_URL sha256 $LAYER_SHA256 (not packed)"
|
||||
echo "d7vk $D7VK_COMMIT: i386 ddraw.dll from $D7VK_FROM"
|
||||
echo "gamescope $GAMESCOPE_TAG $GAMESCOPE_COMMIT + $GAMESCOPE_PATCHES; vkroots $(git -C "$GS/subprojects/vkroots" rev-parse HEAD); Vulkan-Headers $VULKAN_HEADERS_TAG"
|
||||
echo
|
||||
(cd "$PACK" && find . -type f ! -name MANIFEST.txt | sort | xargs sha256sum)
|
||||
} > "$PACK/MANIFEST.txt"
|
||||
tar --zstd -cf "$OUT/droiddeck-bionic-runtime-$REV.tar.zst" -C "$WORK" droiddeck-bionic-runtime
|
||||
(cd "$OUT" && sha256sum "droiddeck-bionic-runtime-$REV.tar.zst" > "droiddeck-bionic-runtime-$REV.tar.zst.sha256")
|
||||
du -sh "$PACK" "$OUT"/*.tar.zst
|
||||
|
||||
echo "== DroidDeck-Bionic tool: layer + this pack + FEX + DXVK/VKD3D + tool scripts, in Proton's layout"
|
||||
NAME="DroidDeck-Bionic-$LAYER_VERSION-r${BUILD_NUMBER:-0}"
|
||||
T="$WORK/tool/$NAME"
|
||||
mkdir -p "$T/files" "$T/bionic"
|
||||
tar --zstd -xf "$WORK/layer.wcp" -C "$T/files" bin lib share prefixPack.txz
|
||||
mkdir -p "$WORK/pfx" && tar -xJf "$T/files/prefixPack.txz" -C "$WORK/pfx" && rm "$T/files/prefixPack.txz"
|
||||
mv "$WORK/pfx/.wine" "$T/files/default_pfx"
|
||||
# No drives in the template: its links point into Winlator, and a Z: -> / link here once let DroidDeck's tool delete
|
||||
# walk the whole device. launch.sh makes C: and Z: in each game's own prefix.
|
||||
rm -rf "$T/files/default_pfx/dosdevices"
|
||||
for c in FEX:"$FEX_URL":"$FEX_SHA256" DXVK:"$DXVK_URL":"$DXVK_SHA256" VKD3D:"$VKD3D_URL":"$VKD3D_SHA256"; do
|
||||
n=${c%%:*}; rest=${c#*:}; sha=${rest##*:}; url=${rest%:*}
|
||||
fetch "$url" "$sha" "$WORK/$n.wcp"
|
||||
mkdir -p "$WORK/$n" && tar --zstd -xf "$WORK/$n.wcp" -C "$WORK/$n"
|
||||
done
|
||||
cp "$WORK/FEX/aarch64-unix/"*.so "$T/files/lib/wine/aarch64-unix/"
|
||||
cp "$WORK/FEX/system32/"*.dll "$T/files/lib/wine/aarch64-windows/"
|
||||
cp -r "$WORK/DXVK/files/lib/wine/dxvk" "$WORK/VKD3D/files/lib/wine/vkd3d-proton" "$T/files/lib/wine/"
|
||||
cp -a "$PACK" "$T/files/runtime"
|
||||
# a spare copy of the tool's FEX for launch.sh, which puts it back if DroidDeck's component check swapped in its
|
||||
# own FEX (glibc unix libraries) for a game with a per-game FEX choice
|
||||
mkdir -p "$T/files/runtime/fex/aarch64-unix" "$T/files/runtime/fex/aarch64-windows"
|
||||
cp "$WORK/FEX/aarch64-unix/"*.so "$T/files/runtime/fex/aarch64-unix/"
|
||||
cp "$WORK/FEX/system32/"*.dll "$T/files/runtime/fex/aarch64-windows/"
|
||||
install -m 755 "$HERE/tool/proton" "$T/proton"
|
||||
install -m 755 "$HERE/tool/launch.sh" "$T/bionic/launch.sh"
|
||||
cp "$HERE/tool/desktop.reg" "$HERE/tool/Xdefaults" "$T/bionic/"
|
||||
cp "$HERE/tool/toolmanifest.vdf" "$T/"
|
||||
# The name Steam registers the tool under ends in -Proton: Steam maps Windows save folders (WinAppDataLocal, WinMyDocuments
|
||||
# ...) into compatdata/<app>/pfx only for tools whose name contains "proton" (a case-insensitive search in
|
||||
# steamclient.so's compat manager); without it Steam Cloud skipped every such save rule. The folder, the version file and
|
||||
# the release keep $NAME, which is what DroidDeck matches on.
|
||||
sed -e "s/@NAME@/$NAME-Proton/" -e "s/@DISPLAY@/DroidDeck-Bionic $LAYER_VERSION r${BUILD_NUMBER:-0}/" "$HERE/tool/compatibilitytool.vdf.in" > "$T/compatibilitytool.vdf"
|
||||
echo "$(date -u +%s) $NAME" > "$T/version"
|
||||
{
|
||||
echo "$NAME: DroidDeck runtime pack $REV + layer + FEX/DXVK/VKD3D"
|
||||
echo "fex $FEX_URL sha256 $FEX_SHA256"
|
||||
echo "dxvk $DXVK_URL sha256 $DXVK_SHA256"
|
||||
echo "vkd3d $VKD3D_URL sha256 $VKD3D_SHA256"
|
||||
} > "$T/SOURCES.txt"
|
||||
python3 "$HERE/check-needed.py" "$READELF" "$T/files" --available "$T/files/lib"
|
||||
echo "== no link may point out of the tool (DroidDeck deletes old tool folders)"
|
||||
python3 - "$T" <<'PY'
|
||||
import os, sys
|
||||
root = os.path.realpath(sys.argv[1])
|
||||
bad = []
|
||||
for d, dirs, files in os.walk(root):
|
||||
for n in dirs + files:
|
||||
p = os.path.join(d, n)
|
||||
if os.path.islink(p):
|
||||
t = os.path.realpath(p)
|
||||
if t != root and not t.startswith(root + os.sep):
|
||||
bad.append("%s -> %s" % (os.path.relpath(p, root), os.readlink(p)))
|
||||
if bad:
|
||||
sys.exit("links out of the tool:\n" + "\n".join(bad))
|
||||
print("no links out of the tool")
|
||||
PY
|
||||
tar -C "$WORK/tool" -cf - "$NAME" | xz -T0 -6 > "$OUT/$NAME-aarch64.tar.xz"
|
||||
(cd "$OUT" && sha512sum "$NAME-aarch64.tar.xz" > "$NAME-aarch64.sha512sum")
|
||||
du -sh "$T" "$OUT/$NAME-aarch64.tar.xz"
|
||||
Executable
+123
@@ -0,0 +1,123 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Checks that every library an ELF file in the bionic runtime pack needs is in the pack, in --available
|
||||
(the Proton layer's lib/, on the library path at run time) or on Android.
|
||||
|
||||
usage: check-needed.py <llvm-readelf> <pack dir> [--available DIR]... [--fill IMAGEFS_LIB] [--prune SUBDIR]
|
||||
--fill copies missing libraries (and the links on the way to them) from IMAGEFS_LIB into <pack>/lib, repeatedly
|
||||
--prune deletes ELF files under <pack>/SUBDIR that still miss a library (plugins nothing else links to)
|
||||
Exits 1 when anything is still missing."""
|
||||
import argparse
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
# Android's own libraries (/system/lib64, /apex) the pack may rely on.
|
||||
ANDROID = {
|
||||
"libc.so", "libm.so", "libdl.so", "liblog.so", "libz.so", "libandroid.so", "libnativewindow.so", "libsync.so",
|
||||
"libEGL.so", "libGLESv1_CM.so", "libGLESv2.so", "libGLESv3.so", "libvulkan.so", "libaaudio.so", "libOpenSLES.so",
|
||||
"libmediandk.so", "libjnigraphics.so", "libcamera2ndk.so", "libbinder_ndk.so", "ld-android.so",
|
||||
}
|
||||
# Known gaps, loaded only for features the first version does not cover.
|
||||
OPTIONAL = {
|
||||
"libGL.so.1", # OpenGL games; a dangling link in the pinned imagefs
|
||||
"libodbc.so", # odbc32
|
||||
}
|
||||
|
||||
|
||||
def elf_files(pack):
|
||||
for root, _, files in os.walk(pack):
|
||||
for f in files:
|
||||
path = os.path.join(root, f)
|
||||
if os.path.islink(path) or not os.path.isfile(path):
|
||||
continue
|
||||
with open(path, "rb") as fh:
|
||||
if fh.read(4) == b"\x7fELF":
|
||||
yield path
|
||||
|
||||
|
||||
def needed(readelf, path):
|
||||
out = subprocess.run([readelf, "-d", path], capture_output=True, text=True).stdout
|
||||
return [l.split("[", 1)[1].split("]", 1)[0] for l in out.splitlines() if "(NEEDED)" in l]
|
||||
|
||||
|
||||
def names_in(*dirs):
|
||||
names = set()
|
||||
for d in dirs:
|
||||
for _, _, files in os.walk(d):
|
||||
names.update(files)
|
||||
return names
|
||||
|
||||
|
||||
def missing_map(readelf, pack, available):
|
||||
have = names_in(pack, *available)
|
||||
missing = {}
|
||||
for path in elf_files(pack):
|
||||
for lib in needed(readelf, path):
|
||||
if lib not in have and lib not in ANDROID and lib not in OPTIONAL:
|
||||
missing.setdefault(lib, []).append(path)
|
||||
return missing
|
||||
|
||||
|
||||
def copy_from(img, name, dest):
|
||||
"""Copies img/name into dest, keeping relative links; False when absent or one of Android's (absolute link)."""
|
||||
src = os.path.join(img, name)
|
||||
if not os.path.lexists(src):
|
||||
return False
|
||||
while os.path.islink(src):
|
||||
target = os.readlink(src)
|
||||
if target.startswith("/"):
|
||||
return False
|
||||
link = os.path.join(dest, os.path.basename(src))
|
||||
if not os.path.lexists(link):
|
||||
os.symlink(os.path.basename(target), link)
|
||||
src = os.path.join(os.path.dirname(src), target)
|
||||
if not os.path.exists(src):
|
||||
return False
|
||||
out = os.path.join(dest, os.path.basename(src))
|
||||
if not os.path.exists(out):
|
||||
shutil.copy2(src, out)
|
||||
return True
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("readelf")
|
||||
ap.add_argument("pack")
|
||||
ap.add_argument("--available", action="append", default=[])
|
||||
ap.add_argument("--fill")
|
||||
ap.add_argument("--prune")
|
||||
a = ap.parse_args()
|
||||
|
||||
if a.fill:
|
||||
added = []
|
||||
while True:
|
||||
missing = missing_map(a.readelf, a.pack, a.available)
|
||||
new = [lib for lib in sorted(missing) if copy_from(a.fill, lib, os.path.join(a.pack, "lib"))]
|
||||
if not new:
|
||||
break
|
||||
added += new
|
||||
print(f"added from the imagefs: {len(added)} ({', '.join(added)})" if added else "added from the imagefs: none")
|
||||
|
||||
if a.prune:
|
||||
prune_root = os.path.join(a.pack, a.prune)
|
||||
while True:
|
||||
missing = missing_map(a.readelf, a.pack, a.available)
|
||||
doomed = {p for users in missing.values() for p in users if p.startswith(prune_root + os.sep)}
|
||||
if not doomed:
|
||||
break
|
||||
for p in sorted(doomed):
|
||||
libs = sorted(l for l, users in missing.items() if p in users)
|
||||
print(f"pruned {os.path.relpath(p, a.pack)}: missing {', '.join(libs)}")
|
||||
os.remove(p)
|
||||
|
||||
missing = missing_map(a.readelf, a.pack, a.available)
|
||||
for lib, users in sorted(missing.items()):
|
||||
print(f"missing {lib}: needed by {', '.join(sorted(os.path.relpath(u, a.pack) for u in users)[:5])}")
|
||||
if missing:
|
||||
sys.exit(1)
|
||||
print("all needed libraries present")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,195 @@
|
||||
// execshim: preloaded into the bionic Wine processes. From targetSdk 29 Android refuses execve() of files in the
|
||||
// app's data directory, but the system linker still starts them: "/system/bin/linker64 <file> [args]". So an
|
||||
// execve()/posix_spawn() of a dynamic ELF under /data whose interpreter is /system/bin/linker64 becomes a linker64
|
||||
// start, and a "#!" script there becomes a start of its interpreter. Static ELFs (wine-preloader) and everything
|
||||
// else pass through unchanged: where Android refuses them, Wine falls back to its loader, as on any failed exec.
|
||||
// A program started that way sees /proc/self/exe as linker64; wineserver looks for its NLS files next to its own
|
||||
// executable (server/unicode.c get_nls_dir), so realpath()/readlink() of /proc/self/exe answer with the program
|
||||
// linker64 runs (the second /proc/self/cmdline entry).
|
||||
#define _GNU_SOURCE
|
||||
#include <dlfcn.h>
|
||||
#include <elf.h>
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <limits.h>
|
||||
#if __has_include(<spawn.h>)
|
||||
#include <spawn.h>
|
||||
#else // old Android headers (e.g. Termux's): bionic's own definitions, both opaque pointers
|
||||
typedef struct __posix_spawnattr *posix_spawnattr_t;
|
||||
typedef struct __posix_spawn_file_actions *posix_spawn_file_actions_t;
|
||||
#endif
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#define LINKER "/system/bin/linker64"
|
||||
|
||||
enum kind { PASS, VIA_LINKER, VIA_INTERP };
|
||||
|
||||
// What starting `path` needs; for scripts, the interpreter and its optional argument.
|
||||
static enum kind classify(const char *path, char *resolved, char *interp, char *iarg) {
|
||||
if (!path || !realpath(path, resolved) || strncmp(resolved, "/data/", 6) != 0) return PASS;
|
||||
int fd = open(resolved, O_RDONLY | O_CLOEXEC);
|
||||
if (fd < 0) return PASS;
|
||||
enum kind k = PASS;
|
||||
unsigned char head[256];
|
||||
ssize_t n = pread(fd, head, sizeof head, 0);
|
||||
if (n >= (ssize_t)sizeof(Elf64_Ehdr) && memcmp(head, ELFMAG, SELFMAG) == 0 && head[EI_CLASS] == ELFCLASS64) {
|
||||
Elf64_Ehdr eh;
|
||||
memcpy(&eh, head, sizeof eh);
|
||||
for (int i = 0; i < eh.e_phnum && k == PASS; i++) {
|
||||
Elf64_Phdr ph;
|
||||
if (pread(fd, &ph, sizeof ph, (off_t)(eh.e_phoff + (Elf64_Off)i * eh.e_phentsize)) != sizeof ph) break;
|
||||
if (ph.p_type != PT_INTERP || ph.p_filesz == 0 || ph.p_filesz >= PATH_MAX) continue;
|
||||
char name[PATH_MAX] = {0};
|
||||
if (pread(fd, name, ph.p_filesz, (off_t)ph.p_offset) == (ssize_t)ph.p_filesz && strcmp(name, LINKER) == 0)
|
||||
k = VIA_LINKER;
|
||||
}
|
||||
} else if (n > 2 && head[0] == '#' && head[1] == '!') {
|
||||
char line[256];
|
||||
size_t len = 0;
|
||||
for (ssize_t i = 2; i < n && head[i] != '\n' && len < sizeof line - 1; i++) line[len++] = (char)head[i];
|
||||
line[len] = 0;
|
||||
char *p = line;
|
||||
while (*p == ' ' || *p == '\t') p++;
|
||||
char *end = p;
|
||||
while (*end && *end != ' ' && *end != '\t') end++;
|
||||
char *rest = *end ? end + 1 : end;
|
||||
*end = 0;
|
||||
while (*rest == ' ' || *rest == '\t') rest++;
|
||||
size_t rl = strlen(rest);
|
||||
while (rl && (rest[rl - 1] == ' ' || rest[rl - 1] == '\t' || rest[rl - 1] == '\r')) rest[--rl] = 0;
|
||||
if (*p) {
|
||||
strcpy(interp, p);
|
||||
strcpy(iarg, rest);
|
||||
k = VIA_INTERP;
|
||||
}
|
||||
}
|
||||
close(fd);
|
||||
return k;
|
||||
}
|
||||
|
||||
static int argc_of(char *const argv[]) {
|
||||
int n = 0;
|
||||
while (argv && argv[n]) n++;
|
||||
return n;
|
||||
}
|
||||
|
||||
// New argv for the rewritten start; *file is what to start. NULL when nothing changes.
|
||||
static char **rewrite(const char *path, char *const argv[], const char **file, char *storage) {
|
||||
char *resolved = storage, *interp = storage + PATH_MAX, *iarg = storage + 2 * PATH_MAX;
|
||||
enum kind k = classify(path, resolved, interp, iarg);
|
||||
if (k == PASS) return NULL;
|
||||
int argc = argc_of(argv);
|
||||
char **out = calloc((size_t)argc + 4, sizeof *out);
|
||||
if (!out) return NULL;
|
||||
int j = 0;
|
||||
if (k == VIA_LINKER) {
|
||||
*file = LINKER;
|
||||
out[j++] = (char *)LINKER;
|
||||
out[j++] = resolved;
|
||||
} else {
|
||||
// the interpreter may itself live in app data
|
||||
char *iresolved = storage + 3 * PATH_MAX, *x = storage + 4 * PATH_MAX, *y = storage + 5 * PATH_MAX;
|
||||
if (classify(interp, iresolved, x, y) == VIA_LINKER) {
|
||||
*file = LINKER;
|
||||
out[j++] = (char *)LINKER;
|
||||
out[j++] = iresolved;
|
||||
} else {
|
||||
*file = interp;
|
||||
out[j++] = interp;
|
||||
}
|
||||
if (*iarg) out[j++] = iarg;
|
||||
out[j++] = resolved;
|
||||
}
|
||||
for (int i = 1; i < argc; i++) out[j++] = argv[i];
|
||||
out[j] = NULL;
|
||||
return out;
|
||||
}
|
||||
|
||||
static ssize_t (*real_readlink)(const char *, char *, size_t);
|
||||
|
||||
// The program linker64 runs, when this process is such a start; 0 otherwise.
|
||||
static int linker_program(char *out, size_t n) {
|
||||
if (!real_readlink) real_readlink = (ssize_t (*)(const char *, char *, size_t))dlsym(RTLD_NEXT, "readlink");
|
||||
char link[PATH_MAX];
|
||||
ssize_t l = real_readlink("/proc/self/exe", link, sizeof link - 1);
|
||||
if (l <= 0) return 0;
|
||||
link[l] = 0;
|
||||
const char *base = strrchr(link, '/'); // /system/bin/linker64 is a link into /apex/com.android.runtime/bin
|
||||
if (strcmp(base ? base + 1 : link, "linker64") != 0) return 0;
|
||||
int fd = open("/proc/self/cmdline", O_RDONLY | O_CLOEXEC);
|
||||
if (fd < 0) return 0;
|
||||
char buf[2 * PATH_MAX];
|
||||
ssize_t got = read(fd, buf, sizeof buf - 1);
|
||||
close(fd);
|
||||
if (got <= 0) return 0;
|
||||
buf[got] = 0;
|
||||
size_t first = strlen(buf);
|
||||
if ((ssize_t)first + 1 >= got || !buf[first + 1] || strlen(buf + first + 1) >= n) return 0;
|
||||
strcpy(out, buf + first + 1);
|
||||
return 1;
|
||||
}
|
||||
|
||||
char *realpath(const char *path, char *resolved) {
|
||||
static char *(*real)(const char *, char *);
|
||||
if (!real) real = (char *(*)(const char *, char *))dlsym(RTLD_NEXT, "realpath");
|
||||
char prog[PATH_MAX];
|
||||
if (path && strcmp(path, "/proc/self/exe") == 0 && linker_program(prog, sizeof prog)) return real(prog, resolved);
|
||||
return real(path, resolved);
|
||||
}
|
||||
|
||||
ssize_t readlink(const char *path, char *buf, size_t size) {
|
||||
char prog[PATH_MAX], full[PATH_MAX];
|
||||
if (path && strcmp(path, "/proc/self/exe") == 0 && linker_program(prog, sizeof prog)) {
|
||||
static char *(*real_rp)(const char *, char *);
|
||||
if (!real_rp) real_rp = (char *(*)(const char *, char *))dlsym(RTLD_NEXT, "realpath");
|
||||
if (real_rp(prog, full)) {
|
||||
size_t l = strlen(full);
|
||||
if (l > size) l = size;
|
||||
memcpy(buf, full, l);
|
||||
return (ssize_t)l;
|
||||
}
|
||||
}
|
||||
if (!real_readlink) real_readlink = (ssize_t (*)(const char *, char *, size_t))dlsym(RTLD_NEXT, "readlink");
|
||||
return real_readlink(path, buf, size);
|
||||
}
|
||||
|
||||
int execve(const char *path, char *const argv[], char *const envp[]) {
|
||||
static int (*real)(const char *, char *const[], char *const[]);
|
||||
if (!real) real = (int (*)(const char *, char *const[], char *const[]))dlsym(RTLD_NEXT, "execve");
|
||||
char storage[6 * PATH_MAX]; // stack only: this may run in posix_spawn's vfork-like child (where it passes)
|
||||
const char *file = path;
|
||||
char **args = rewrite(path, argv, &file, storage);
|
||||
int ret = real(file, args ? args : argv, envp);
|
||||
int saved = errno;
|
||||
free(args);
|
||||
errno = saved;
|
||||
return ret;
|
||||
}
|
||||
|
||||
int posix_spawn(pid_t *pid, const char *path, const posix_spawn_file_actions_t *actions,
|
||||
const posix_spawnattr_t *attr, char *const argv[], char *const envp[]) {
|
||||
static int (*real)(pid_t *, const char *, const posix_spawn_file_actions_t *, const posix_spawnattr_t *,
|
||||
char *const[], char *const[]);
|
||||
if (!real)
|
||||
real = (int (*)(pid_t *, const char *, const posix_spawn_file_actions_t *, const posix_spawnattr_t *,
|
||||
char *const[], char *const[]))dlsym(RTLD_NEXT, "posix_spawn");
|
||||
char storage[6 * PATH_MAX];
|
||||
const char *file = path;
|
||||
char **args = rewrite(path, argv, &file, storage);
|
||||
int ret = real(pid, file, actions, attr, args ? args : argv, envp);
|
||||
free(args);
|
||||
return ret;
|
||||
}
|
||||
|
||||
int posix_spawnp(pid_t *pid, const char *file, const posix_spawn_file_actions_t *actions,
|
||||
const posix_spawnattr_t *attr, char *const argv[], char *const envp[]) {
|
||||
static int (*real)(pid_t *, const char *, const posix_spawn_file_actions_t *, const posix_spawnattr_t *,
|
||||
char *const[], char *const[]);
|
||||
if (strchr(file, '/')) return posix_spawn(pid, file, actions, attr, argv, envp);
|
||||
if (!real)
|
||||
real = (int (*)(pid_t *, const char *, const posix_spawn_file_actions_t *, const posix_spawnattr_t *,
|
||||
char *const[], char *const[]))dlsym(RTLD_NEXT, "posix_spawnp");
|
||||
return real(pid, file, actions, attr, argv, envp);
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
# GStreamer plugins packed for winegstreamer (game video/audio), from the imagefs's lib/gstreamer-1.0 by name
|
||||
# (libgst<name>.so): Proton's usual set as far as this imagefs has it (no vpx; videoconvert+videoscale are videoconvertscale).
|
||||
coreelements
|
||||
app
|
||||
audioconvert
|
||||
audiorate
|
||||
audioresample
|
||||
ogg
|
||||
opus
|
||||
pbtypes
|
||||
playback
|
||||
rawparse
|
||||
subparse
|
||||
theora
|
||||
typefindfunctions
|
||||
videoconvertscale
|
||||
videorate
|
||||
volume
|
||||
vorbis
|
||||
apetag
|
||||
audioparsers
|
||||
autodetect
|
||||
avi
|
||||
deinterlace
|
||||
id3demux
|
||||
interleave
|
||||
isomp4
|
||||
matroska
|
||||
mpg123
|
||||
videocrop
|
||||
videofilter
|
||||
wavparse
|
||||
flac
|
||||
videoparsersbad
|
||||
libav
|
||||
asf
|
||||
dvdsub
|
||||
mpegpsdemux
|
||||
mpegtsdemux
|
||||
jpeg
|
||||
png
|
||||
@@ -0,0 +1,258 @@
|
||||
// gstag: tags top-level X windows whose WM_CLASS contains <match> (any case) with
|
||||
// STEAM_GAME=<appid>, so gamescope treats a game started outside Steam's process tree
|
||||
// as the game (stand-in until a bionic winex11 sets STEAM_GAME itself).
|
||||
// Usage: gstag <display> <appid> <match> <seconds> [stop when this pid exits]
|
||||
// gamescope publishes focus (GAMESCOPE_FOCUSED_APP) and reads GAMESCOPECTRL_BASELAYER_APPID on its first X server
|
||||
// (:0, Steam's); with several (DroidDeck: games on :1) those two are read and written there.
|
||||
// If gamescope still focuses another app 8 s after the tag, it sets GAMESCOPECTRL_BASELAYER_APPID once to
|
||||
// <appid>,769 (what Steam writes when it shows a game); Steam can change it again later (e.g. the Steam button).
|
||||
#define _GNU_SOURCE
|
||||
#include <errno.h>
|
||||
#include <signal.h>
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/select.h>
|
||||
#include <sys/socket.h>
|
||||
#include <sys/un.h>
|
||||
#include <time.h>
|
||||
#include <unistd.h>
|
||||
|
||||
static int fd;
|
||||
static uint8_t rbuf[1 << 16];
|
||||
static uint32_t pending[256]; static int npending;
|
||||
static uint32_t tagged[256]; static int ntagged;
|
||||
|
||||
static int wr(const void *p, size_t n) {
|
||||
const uint8_t *b = p;
|
||||
while (n) { ssize_t k = write(fd, b, n); if (k <= 0) return -1; b += k; n -= (size_t)k; }
|
||||
return 0;
|
||||
}
|
||||
static int rd(void *p, size_t n) {
|
||||
uint8_t *b = p;
|
||||
while (n) { ssize_t k = read(fd, b, n); if (k <= 0) return -1; b += k; n -= (size_t)k; }
|
||||
return 0;
|
||||
}
|
||||
static size_t pad4(size_t n) { return (n + 3) & ~(size_t)3; }
|
||||
static int known(uint32_t *list, int n, uint32_t w) { for (int i = 0; i < n; i++) if (list[i] == w) return 1; return 0; }
|
||||
|
||||
static void note_event(const uint8_t *e) {
|
||||
uint8_t type = e[0] & 0x7f;
|
||||
uint32_t win = 0;
|
||||
if (type == 16) win = *(uint32_t *)(e + 8); // CreateNotify
|
||||
else if (type == 19) win = *(uint32_t *)(e + 8); // MapNotify
|
||||
if (win && !known(tagged, ntagged, win) && !known(pending, npending, win) && npending < 256) pending[npending++] = win;
|
||||
}
|
||||
|
||||
// Reads one packet. Returns 1 reply, 0 error, -1 io; events are noted and skipped.
|
||||
static int reply(void) {
|
||||
for (;;) {
|
||||
if (rd(rbuf, 32)) return -1;
|
||||
if (rbuf[0] == 0) return 0;
|
||||
if (rbuf[0] == 1) {
|
||||
uint32_t extra = *(uint32_t *)(rbuf + 4) * 4;
|
||||
if (extra > sizeof rbuf - 32 || (extra && rd(rbuf + 32, extra))) return -1;
|
||||
return 1;
|
||||
}
|
||||
note_event(rbuf);
|
||||
}
|
||||
}
|
||||
|
||||
static uint32_t intern(const char *name) {
|
||||
size_t n = strlen(name);
|
||||
uint8_t req[256] = {0};
|
||||
req[0] = 16;
|
||||
*(uint16_t *)(req + 2) = (uint16_t)(2 + pad4(n) / 4);
|
||||
*(uint16_t *)(req + 4) = (uint16_t)n;
|
||||
memcpy(req + 8, name, n);
|
||||
if (wr(req, 8 + pad4(n))) return 0;
|
||||
return reply() == 1 ? *(uint32_t *)(rbuf + 8) : 0;
|
||||
}
|
||||
|
||||
// WM_CLASS of a window into out (both strings joined by '|'); 0 if none.
|
||||
static int wm_class(uint32_t win, char *out, size_t cap) {
|
||||
uint8_t req[24] = {0};
|
||||
req[0] = 20;
|
||||
*(uint16_t *)(req + 2) = 6;
|
||||
*(uint32_t *)(req + 4) = win;
|
||||
*(uint32_t *)(req + 8) = 67; // WM_CLASS
|
||||
*(uint32_t *)(req + 12) = 31; // STRING
|
||||
*(uint32_t *)(req + 20) = 64;
|
||||
if (wr(req, sizeof req) || reply() != 1) return 0;
|
||||
uint32_t n = *(uint32_t *)(rbuf + 16);
|
||||
if (!n || n >= cap) return 0;
|
||||
for (uint32_t i = 0; i < n; i++) out[i] = rbuf[32 + i] ? (char)rbuf[32 + i] : '|';
|
||||
out[n] = 0;
|
||||
return 1;
|
||||
}
|
||||
|
||||
static void set_cards(uint32_t win, uint32_t prop, const uint32_t *values, uint32_t n) {
|
||||
uint8_t req[24 + 4 * 8] = {0};
|
||||
if (n > 8) n = 8;
|
||||
req[0] = 18;
|
||||
*(uint16_t *)(req + 2) = (uint16_t)(6 + n);
|
||||
*(uint32_t *)(req + 4) = win;
|
||||
*(uint32_t *)(req + 8) = prop;
|
||||
*(uint32_t *)(req + 12) = 6; // CARDINAL
|
||||
req[16] = 32;
|
||||
*(uint32_t *)(req + 20) = n;
|
||||
memcpy(req + 24, values, 4 * n);
|
||||
wr(req, 24 + 4 * n);
|
||||
}
|
||||
|
||||
// First CARDINAL of a root property, or 0 when unset.
|
||||
static uint32_t first_card(uint32_t root, uint32_t prop) {
|
||||
uint8_t gp[24] = {20, 0, 6, 0};
|
||||
*(uint32_t *)(gp + 4) = root;
|
||||
*(uint32_t *)(gp + 8) = prop;
|
||||
*(uint32_t *)(gp + 20) = 64;
|
||||
if (wr(gp, sizeof gp) || reply() != 1) return 0;
|
||||
return *(uint32_t *)(rbuf + 16) ? *(uint32_t *)(rbuf + 32) : 0;
|
||||
}
|
||||
|
||||
static void set_card(uint32_t win, uint32_t prop, uint32_t value) {
|
||||
uint8_t req[28] = {0};
|
||||
req[0] = 18;
|
||||
*(uint16_t *)(req + 2) = 7;
|
||||
*(uint32_t *)(req + 4) = win;
|
||||
*(uint32_t *)(req + 8) = prop;
|
||||
*(uint32_t *)(req + 12) = 6; // CARDINAL
|
||||
req[16] = 32;
|
||||
*(uint32_t *)(req + 20) = 1;
|
||||
*(uint32_t *)(req + 24) = value;
|
||||
wr(req, sizeof req);
|
||||
}
|
||||
|
||||
// Connects to display :<disp> (abstract socket) and returns the socket, its root window in *root; -1 on failure.
|
||||
static int x_connect(int disp, uint32_t *root) {
|
||||
struct sockaddr_un sa = {.sun_family = AF_UNIX};
|
||||
int n = snprintf(sa.sun_path + 1, sizeof sa.sun_path - 1, "/tmp/.X11-unix/X%d", disp);
|
||||
fd = socket(AF_UNIX, SOCK_STREAM, 0);
|
||||
if (connect(fd, (struct sockaddr *)&sa, (socklen_t)(offsetof(struct sockaddr_un, sun_path) + 1 + n))) {
|
||||
printf("gstag: connect to :%d failed: %s\n", disp, strerror(errno)); close(fd); return -1;
|
||||
}
|
||||
uint8_t setup[12] = {'l', 0, 11, 0};
|
||||
if (wr(setup, sizeof setup) || rd(rbuf, 8)) { close(fd); return -1; }
|
||||
uint32_t extra = *(uint16_t *)(rbuf + 6) * 4u;
|
||||
if (extra > sizeof rbuf - 8 || rd(rbuf + 8, extra) || rbuf[0] != 1) { printf("gstag: :%d refused\n", disp); close(fd); return -1; }
|
||||
uint8_t *d = rbuf + 8;
|
||||
uint16_t vlen = *(uint16_t *)(d + 16);
|
||||
uint8_t nformats = d[21];
|
||||
*root = *(uint32_t *)(d + 32 + pad4(vlen) + 8u * nformats);
|
||||
return fd;
|
||||
}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
if (argc < 5) { fprintf(stderr, "usage: %s <display> <appid> <match> <seconds> [pid]\n", argv[0]); return 2; }
|
||||
setvbuf(stdout, NULL, _IONBF, 0);
|
||||
int disp = atoi(argv[1]);
|
||||
uint32_t appid = (uint32_t)strtoul(argv[2], NULL, 10);
|
||||
const char *match = argv[3];
|
||||
int seconds = atoi(argv[4]);
|
||||
pid_t watch = argc > 5 ? (pid_t)atoi(argv[5]) : 0;
|
||||
|
||||
uint32_t root, croot;
|
||||
int tfd = x_connect(disp, &root), cfd = tfd;
|
||||
if (tfd < 0) return 3;
|
||||
croot = root;
|
||||
if (disp != 0) {
|
||||
int c = x_connect(0, &croot);
|
||||
if (c >= 0) cfd = c;
|
||||
else croot = root;
|
||||
}
|
||||
fd = tfd;
|
||||
uint32_t a_game = intern("STEAM_GAME");
|
||||
|
||||
uint8_t cwa[16] = {2, 0, 4, 0}; // ChangeWindowAttributes(root, CWEventMask=SubstructureNotify)
|
||||
*(uint32_t *)(cwa + 4) = root;
|
||||
*(uint32_t *)(cwa + 8) = 0x800;
|
||||
*(uint32_t *)(cwa + 12) = 0x80000;
|
||||
wr(cwa, sizeof cwa);
|
||||
|
||||
uint8_t qt[8] = {15, 0, 2, 0}; // QueryTree(root): windows that exist already
|
||||
*(uint32_t *)(qt + 4) = root;
|
||||
if (wr(qt, sizeof qt) == 0 && reply() == 1) {
|
||||
uint16_t nk = *(uint16_t *)(rbuf + 16);
|
||||
uint32_t kids[1024];
|
||||
if (nk > 1024) nk = 1024;
|
||||
memcpy(kids, rbuf + 32, nk * 4u);
|
||||
for (int i = 0; i < nk && npending < 256; i++) pending[npending++] = kids[i];
|
||||
}
|
||||
printf("gstag: watching display %d for WM_CLASS ~ \"%s\" -> STEAM_GAME=%u\n", disp, match, appid);
|
||||
|
||||
fd = cfd; // atoms belong to the server they are interned on
|
||||
uint32_t a_apps = intern("GAMESCOPE_FOCUSABLE_APPS");
|
||||
uint32_t a_focus = intern("GAMESCOPE_FOCUSED_APP");
|
||||
uint32_t a_ctrl = intern("GAMESCOPECTRL_BASELAYER_APPID");
|
||||
fd = tfd;
|
||||
time_t tagged_at = 0; int focus_checked = 0;
|
||||
time_t end = time(NULL) + seconds, next_status = time(NULL) + 3;
|
||||
while (time(NULL) < end) {
|
||||
if (time(NULL) >= next_status) {
|
||||
next_status = time(NULL) + 5;
|
||||
printf("status:");
|
||||
uint32_t props[3] = {a_apps, a_focus, a_ctrl};
|
||||
const char *names[3] = {"focusable", "focused", "baselayer"};
|
||||
fd = cfd;
|
||||
for (int k = 0; k < 3; k++) {
|
||||
uint8_t gp[24] = {20, 0, 6, 0};
|
||||
*(uint32_t *)(gp + 4) = croot;
|
||||
*(uint32_t *)(gp + 8) = props[k];
|
||||
*(uint32_t *)(gp + 20) = 64;
|
||||
if (wr(gp, sizeof gp) == 0 && reply() == 1) {
|
||||
uint32_t cnt = *(uint32_t *)(rbuf + 16);
|
||||
printf(" %s=[", names[k]);
|
||||
for (uint32_t i = 0; i < cnt && i < 16; i++) printf("%s%u", i ? "," : "", ((uint32_t *)(rbuf + 32))[i]);
|
||||
printf("]");
|
||||
}
|
||||
}
|
||||
fd = tfd;
|
||||
for (int i = 0; i < ntagged; i++) {
|
||||
uint8_t ga[8] = {3, 0, 2, 0}; // GetWindowAttributes
|
||||
*(uint32_t *)(ga + 4) = tagged[i];
|
||||
int map = -1, ovr = -1, w = -1, h = -1;
|
||||
if (wr(ga, sizeof ga) == 0 && reply() == 1) { map = rbuf[26]; ovr = rbuf[27]; }
|
||||
uint8_t gg[8] = {14, 0, 2, 0}; // GetGeometry
|
||||
*(uint32_t *)(gg + 4) = tagged[i];
|
||||
if (wr(gg, sizeof gg) == 0 && reply() == 1) { w = *(uint16_t *)(rbuf + 16); h = *(uint16_t *)(rbuf + 18); }
|
||||
printf(" win0x%x=%dx%d map%d ovr%d", tagged[i], w, h, map, ovr);
|
||||
}
|
||||
printf("\n");
|
||||
}
|
||||
if (tagged_at && !focus_checked && time(NULL) - tagged_at >= 8) {
|
||||
focus_checked = 1;
|
||||
fd = cfd;
|
||||
uint32_t f = first_card(croot, a_focus);
|
||||
if (f != appid) {
|
||||
uint32_t ids[2] = {appid, 769};
|
||||
set_cards(croot, a_ctrl, ids, 2);
|
||||
printf("gstag: focus was %u, not %u, 8 s after the tag; set GAMESCOPECTRL_BASELAYER_APPID=%u,769\n", f, appid, appid);
|
||||
} else printf("gstag: %u has focus\n", appid);
|
||||
fd = tfd;
|
||||
}
|
||||
if (watch && kill(watch, 0) != 0 && errno == ESRCH) { printf("gstag: pid %d gone, stopping\n", watch); break; }
|
||||
for (int i = 0; i < npending; ) {
|
||||
char cls[512];
|
||||
uint32_t w = pending[i];
|
||||
if (wm_class(w, cls, sizeof cls) && strcasestr(cls, match)) {
|
||||
set_card(w, a_game, appid);
|
||||
if (ntagged < 256) tagged[ntagged++] = w;
|
||||
if (!tagged_at) tagged_at = time(NULL);
|
||||
printf("gstag: tagged window 0x%x (%s)\n", w, cls);
|
||||
pending[i] = pending[--npending];
|
||||
} else i++;
|
||||
}
|
||||
fd_set rs; FD_ZERO(&rs); FD_SET(fd, &rs);
|
||||
struct timeval tv = {0, 500000};
|
||||
if (select(fd + 1, &rs, NULL, NULL, &tv) > 0) {
|
||||
if (rd(rbuf, 32)) { printf("gstag: connection closed\n"); break; }
|
||||
if (rbuf[0] == 1) { uint32_t x = *(uint32_t *)(rbuf + 4) * 4; if (x && rd(rbuf + 32, x)) break; }
|
||||
else if (rbuf[0] != 0) note_event(rbuf);
|
||||
}
|
||||
if (npending > 200) npending = 0;
|
||||
}
|
||||
printf("gstag: done, %d window(s) tagged\n", ntagged);
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"file_format_version": "1.0.0",
|
||||
"ICD": { "library_path": "./libvulkan_wrapper.so", "api_version": "1.3.0" }
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
// Turns off Android's heap pointer tagging (TBI) in the bionic Wine processes it is preloaded into.
|
||||
// Wine/FEX paths can hand free() a pointer whose top byte was dropped; with tagging on, bionic aborts
|
||||
// ("Pointer tag for 0x... was truncated"). Going from TBI to none at run time is allowed by bionic.
|
||||
// mallopt is looked up at run time, so the file builds with any NDK API level.
|
||||
#include <dlfcn.h>
|
||||
#define M_BIONIC_SET_HEAP_TAGGING_LEVEL_OPT (-204)
|
||||
#define M_HEAP_TAGGING_LEVEL_NONE_VAL 0
|
||||
__attribute__((constructor(101))) static void ddbionic_notag(void) {
|
||||
int (*mallopt_fn)(int, int) = (int (*)(int, int))dlsym(RTLD_DEFAULT, "mallopt");
|
||||
if (mallopt_fn) mallopt_fn(M_BIONIC_SET_HEAP_TAGGING_LEVEL_OPT, M_HEAP_TAGGING_LEVEL_NONE_VAL);
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
# Android (bionic) libraries the bionic DroidDeck-Proton layer needs from Bannerlator's base imagefs (usr/lib), by name.
|
||||
# Made 2026-11-16 from the NEEDED closure of layer v16 (proton-wine 067c719d) lib/wine/aarch64-unix + bin, plus the
|
||||
# libraries Wine opens by name (strings of its unix modules), the Wayland adapter and the gamescope WSI layer.
|
||||
# libGL.so.1 is left out: it is a dangling link in this imagefs (OpenGL games are not covered yet).
|
||||
libSDL2.so
|
||||
libX11-xcb.so
|
||||
libX11-xcb.so.1
|
||||
libX11.so
|
||||
libX11.so.6
|
||||
libXau.so.6
|
||||
libXcursor.so
|
||||
libXext.so
|
||||
libXext.so.6
|
||||
libXfixes.so
|
||||
libXfixes.so.3
|
||||
libXi.so
|
||||
libXrandr.so
|
||||
libXrender.so
|
||||
libXrender.so.1
|
||||
libadrenotools.so
|
||||
libandroid-support.so
|
||||
libandroid-sysv-semaphore.so
|
||||
libandroid-sysvshm.so
|
||||
libasound.so
|
||||
libbrotlicommon.so.1
|
||||
libbrotlidec.so.1
|
||||
libbz2.so.1.0
|
||||
libc++_shared.so
|
||||
libexpat.so.1
|
||||
libffi.so
|
||||
libfile_redirect_hook.so
|
||||
libfontconfig.so
|
||||
libfreetype.so
|
||||
libfreetype.so.6
|
||||
libgio-2.0.so.0
|
||||
libglib-2.0.so.0
|
||||
libgmodule-2.0.so.0
|
||||
libgmp.so
|
||||
libgmp.so.10
|
||||
libgnutls.so
|
||||
libgobject-2.0.so.0
|
||||
libgsl_alloc_hook.so
|
||||
libgstapp-1.0.so
|
||||
libgstaudio-1.0.so
|
||||
libgstbase-1.0.so
|
||||
libgstbase-1.0.so.0
|
||||
libgstgl-1.0.so
|
||||
libgstreamer-1.0.so
|
||||
libgstreamer-1.0.so.0
|
||||
libgsttag-1.0.so
|
||||
libgsttag-1.0.so.0
|
||||
libgstvideo-1.0.so
|
||||
libgstvideo-1.0.so.0
|
||||
libhogweed.so.6
|
||||
libhook_impl.so
|
||||
libiconv.so
|
||||
libidn2.so.0
|
||||
libmain_hook.so
|
||||
libnettle.so.8
|
||||
libpcre2-8.so.0
|
||||
libpng16.so
|
||||
libpulse.so
|
||||
libpulsecommon-13.0.so
|
||||
libsndfile.so
|
||||
libunistring.so
|
||||
libvulkan.so.1
|
||||
libxcb-composite.so
|
||||
libxcb-composite.so.0
|
||||
libxcb-dri3.so
|
||||
libxcb-present.so
|
||||
libxcb-randr.so
|
||||
libxcb-shm.so
|
||||
libxcb-sync.so
|
||||
libxcb.so
|
||||
libxcb.so.1
|
||||
libxml2.so.16
|
||||
libz.so
|
||||
libz.so.1
|
||||
@@ -0,0 +1,450 @@
|
||||
// Valve's Android libsteamclient keeps its named shared memory ("/u<uid>-Shm_<crc>" streams and the
|
||||
// "/u<uid>-ValveIPCSharedObj-Steam" object that holds the named locks and events) in a table inside the process, so
|
||||
// the Steam Input data DroidDeck's Linux Steam publishes in /dev/shm never reaches a game on DroidDeck-Bionic. Once
|
||||
// that library is loaded, this preload makes it use the files the Linux client uses: DROIDDECK_BIONIC_SHM_DIR
|
||||
// (DroidDeck's /dev/shm) under Steam's user id. DROIDDECK_BIONIC_STEAMSHM=0 turns it off.
|
||||
// The library's thread semaphores come from sem_open with a per-object name ("%p"), which Android's libc does not
|
||||
// implement (it always fails), so this preload also gives sem_open/sem_close a table of in-process semaphores.
|
||||
#define _GNU_SOURCE
|
||||
#include <dirent.h>
|
||||
#include <dlfcn.h>
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <limits.h>
|
||||
#include <link.h>
|
||||
#include <pthread.h>
|
||||
#include <stdarg.h>
|
||||
#include <stdbool.h>
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <semaphore.h>
|
||||
#include <sys/auxv.h>
|
||||
#include <sys/mman.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#define EXPORT __attribute__((visibility("default")))
|
||||
|
||||
typedef int (*shm_open_fn)(const char *name, size_t size, bool *created);
|
||||
typedef void (*shm_unlink_fn)(const char *name);
|
||||
|
||||
static shm_open_fn orig_open;
|
||||
static shm_unlink_fn orig_unlink;
|
||||
static char shm_dir[PATH_MAX];
|
||||
static char steam_uid[16];
|
||||
static int notes;
|
||||
|
||||
static void say(const char *fmt, ...)
|
||||
{
|
||||
char b[600];
|
||||
va_list a;
|
||||
va_start(a, fmt);
|
||||
int n = vsnprintf(b, sizeof b, fmt, a);
|
||||
va_end(a);
|
||||
if (n > 0) write(2, b, n < (int)sizeof b ? (size_t)n : sizeof b - 1);
|
||||
}
|
||||
|
||||
// "/u<digits>-Shm_<hex>" or "/u<digits>-ValveIPCSharedObj-Steam": the part after the uid, else NULL.
|
||||
static const char *shared_part(const char *name)
|
||||
{
|
||||
if (!name || name[0] != '/' || name[1] != 'u') return NULL;
|
||||
const char *p = name + 2;
|
||||
while (*p >= '0' && *p <= '9') p++;
|
||||
if (p == name + 2 || *p != '-') return NULL;
|
||||
if (!strcmp(p + 1, "ValveIPCSharedObj-Steam")) return p + 1;
|
||||
const char *h = p + 5;
|
||||
if (strncmp(p + 1, "Shm_", 4)) return NULL;
|
||||
while ((*h >= '0' && *h <= '9') || (*h >= 'a' && *h <= 'f')) h++;
|
||||
return h > p + 5 && h <= p + 13 && !*h ? p + 1 : NULL;
|
||||
}
|
||||
|
||||
// The uid Steam put in its IPC object's name (DroidDeck's Linux side reports 0).
|
||||
static const char *uid_of_steam(void)
|
||||
{
|
||||
if (steam_uid[0]) return steam_uid;
|
||||
DIR *d = opendir(shm_dir);
|
||||
struct dirent *e;
|
||||
while (d && (e = readdir(d))) {
|
||||
const char *n = e->d_name, *p = n + 1;
|
||||
if (n[0] != 'u') continue;
|
||||
while (*p >= '0' && *p <= '9') p++;
|
||||
if (p > n + 1 && p - n - 1 < (long)sizeof steam_uid && !strcmp(p, "-ValveIPCSharedObj-Steam")) {
|
||||
memcpy(steam_uid, n + 1, (size_t)(p - n - 1));
|
||||
steam_uid[p - n - 1] = 0;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (d) closedir(d);
|
||||
if (!steam_uid[0]) return "0";
|
||||
return steam_uid;
|
||||
}
|
||||
|
||||
static bool real_path(const char *part, char *out, size_t n)
|
||||
{
|
||||
int w = snprintf(out, n, "%s/u%s-%s", shm_dir, uid_of_steam(), part);
|
||||
return w > 0 && (size_t)w < n;
|
||||
}
|
||||
|
||||
static int hook_open(const char *name, size_t size, bool *created)
|
||||
{
|
||||
const char *part = shared_part(name);
|
||||
char path[PATH_MAX];
|
||||
if (!part || !real_path(part, path, sizeof path)) return orig_open(name, size, created);
|
||||
for (int i = 0; i < 4; i++) {
|
||||
int fd = open(path, O_RDWR | O_CLOEXEC);
|
||||
if (fd >= 0) {
|
||||
if (notes++ < 64) say("steamshm: %s opened (%zu bytes)\n", path, size);
|
||||
return fd;
|
||||
}
|
||||
if (errno != ENOENT) break;
|
||||
fd = open(path, O_RDWR | O_CREAT | O_EXCL | O_CLOEXEC, 0600);
|
||||
if (fd >= 0) {
|
||||
if (ftruncate(fd, (off_t)size) == 0) {
|
||||
if (created) *created = true;
|
||||
if (notes++ < 64) say("steamshm: %s created (%zu bytes)\n", path, size);
|
||||
return fd;
|
||||
}
|
||||
close(fd);
|
||||
unlink(path);
|
||||
break;
|
||||
}
|
||||
if (errno != EEXIST) break;
|
||||
}
|
||||
say("steamshm: %s failed (errno %d)\n", path, errno);
|
||||
return -1;
|
||||
}
|
||||
|
||||
static void hook_unlink(const char *name)
|
||||
{
|
||||
const char *part = shared_part(name);
|
||||
char path[PATH_MAX];
|
||||
// Steam's IPC object belongs to Steam: never removed from a game
|
||||
if (!part || !strncmp(part, "Valve", 5) || !real_path(part, path, sizeof path)) {
|
||||
orig_unlink(name);
|
||||
return;
|
||||
}
|
||||
if (unlink(path) == 0 && notes++ < 64) say("steamshm: %s removed\n", path);
|
||||
}
|
||||
|
||||
struct object {
|
||||
uintptr_t base;
|
||||
uintptr_t lo[8], hi[8];
|
||||
bool exec[8];
|
||||
int n;
|
||||
};
|
||||
|
||||
static int find_object(struct dl_phdr_info *info, size_t size, void *data)
|
||||
{
|
||||
(void)size;
|
||||
struct object *o = data;
|
||||
const char *n = info->dlpi_name;
|
||||
size_t l = n ? strlen(n) : 0;
|
||||
if (l < 18 || strcmp(n + l - 18, "/libsteamclient.so")) return 0;
|
||||
o->base = info->dlpi_addr;
|
||||
o->n = 0;
|
||||
for (int i = 0; i < info->dlpi_phnum && o->n < 8; i++) {
|
||||
const ElfW(Phdr) *p = &info->dlpi_phdr[i];
|
||||
if (p->p_type != PT_LOAD) continue;
|
||||
o->lo[o->n] = info->dlpi_addr + p->p_vaddr;
|
||||
o->hi[o->n] = o->lo[o->n] + p->p_memsz;
|
||||
o->exec[o->n] = (p->p_flags & PF_X) != 0;
|
||||
o->n++;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
static bool readable(const struct object *o, uintptr_t a, size_t n)
|
||||
{
|
||||
for (int i = 0; i < o->n; i++)
|
||||
if (a >= o->lo[i] && a + n <= o->hi[i]) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
static int64_t sext(uint64_t v, int bits)
|
||||
{
|
||||
return (int64_t)(v << (64 - bits)) >> (64 - bits);
|
||||
}
|
||||
|
||||
// adrp xd at w[0] and add xd, xd, #imm at w[1]: the address they form, or 0.
|
||||
static uintptr_t adrp_add(const uint32_t *w, int reg)
|
||||
{
|
||||
if ((w[0] & 0x9f000000) != 0x90000000 || (int)(w[0] & 31) != reg) return 0;
|
||||
if ((w[1] & 0xffc00000) != 0x91000000 || (int)(w[1] & 31) != reg || (int)((w[1] >> 5) & 31) != reg) return 0;
|
||||
uint64_t imm = ((uint64_t)((w[0] >> 5) & 0x7ffff) << 2) | ((w[0] >> 29) & 3);
|
||||
uintptr_t page = ((uintptr_t)w & ~(uintptr_t)0xfff) + (uintptr_t)(sext(imm, 21) << 12);
|
||||
return page + ((w[1] >> 10) & 0xfff);
|
||||
}
|
||||
|
||||
static uintptr_t bl_target(const uint32_t *w)
|
||||
{
|
||||
if ((w[0] & 0xfc000000) != 0x94000000) return 0;
|
||||
return (uintptr_t)w + (uintptr_t)(sext(w[0] & 0x3ffffff, 26) << 2);
|
||||
}
|
||||
|
||||
// The first four instructions get copied into a trampoline: none may depend on the pc.
|
||||
static bool relocatable(const uint32_t *w)
|
||||
{
|
||||
for (int i = 0; i < 4; i++) {
|
||||
uint32_t x = w[i];
|
||||
if ((x & 0x1f000000) == 0x10000000 || (x & 0x7c000000) == 0x14000000 || (x & 0xff000010) == 0x54000000 ||
|
||||
(x & 0x7e000000) == 0x34000000 || (x & 0x7e000000) == 0x36000000 || (x & 0x3b000000) == 0x18000000)
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// Back from w to the frame setup: stp x29, x30, [sp, #-N]!, or sub sp, sp, #N then stp x29, x30, [sp, #M].
|
||||
static uint32_t *function_start(const struct object *o, uint32_t *w)
|
||||
{
|
||||
for (int i = 0; i < 256; i++, w--) {
|
||||
if (!readable(o, (uintptr_t)w - 4, 8)) return NULL;
|
||||
if ((*w & 0xffc07fff) == 0xa9807bfd) return w;
|
||||
if ((*w & 0xffc07fff) == 0xa9007bfd) return (w[-1] & 0xff8003ff) == 0xd10003ff ? w - 1 : NULL;
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
// open(".", O_TMPFILE | O_RDWR, 0777) in the library's shared-memory open: its only nameless file.
|
||||
static uint32_t *find_shm_open(const struct object *o)
|
||||
{
|
||||
uint32_t *found = NULL;
|
||||
for (int s = 0; s < o->n; s++) {
|
||||
if (!o->exec[s]) continue;
|
||||
for (uint32_t *w = (uint32_t *)o->lo[s]; (uintptr_t)(w + 6) <= o->hi[s]; w++) {
|
||||
if (w[0] != 0x52880041 || w[3] != 0x72a00801 || w[4] != 0x52803fe2 || !bl_target(w + 5)) continue;
|
||||
uintptr_t str = adrp_add(w + 1, 0);
|
||||
if (!str || !readable(o, str, 2) || memcmp((const char *)str, ".", 2)) continue;
|
||||
if (found) return NULL;
|
||||
found = w;
|
||||
}
|
||||
}
|
||||
return found ? function_start(o, found) : NULL;
|
||||
}
|
||||
|
||||
static const char *find_string(const struct object *o, const char *s)
|
||||
{
|
||||
size_t n = strlen(s) + 1;
|
||||
for (int i = 0; i < o->n; i++) {
|
||||
const char *p = memmem((const void *)o->lo[i], o->hi[i] - o->lo[i], s, n);
|
||||
if (p) return p;
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
// CSharedMemory::Open: snprintf of "/u%d-Shm_%x", a call to the unlink with that name, then the open.
|
||||
static uint32_t *find_shm_unlink(const struct object *o, uintptr_t open_fn)
|
||||
{
|
||||
const char *fmt = find_string(o, "/u%d-Shm_%x");
|
||||
uint32_t *found = NULL;
|
||||
if (!fmt) return NULL;
|
||||
for (int s = 0; s < o->n; s++) {
|
||||
if (!o->exec[s]) continue;
|
||||
for (uint32_t *w = (uint32_t *)o->lo[s]; (uintptr_t)(w + 64) <= o->hi[s]; w++) {
|
||||
if ((w[0] & 0x9f000000) != 0x90000000 || adrp_add(w, (int)(w[0] & 31)) != (uintptr_t)fmt) continue;
|
||||
uint32_t *p = w + 2, *end = w + 12;
|
||||
while (p < end && !bl_target(p)) p++; // snprintf
|
||||
if (p == end) continue;
|
||||
uint32_t *u = p + 1;
|
||||
end = p + 5;
|
||||
while (u < end && !bl_target(u)) u++;
|
||||
if (u == end) continue;
|
||||
bool opens = false;
|
||||
for (uint32_t *q = u + 1; q < u + 48; q++)
|
||||
if (bl_target(q) == open_fn) opens = true;
|
||||
if (!opens) continue;
|
||||
uint32_t *fn = (uint32_t *)bl_target(u);
|
||||
if (found && found != fn) return NULL;
|
||||
found = fn;
|
||||
}
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
static void flush(uintptr_t a, size_t n)
|
||||
{
|
||||
uint64_t ctr;
|
||||
__asm__ volatile("mrs %0, ctr_el0" : "=r"(ctr));
|
||||
uintptr_t d = 4u << ((ctr >> 16) & 15), i = 4u << (ctr & 15), x;
|
||||
for (x = a & ~(d - 1); x < a + n; x += d) __asm__ volatile("dc cvau, %0" ::"r"(x) : "memory");
|
||||
__asm__ volatile("dsb ish" ::: "memory");
|
||||
for (x = a & ~(i - 1); x < a + n; x += i) __asm__ volatile("ic ivau, %0" ::"r"(x) : "memory");
|
||||
__asm__ volatile("dsb ish\n\tisb" ::: "memory");
|
||||
}
|
||||
|
||||
static void jump_code(uint32_t *out, uintptr_t to)
|
||||
{
|
||||
out[0] = 0x58000050; // ldr x16, #8
|
||||
out[1] = 0xd61f0200; // br x16
|
||||
memcpy(out + 2, &to, 8);
|
||||
}
|
||||
|
||||
static void *trampoline(uint32_t *fn)
|
||||
{
|
||||
size_t page = getauxval(AT_PAGESZ);
|
||||
uint32_t *t = mmap(NULL, page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
|
||||
if (t == MAP_FAILED) return NULL;
|
||||
memcpy(t, fn, 16);
|
||||
jump_code(t + 4, (uintptr_t)(fn + 4));
|
||||
if (mprotect(t, page, PROT_READ | PROT_EXEC)) return NULL;
|
||||
flush((uintptr_t)t, 32);
|
||||
return t;
|
||||
}
|
||||
|
||||
// The library's code pages are file mappings: write an anonymous copy and move it over the original in one step.
|
||||
static bool redirect(uint32_t *fn, uintptr_t to)
|
||||
{
|
||||
size_t page = getauxval(AT_PAGESZ);
|
||||
uintptr_t lo = (uintptr_t)fn & ~(page - 1), hi = ((uintptr_t)fn + 16 + page - 1) & ~(page - 1);
|
||||
size_t len = hi - lo;
|
||||
uint8_t *copy = mmap(NULL, len, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
|
||||
if (copy == MAP_FAILED) return false;
|
||||
memcpy(copy, (void *)lo, len);
|
||||
jump_code((uint32_t *)(copy + ((uintptr_t)fn - lo)), to);
|
||||
if (mprotect(copy, len, PROT_READ | PROT_EXEC) ||
|
||||
mremap(copy, len, len, MREMAP_MAYMOVE | MREMAP_FIXED, (void *)lo) == MAP_FAILED) {
|
||||
munmap(copy, len);
|
||||
return false;
|
||||
}
|
||||
flush(lo, len);
|
||||
return true;
|
||||
}
|
||||
|
||||
static void install(void)
|
||||
{
|
||||
const char *mode = getenv("DROIDDECK_BIONIC_STEAMSHM");
|
||||
const char *dir = getenv("DROIDDECK_BIONIC_SHM_DIR");
|
||||
struct object o = {0};
|
||||
uint32_t *open_fn, *unlink_fn = NULL;
|
||||
if (mode && !strcmp(mode, "0")) return;
|
||||
if (!dir || !*dir || strlen(dir) >= sizeof shm_dir) {
|
||||
say("steamshm: no DROIDDECK_BIONIC_SHM_DIR; Steam Input data stays in the library\n");
|
||||
return;
|
||||
}
|
||||
strcpy(shm_dir, dir);
|
||||
if (!dl_iterate_phdr(find_object, &o)) {
|
||||
say("steamshm: libsteamclient.so not found among the loaded libraries\n");
|
||||
return;
|
||||
}
|
||||
open_fn = find_shm_open(&o);
|
||||
unlink_fn = open_fn ? find_shm_unlink(&o, (uintptr_t)open_fn) : NULL;
|
||||
if (!open_fn || !unlink_fn || !relocatable(open_fn) || !relocatable(unlink_fn)) {
|
||||
say("steamshm: this libsteamclient.so does not match (open %p, unlink %p); left as it is\n",
|
||||
(void *)open_fn, (void *)unlink_fn);
|
||||
return;
|
||||
}
|
||||
orig_open = (shm_open_fn)trampoline(open_fn);
|
||||
orig_unlink = (shm_unlink_fn)trampoline(unlink_fn);
|
||||
if (!orig_open || !orig_unlink || !redirect(unlink_fn, (uintptr_t)hook_unlink) ||
|
||||
!redirect(open_fn, (uintptr_t)hook_open)) {
|
||||
say("steamshm: could not redirect the library's shared memory; left as it is\n");
|
||||
return;
|
||||
}
|
||||
say("steamshm: libsteamclient.so +%#lx open / +%#lx unlink use %s (Steam uid %s)\n",
|
||||
(unsigned long)((uintptr_t)open_fn - o.base), (unsigned long)((uintptr_t)unlink_fn - o.base), shm_dir,
|
||||
uid_of_steam());
|
||||
}
|
||||
|
||||
struct named_sem {
|
||||
struct named_sem *next;
|
||||
sem_t sem;
|
||||
int refs;
|
||||
char name[];
|
||||
};
|
||||
|
||||
static struct named_sem *sems;
|
||||
static pthread_mutex_t sems_lock = PTHREAD_MUTEX_INITIALIZER;
|
||||
|
||||
// Named semaphores of this process only: the last sem_close frees one (there is no sem_unlink to wait for).
|
||||
EXPORT sem_t *sem_open(const char *name, int oflag, ...)
|
||||
{
|
||||
unsigned value = 0;
|
||||
if (oflag & O_CREAT) {
|
||||
va_list a;
|
||||
va_start(a, oflag);
|
||||
(void)va_arg(a, unsigned); // mode
|
||||
value = va_arg(a, unsigned);
|
||||
va_end(a);
|
||||
}
|
||||
if (!*name) {
|
||||
errno = EINVAL;
|
||||
return SEM_FAILED;
|
||||
}
|
||||
sem_t *r = SEM_FAILED;
|
||||
pthread_mutex_lock(&sems_lock);
|
||||
struct named_sem *s = sems;
|
||||
while (s && strcmp(s->name, name)) s = s->next;
|
||||
if (s && (oflag & O_CREAT) && (oflag & O_EXCL)) {
|
||||
errno = EEXIST;
|
||||
} else if (s) {
|
||||
s->refs++;
|
||||
r = &s->sem;
|
||||
} else if (!(oflag & O_CREAT)) {
|
||||
errno = ENOENT;
|
||||
} else if ((s = calloc(1, sizeof *s + strlen(name) + 1))) {
|
||||
strcpy(s->name, name);
|
||||
if (sem_init(&s->sem, 0, value) == 0) {
|
||||
s->refs = 1;
|
||||
s->next = sems;
|
||||
sems = s;
|
||||
r = &s->sem;
|
||||
} else {
|
||||
free(s);
|
||||
}
|
||||
} else {
|
||||
errno = ENOMEM;
|
||||
}
|
||||
pthread_mutex_unlock(&sems_lock);
|
||||
return r;
|
||||
}
|
||||
|
||||
EXPORT int sem_close(sem_t *sem)
|
||||
{
|
||||
int r = -1;
|
||||
pthread_mutex_lock(&sems_lock);
|
||||
struct named_sem **p = &sems;
|
||||
while (*p && &(*p)->sem != sem) p = &(*p)->next;
|
||||
if (*p) {
|
||||
struct named_sem *s = *p;
|
||||
r = 0;
|
||||
if (--s->refs == 0) {
|
||||
*p = s->next;
|
||||
sem_destroy(&s->sem);
|
||||
free(s);
|
||||
}
|
||||
} else {
|
||||
errno = EINVAL;
|
||||
}
|
||||
pthread_mutex_unlock(&sems_lock);
|
||||
return r;
|
||||
}
|
||||
|
||||
static long raw_getuid(void)
|
||||
{
|
||||
register long x8 __asm__("x8") = 174; // __NR_getuid
|
||||
register long x0 __asm__("x0");
|
||||
__asm__ volatile("svc #0" : "=r"(x0) : "r"(x8) : "memory");
|
||||
return x0;
|
||||
}
|
||||
|
||||
// libsteamclient asks for the uid just before it names each shared-memory object, so its first call installs the
|
||||
// redirect before the first open. Calls from anywhere else only return the uid.
|
||||
EXPORT uid_t getuid(void)
|
||||
{
|
||||
static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
|
||||
static int done;
|
||||
if (!__atomic_load_n(&done, __ATOMIC_ACQUIRE)) {
|
||||
Dl_info i;
|
||||
size_t l;
|
||||
if (dladdr(__builtin_return_address(0), &i) && i.dli_fname && (l = strlen(i.dli_fname)) >= 18 &&
|
||||
!strcmp(i.dli_fname + l - 18, "/libsteamclient.so")) {
|
||||
pthread_mutex_lock(&lock);
|
||||
if (!done) {
|
||||
install();
|
||||
__atomic_store_n(&done, 1, __ATOMIC_RELEASE);
|
||||
}
|
||||
pthread_mutex_unlock(&lock);
|
||||
}
|
||||
}
|
||||
return (uid_t)raw_getuid();
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
! DroidDeck-Bionic: an empty X resource file. XENVIRONMENT points here so libX11 has a resource database to
|
||||
! keep; with no file at all it looks for ~/.Xdefaults again on every XGetDefault call (each GDI font selection).
|
||||
@@ -0,0 +1,13 @@
|
||||
"compatibilitytools"
|
||||
{
|
||||
"compat_tools"
|
||||
{
|
||||
"@NAME@"
|
||||
{
|
||||
"install_path" "."
|
||||
"display_name" "@DISPLAY@"
|
||||
"from_oslist" "windows"
|
||||
"to_oslist" "linux"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
Windows Registry Editor Version 5.00
|
||||
|
||||
; Black instead of Wine's default colour, and no shell/taskbar or tray, if a game is run on a Wine desktop
|
||||
; (launch.sh itself runs games straight on gamescope).
|
||||
[HKEY_CURRENT_USER\Control Panel\Colors]
|
||||
"Background"="0 0 0"
|
||||
|
||||
[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\ThemeManager\Control Panel\Colors]
|
||||
"Background"="0 0 0"
|
||||
|
||||
[HKEY_CURRENT_USER\Software\Wine\Explorer\Desktops\Default]
|
||||
"EnableShell"=dword:00000000
|
||||
"ShowSystray"=dword:00000000
|
||||
@@ -0,0 +1,411 @@
|
||||
#!/system/bin/sh
|
||||
# DroidDeck-Bionic launcher, Android side. ../proton calls it: launch.sh <verb> <compatdata dir> <exe> [args...]
|
||||
# Runs <exe> on the bionic Proton layer in ../files with the prefix <compatdata>/pfx, inside DroidDeck's
|
||||
# gamescope session. Every program from app data starts through /system/bin/linker64 (targetSdk 29+ refuses
|
||||
# execve of app data files); the runtime pack's execshim does the same for Wine's own starts.
|
||||
verb=$1; COMPAT=$2; EXE=$3
|
||||
shift 3
|
||||
TOOL=$(cd "$(dirname "$0")/.." && pwd)
|
||||
F=$TOOL/files
|
||||
PACK=$F/runtime
|
||||
ROOTFS=${DROIDDECK_BIONIC_ROOT:?started without DROIDDECK_BIONIC_ROOT}
|
||||
APP=${ROOTFS%/linuxfs}
|
||||
LINKER=/system/bin/linker64
|
||||
VERSION=$(awk '{print $2}' "$TOOL/version" 2>/dev/null)
|
||||
|
||||
mkdir -p "$COMPAT"
|
||||
LOG=$COMPAT/droiddeck-bionic.log
|
||||
[ "$verb" = runinprefix ] || { [ -f "$LOG" ] && mv -f "$LOG" "$LOG.1"; }
|
||||
exec >> "$LOG" 2>&1
|
||||
echo "$(date +%H:%M:%S) $verb $EXE ($VERSION, uid $(id -u), DISPLAY ${DISPLAY:-unset})"
|
||||
|
||||
# Keep Steam's game identity, DroidDeck's input/display/driver/sync settings and its game environment (the names
|
||||
# ../proton lists in DROIDDECK_BIONIC_KEEP); drop the rest of the glibc guest's environment.
|
||||
KEEP=" ${DROIDDECK_BIONIC_KEEP:-} "
|
||||
for v in $(env | sed -n 's/^\([A-Za-z_][A-Za-z0-9_]*\)=.*/\1/p'); do
|
||||
case "$KEEP" in *" $v "*) continue ;; esac
|
||||
case "$v" in
|
||||
SteamAppId|SteamGameId|SteamOverlayGameId|SteamClientLaunch|SteamEnv|SteamAppUser|SteamUser|STEAM_COMPAT_*) ;;
|
||||
ANDROID_*|BOOTCLASSPATH|DEX2OATBOOTCLASSPATH|SYSTEMSERVERCLASSPATH|EXTERNAL_STORAGE|ASEC_MOUNTPOINT) ;;
|
||||
FAKE_*|SDL_*|DD_WIDTH|DD_HEIGHT|DD_VK_DRIVER|WINEDLLOVERRIDES) ;;
|
||||
DISPLAY|GAMESCOPE_WAYLAND_DISPLAY|FEX_*) ;;
|
||||
TU_DEBUG|MESA_NO_ERROR|DXVK_CONFIG|DXVK_HUD|DROIDDECK_FORCE_SSBS) ;;
|
||||
mesa_glthread|vblank_mode|ZINK_*|GALLIUM_HUD|GALLIUM_THREAD) ;;
|
||||
DD_SYNC|DD_FSYNC_FIRST|DD_SYNC_FALLBACK|PROTON_NO_ESYNC|PROTON_NO_FSYNC|PROTON_NO_NTSYNC|WINEESYNC) ;;
|
||||
PROTON_USE_D7VK) ;;
|
||||
XODUS_*|RUST_LOG) ;;
|
||||
WINE_OFFSCREEN_CHECK_MS|WINE_CPU_TOPOLOGY|WINE_LARGE_ADDRESS_AWARE|WINESTEAMNOEXEC|TZ) ;;
|
||||
DXVK_LOG_LEVEL|DXVK_HDR|VKD3D_DEBUG|VKD3D_SHADER_DEBUG) ;;
|
||||
DROIDDECK_GPU_LOAD|DROIDDECK_GPU_LOAD_DIR|DROIDDECK_VRAM_CAP|DROIDDECK_VRAM_CAP_MB|DROIDDECK_DISPLAY_DRIVER) ;;
|
||||
VKD3D_FEATURE_LEVEL|VKD3D_SHADER_MODEL|vk_x11_strict_image_count) ;;
|
||||
*) unset "$v" 2>/dev/null ;;
|
||||
esac
|
||||
done
|
||||
export PATH=/system/bin:/system/xbin
|
||||
# DISPLAY: the X server Steam gives games. DroidDeck's gamescope runs two (Steam's UI on :0, games on
|
||||
# STEAM_GAME_DISPLAY_0), so Steam's menus do not take X focus from the game.
|
||||
export HOME=$COMPAT WINEPREFIX=$COMPAT/pfx TMPDIR=$ROOTFS/tmp LANG=en_US.UTF-8 DISPLAY=${DISPLAY:-:0}
|
||||
# Proton's user name: the same C:\users\steamuser (saves, settings) as DroidDeck-Proton in a shared prefix
|
||||
export USER=steamuser LOGNAME=steamuser
|
||||
|
||||
# Graphics: DroidDeck's chosen Turnip (its Android half) through Bannerlator's Wayland adapter, and gamescope's
|
||||
# WSI layer handing the swapchain to gamescope (zero copy).
|
||||
drvlib() { # an Android driver folder's library: meta.json's libraryName, else libvulkan_freedreno.so
|
||||
l=$(sed -n 's/.*"libraryName"[[:space:]]*:[[:space:]]*"\([^"/]*\)".*/\1/p' "$1/meta.json" 2>/dev/null | head -1)
|
||||
echo "${l:-libvulkan_freedreno.so}"
|
||||
}
|
||||
DRV=$(basename "$(dirname "${DD_VK_DRIVER:-/x/none/icd.json}")")
|
||||
DRVDIR=$APP/graphics_driver/$DRV
|
||||
if [ ! -f "$DRVDIR/$(drvlib "$DRVDIR")" ]; then
|
||||
# The runtime driver has no Android build: the one DroidDeck's display uses, else the first one installed.
|
||||
DRVDIR=
|
||||
if [ -n "${DROIDDECK_DISPLAY_DRIVER:-}" ] && [ "${DROIDDECK_DISPLAY_DRIVER#*/}" = "$DROIDDECK_DISPLAY_DRIVER" ] && \
|
||||
[ -f "$APP/graphics_driver/$DROIDDECK_DISPLAY_DRIVER/$(drvlib "$APP/graphics_driver/$DROIDDECK_DISPLAY_DRIVER")" ]; then
|
||||
DRVDIR=$APP/graphics_driver/$DROIDDECK_DISPLAY_DRIVER
|
||||
else
|
||||
for d in "$APP"/graphics_driver/*/; do [ -f "$d$(drvlib "${d%/}")" ] && { DRVDIR=${d%/}; break; }; done
|
||||
fi
|
||||
echo "driver $DRV has no Android build; using ${DRVDIR:+$(basename "$DRVDIR")}${DRVDIR:-none} (display driver ${DROIDDECK_DISPLAY_DRIVER:-unknown})"
|
||||
fi
|
||||
echo "driver $DRVDIR"
|
||||
RTD=$APP/.wayland-rt
|
||||
export VK_ICD_FILENAMES=$PACK/adapter/icd.json ADRENOTOOLS_DRIVER_PATH=$DRVDIR/ ADRENOTOOLS_HOOKS_PATH=$PACK/lib
|
||||
export ADRENOTOOLS_DRIVER_NAME=$(drvlib "$DRVDIR")
|
||||
export VK_ADD_IMPLICIT_LAYER_PATH=$PACK/layer ENABLE_GAMESCOPE_WSI=1 GAMESCOPE_WAYLAND_DISPLAY=${GAMESCOPE_WAYLAND_DISPLAY:-gamescope-0}
|
||||
export XDG_RUNTIME_DIR=$RTD DROIDDECK_WSI_BYPASS_CHECK_MS=100 GAMESCOPE_WSI_FORCE_BYPASS=1
|
||||
[ -e "$RTD/droiddeck-gamescope-limiter" ] && export GAMESCOPE_LIMITER_FILE=$RTD/droiddeck-gamescope-limiter
|
||||
|
||||
# Wine: DXVK/VKD3D over the builtins, X11 inside gamescope (winewayland would pick DroidDeck's compositor),
|
||||
# FEX for x86 code, userspace ntsync (no /dev/ntsync on Android), Valve's Android Steam client library.
|
||||
export WINEDLLOVERRIDES="${WINEDLLOVERRIDES:+$WINEDLLOVERRIDES;}d3d8,d3d9,d3d10core,d3d11,dxgi,d3d12,d3d12core=n,b;winewayland.drv=d"
|
||||
# Sync as chosen in DroidDeck (Wine sync, per-game PROTON_NO_*): ntsync is userspace ntsync (no /dev/ntsync on
|
||||
# Android) with esync as its fallback; Android has no futex_waitv, so an fsync choice runs ntsync.
|
||||
on() { case "$1" in 1|on|true|yes) return 0 ;; esac; return 1; }
|
||||
NT=1; ES=1
|
||||
[ "${DD_SYNC:-1}" = 0 ] && NT=0
|
||||
[ "${DD_FSYNC_FIRST:-0}" = 1 ] && NT=1
|
||||
[ "${DD_SYNC:-1}" = 0 ] && [ "${DD_SYNC_FALLBACK:-1}" = 0 ] && ES=0
|
||||
on "${PROTON_NO_NTSYNC:-}" && NT=0
|
||||
{ on "${PROTON_NO_ESYNC:-}" || [ "${WINEESYNC:-}" = 0 ]; } && ES=0
|
||||
export WINENTSYNC=$NT WINEESYNC=$ES
|
||||
# Userspace ntsync keeps its state in one file. Per prefix, not in the shared TMPDIR (DroidDeck-Proton's ntsync
|
||||
# uses that too), and cleared before Wine starts in this prefix: a process killed while it held the file's lock
|
||||
# leaves it held, and every later start in that prefix hangs at its first ntsync wait.
|
||||
export NTSYNC_SHM=$COMPAT/ntsync-shm
|
||||
# DroidDeck's Force SSBS (its glibc libssbs.so preload) is bionic Wine's own WINE_FORCE_SSBS
|
||||
on "${DROIDDECK_FORCE_SSBS:-}" && export WINE_FORCE_SSBS=1
|
||||
export HODLL=libwow64fex.dll WINEDEBUG=err+all,fixme-all
|
||||
export XENVIRONMENT=$TOOL/bionic/Xdefaults
|
||||
# The adapter's Wayland swapchain gets its buffers back from gamescope later than DroidDeck-Proton's Turnip does;
|
||||
# with gamescope's default three images the game waits for one about a fifth of the time at high frame rates.
|
||||
# droiddeck-game-env's fix for a game that needs its own image count sets vk_x11_strict_image_count instead.
|
||||
case "${vk_x11_strict_image_count:-}" in
|
||||
true|1) ;;
|
||||
*) export GAMESCOPE_WSI_MIN_IMAGE_COUNT=${GAMESCOPE_WSI_MIN_IMAGE_COUNT:-4} GAMESCOPE_WSI_ENSURE_MIN_IMAGE_COUNT=${GAMESCOPE_WSI_ENSURE_MIN_IMAGE_COUNT:-1} ;;
|
||||
esac
|
||||
# FEX: DroidDeck-Proton's defaults (its share/fex-emu/Config.json: x87 in 64-bit precision, TSO without the vector
|
||||
# and memcpy parts); droiddeck-game-env's per-game choices (FEX_* in the environment, e.g. .NET, Unity) win.
|
||||
export FEX_TSOENABLED=${FEX_TSOENABLED:-1} FEX_VECTORTSOENABLED=${FEX_VECTORTSOENABLED:-0} \
|
||||
FEX_MEMCPYSETTSOENABLED=${FEX_MEMCPYSETTSOENABLED:-0} FEX_HALFBARRIERTSOENABLED=${FEX_HALFBARRIERTSOENABLED:-1} \
|
||||
FEX_X87REDUCEDPRECISION=${FEX_X87REDUCEDPRECISION:-1} FEX_MULTIBLOCK=${FEX_MULTIBLOCK:-1} FEX_MAXINST=${FEX_MAXINST:-500} FEX_DISKCACHE=${FEX_DISKCACHE:-1}
|
||||
echo "fex $(env | grep '^FEX_' | sort | tr '\n' ' ')"
|
||||
echo "sync ntsync=$WINENTSYNC esync=$WINEESYNC ssbs=${WINE_FORCE_SSBS:-0} tu_debug=${TU_DEBUG:-} kept=$(echo $KEEP)"
|
||||
export WINESTEAMCLIENTPATH64=$ROOTFS/root/.local/share/Steam/androidarm64/libsteamclient.so
|
||||
# The layer sends a game's steamclient(64).dll to lsteamclient (and so to DroidDeck's Steam through the library
|
||||
# above) only with WINE_LSTEAMCLIENT set; without it Valve's Windows steamclient runs alone and SteamAPI_Init fails.
|
||||
export WINE_LSTEAMCLIENT=${WINE_LSTEAMCLIENT:-1}
|
||||
# Steam Input data (Valve's Steam Deck layouts with game actions) lives in DroidDeck's /dev/shm; libsteamshm.so
|
||||
# points the Android library's shared memory there (it keeps its own in-process otherwise) and gives it the
|
||||
# sem_open Android lacks (without it the game hangs once that data arrives).
|
||||
export DROIDDECK_BIONIC_SHM_DIR=${APP%/files}/no_backup/guest-runtime/shm
|
||||
export DXVK_LOG_PATH=$COMPAT PULSE_SERVER=unix:$APP/pulseaudio/PS0
|
||||
export ANDROID_SYSVSHM_SERVER=$COMPAT/.no-sysvshm-server # its client faults on an unset name, inside a Wine lock
|
||||
|
||||
# The pack's imagefs libraries carry Winlator's prefix for plugins and X11 data. No FONTCONFIG_*: with the
|
||||
# imagefs fonts.conf (Android's /system/fonts) DiRT Showdown quit right after start.
|
||||
export GST_PLUGIN_SYSTEM_PATH=$PACK/lib/gstreamer-1.0 GST_REGISTRY=$COMPAT/gst-registry.bin GST_REGISTRY_FORK=no
|
||||
export XLOCALEDIR=$PACK/share/X11/locale XKB_CONFIG_ROOT=$PACK/share/X11/xkb
|
||||
export SSL_CERT_FILE=$PACK/etc/tls/cert.pem SSL_CERT_DIR=$PACK/etc/tls/certs OPENSSL_CONF=$PACK/etc/tls/openssl.cnf
|
||||
export WINE_ADDITIONAL_CERTS_DIR=$PACK/etc/tls/cert.pem
|
||||
|
||||
# Controller: the bionic winebus has no udev bus, so Steam's virtual pad is shown to it as an Xbox 360 pad;
|
||||
# Steam's ignore list names that id because of the built-in pad, which Wine does not see here.
|
||||
export FAKE_EVDEV_STEAM_PAD_AS_X360=1
|
||||
export SDL_GAMECONTROLLER_IGNORE_DEVICES="$(echo "${SDL_GAMECONTROLLER_IGNORE_DEVICES:-}" | sed -e 's#0x045e/0x028e,##' -e 's#,0x045e/0x028e$##')"
|
||||
|
||||
# OpenGL, and WineD3D on it (DirectDraw, Direct3D 1-8 without DXVK): Mesa's Zink on Vulkan through winex11's EGL
|
||||
# backend (the runtime's egl/), the way Bannerlator's Fast OpenGL runs it; DroidDeck's GL settings above are kept.
|
||||
export WINE_USE_EGL=1 WINE_X11FORCEGLX=1 GALLIUM_DRIVER=zink MESA_LOADER_DRIVER_OVERRIDE=zink LIBGL_KOPPER_DRI2=1
|
||||
export ZINK_DESCRIPTORS=${ZINK_DESCRIPTORS:-lazy} ZINK_DEBUG=${ZINK_DEBUG:-compact} vblank_mode=${vblank_mode:-0}
|
||||
# Gallium's threaded context off, as in Bannerlator's Fast OpenGL: with it, WineD3D (DirectDraw / Direct3D 1-7)
|
||||
# crashed in native code within seconds (AIO Direct3D 7, SIGSEGV).
|
||||
export GALLIUM_THREAD=${GALLIUM_THREAD:-0}
|
||||
# Mesa's GL thread off unless the game's own DroidDeck environment sets it: with DroidDeck's session-wide
|
||||
# mesa_glthread=true, WineD3D's persistent buffer writes lost vertex colours on this Mesa build (AIO 64-bit
|
||||
# Direct3D 7 drew its cube white; DroidDeck-Proton's Mesa does not do this).
|
||||
case "$KEEP" in *" mesa_glthread "*) ;; *) export mesa_glthread=false ;; esac
|
||||
|
||||
# egl/ first: the layer's own lib/ carries a Wayland-only Mesa EGL of the same names, which winex11 cannot use
|
||||
LIBS=$PACK/egl:$F/lib:$PACK/lib:/system/lib64
|
||||
PRELOAD=$PACK/preload/libexecshim.so:$PACK/preload/libnotag.so:$PACK/preload/libfakeinput.so:$PACK/preload/libsteamshm.so
|
||||
wine_() { LD_LIBRARY_PATH=$LIBS LD_PRELOAD=$PRELOAD "$LINKER" "$F/lib/wine/aarch64-unix/wine" "$@"; }
|
||||
wineserver_() { LD_LIBRARY_PATH=$LIBS LD_PRELOAD=$PRELOAD "$LINKER" "$F/bin/wineserver" "$@"; }
|
||||
|
||||
is_builtin() { head -c 128 "$1" 2>/dev/null | grep -q "Wine builtin DLL"; }
|
||||
# Names wine.inf has Wine's update delete from system32 (section FakeDlls) or syswow64 (FakeDllsWow64), "11,,name,-":
|
||||
# in Windows they live only under Microsoft.NET or winsxs. Wine deletes through a link, so a link there cost this
|
||||
# tool its own fusion.dll, ngen.exe, comctl32_v6.dll and the rest, and later prefixes their .NET stubs and comctl32 v6.
|
||||
inf_drops() {
|
||||
awk -v s="[$1]" '/^\[/ { h = $0; sub(/[ \t\r]+$/, "", h); on = (h == s); next }
|
||||
on && /^11,,[^,]+,-[ \t\r]*$/ { split($0, a, ","); print a[3] }' "$F/share/wine/wine.inf" 2>/dev/null
|
||||
}
|
||||
dropped() { # name patterns
|
||||
set -f
|
||||
for p in $2; do case "$1" in $p) set +f; return 0 ;; esac; done
|
||||
set +f; return 1
|
||||
}
|
||||
link_dir() { # src dst [names]: links every file of src into dst; replaces links and Wine builtin copies, keeps native
|
||||
# DLLs; names (wine.inf patterns) are not linked and a link left under one is removed
|
||||
[ -d "$1" ] || return 0
|
||||
for f in "$1"/*; do
|
||||
[ -f "$f" ] || continue
|
||||
t=$2/${f##*/}
|
||||
if [ -n "${3:-}" ] && dropped "${f##*/}" "$3"; then
|
||||
[ -L "$t" ] && rm -f "$t"
|
||||
continue
|
||||
fi
|
||||
if [ -L "$t" ]; then
|
||||
[ "$(readlink "$t")" = "$f" ] && continue
|
||||
rm -f "$t"
|
||||
elif [ -e "$t" ]; then
|
||||
is_builtin "$t" || continue
|
||||
rm -f "$t"
|
||||
fi
|
||||
ln -s "$f" "$t"
|
||||
done
|
||||
}
|
||||
winpath() { echo "Z:$1" | sed 's#/#\\#g'; }
|
||||
|
||||
# The prefix carries this tool's builtins when it was last set up by this version; another Proton (or an
|
||||
# older DroidDeck-Bionic) leaves its own links there, and the compatdata version file tells DroidDeck-Proton
|
||||
# to relink when it runs this prefix again.
|
||||
# Drive Z: is the whole device for this tool: winpath, getcompatpath and the Xbox paths name Android paths on Z:.
|
||||
# Proton copies a prefix's links as relative ones, and DroidDeck-Proton's relative z: reaches only the Linux userland
|
||||
# here, so a game outside it (SD card, shared storage) was on no drive and Wine crashed on its path at start.
|
||||
# DroidDeck-Proton follows z: -> / in the guest's view, with proot and without.
|
||||
drive_z() {
|
||||
z=$1/dosdevices/z:
|
||||
[ -d "$1/dosdevices" ] || return 0
|
||||
[ -L "$z" ] || { [ -e "$z" ] && return 0; }
|
||||
old=$(readlink "$z" 2>/dev/null)
|
||||
[ "$old" = / ] && return 0
|
||||
rm -f "$z" && ln -s / "$z" && echo "$(date +%H:%M:%S) drive z: -> / (was ${old:-missing})"
|
||||
}
|
||||
|
||||
prepare_prefix() {
|
||||
P=$COMPAT/pfx
|
||||
drive_z "$P"
|
||||
if [ -f "$P/.droiddeck-bionic" ] && [ "$(cat "$P/.droiddeck-bionic")" = "$VERSION" ] && \
|
||||
[ "$(cat "$COMPAT/version" 2>/dev/null)" = "$VERSION" ]; then return 0; fi
|
||||
if [ ! -f "$P/system.reg" ]; then
|
||||
echo "$(date +%H:%M:%S) new prefix from the layer's template"
|
||||
mkdir -p "$P" && cp -a "$F/default_pfx/." "$P/"
|
||||
fi
|
||||
W=$P/drive_c/windows
|
||||
mkdir -p "$W/system32" "$W/syswow64" "$P/dosdevices"
|
||||
echo "$(date +%H:%M:%S) linking builtins"
|
||||
link_dir "$F/lib/wine/aarch64-windows" "$W/system32" "$(inf_drops FakeDlls)"
|
||||
link_dir "$F/lib/wine/i386-windows" "$W/syswow64" "$(inf_drops FakeDllsWow64)"
|
||||
for c in dxvk vkd3d-proton; do
|
||||
link_dir "$F/lib/wine/$c/aarch64-windows" "$W/system32"
|
||||
link_dir "$F/lib/wine/$c/i386-windows" "$W/syswow64"
|
||||
done
|
||||
# This layer's Wine always uses the profile C:\users\xuser, Proton's is C:\users\steamuser: one links to the
|
||||
# other so saves and settings are the same whichever tool runs the game.
|
||||
U=$P/drive_c/users
|
||||
if [ -d "$U/steamuser" ] && [ ! -e "$U/xuser" ]; then ln -s steamuser "$U/xuser"
|
||||
elif [ -d "$U/xuser" ] && [ ! -L "$U/xuser" ] && [ ! -e "$U/steamuser" ]; then ln -s xuser "$U/steamuser"; fi
|
||||
[ -e "$P/dosdevices/c:" ] || ln -s ../drive_c "$P/dosdevices/c:"
|
||||
[ -e "$P/dosdevices/z:" ] || ln -s / "$P/dosdevices/z:"
|
||||
wine_ regedit /S "$(winpath "$TOOL/bionic/desktop.reg")"
|
||||
wineserver_ -w
|
||||
echo "$VERSION" > "$P/.droiddeck-bionic"
|
||||
echo "$VERSION" > "$COMPAT/version"
|
||||
# Proton (DroidDeck-Proton, GE, ...) reads tracked_files when it takes this prefix over; one this tool made has
|
||||
# none. The version above is not a Proton prefix version, so Proton updates the prefix and never treats it as
|
||||
# one from a newer Proton (which would delete its tracked files).
|
||||
[ -e "$COMPAT/tracked_files" ] || : > "$COMPAT/tracked_files"
|
||||
echo "$(date +%H:%M:%S) prefix ready"
|
||||
}
|
||||
|
||||
prefix_busy() { # a process of this prefix is running
|
||||
for p in /proc/[0-9]*; do
|
||||
[ "${p#/proc/}" = "$$" ] && continue
|
||||
tr '\0' '\n' < "$p/environ" 2>/dev/null | grep -qx "WINEPREFIX=$COMPAT/pfx" && return 0
|
||||
done
|
||||
return 1
|
||||
}
|
||||
|
||||
programs_left() { # a program of this prefix is still running, apart from Wine's own services and this script's helpers
|
||||
for p in /proc/[0-9]*; do
|
||||
q=${p#/proc/}
|
||||
[ -O "$p" ] || continue
|
||||
[ "$q" = "$$" ] || [ "$q" = "${GT:-x}" ] && continue
|
||||
c=; read -r c < "$p/comm" 2>/dev/null
|
||||
case "$c" in
|
||||
""|wineserver|services.exe|winedevice.exe|plugplay.exe|explorer.exe|svchost.exe|rpcss.exe|conhost.exe|start.exe) continue ;;
|
||||
esac
|
||||
tr '\0' '\n' < "$p/environ" 2>/dev/null | grep -qx "WINEPREFIX=$COMPAT/pfx" && return 0
|
||||
done
|
||||
return 1
|
||||
}
|
||||
|
||||
stop_wine() { # wineserver -k, then whatever of this prefix is left (e.g. a game's crash reporter)
|
||||
wineserver_ -k 2>/dev/null
|
||||
sleep 1
|
||||
for p in /proc/[0-9]*; do
|
||||
tr '\0' '\n' < "$p/environ" 2>/dev/null | grep -qx "WINEPREFIX=$COMPAT/pfx" || continue
|
||||
[ "${p#/proc/}" = "$$" ] && continue
|
||||
echo "$(date +%H:%M:%S) left over: ${p#/proc/} $(cat "$p/comm" 2>/dev/null)"
|
||||
kill -9 "${p#/proc/}" 2>/dev/null
|
||||
done
|
||||
}
|
||||
|
||||
# A FEX from DroidDeck's components runs here only as an Android build (its unix libraries link Android's libc).
|
||||
# Missing or glibc unix libraries (an older app put its glibc FEX here): put the tool's own FEX back.
|
||||
fex_ok=1
|
||||
for f in aarch64-unix/libwow64fex.so aarch64-unix/libarm64ecfex.so; do
|
||||
if [ ! -f "$F/lib/wine/$f" ] || grep -q "ld-linux-aarch64" "$F/lib/wine/$f"; then fex_ok=0; fi
|
||||
done
|
||||
if [ $fex_ok = 0 ]; then
|
||||
for f in aarch64-unix/libwow64fex.so aarch64-unix/libarm64ecfex.so aarch64-windows/libwow64fex.dll aarch64-windows/libarm64ecfex.dll; do
|
||||
[ -f "$PACK/fex/$f" ] || continue
|
||||
cmp -s "$PACK/fex/$f" "$F/lib/wine/$f" || { cat "$PACK/fex/$f" > "$F/lib/wine/$f" && echo "$(date +%H:%M:%S) restored the tool's FEX $f"; }
|
||||
done
|
||||
fi
|
||||
echo "fex build: $(grep -a -o -m1 'FEX-[0-9][0-9.]*[0-9A-Za-z.+-]*' "$F/lib/wine/aarch64-windows/libarm64ecfex.dll" | head -1)"
|
||||
|
||||
if [ "$verb" != runinprefix ] && prefix_busy; then
|
||||
echo "$(date +%H:%M:%S) Wine left running in this prefix; stopping it"
|
||||
stop_wine
|
||||
fi
|
||||
prefix_busy || rm -f "$NTSYNC_SHM".v*
|
||||
|
||||
# Links into a tool that is gone (an older DroidDeck-Bionic, a deleted DroidDeck-Proton) or to a file it no longer has.
|
||||
# Wine's update cannot write over them, so drivers (network, controller) and other files stay missing. Drop them and
|
||||
# clear both stamps: prepare_prefix relinks this tool's files and Wine's update puts its own back.
|
||||
dead=0
|
||||
for d in system32 syswow64 system32/drivers Fonts; do
|
||||
for f in "$COMPAT/pfx/drive_c/windows/$d"/*; do
|
||||
[ -L "$f" ] && [ ! -e "$f" ] && rm -f "$f" && dead=$((dead + 1))
|
||||
done
|
||||
done
|
||||
if [ $dead -gt 0 ]; then
|
||||
rm -f "$COMPAT/pfx/.update-timestamp" "$COMPAT/pfx/.droiddeck-bionic"
|
||||
echo "$(date +%H:%M:%S) removed $dead dead link(s) from the prefix; relinking and Wine's update follow"
|
||||
fi
|
||||
|
||||
prepare_prefix
|
||||
|
||||
# FEX keeps translated code per program in the prefix (AppData/Local/fex-emu/DiskCache) and reuses it with whatever FEX
|
||||
# runs the prefix next. Code cached by another FEX build (DroidDeck-Proton's, or a different FEX picked in the
|
||||
# Components tab) made this FEX crash in Steam's install-script step, and Wine then looped on the crash, so Steam never
|
||||
# started the game. The cache is cleared when the FEX that runs the prefix is not the one that filled it.
|
||||
fexid=$(cat "$F/lib/wine/aarch64-windows/libarm64ecfex.dll" "$F/lib/wine/aarch64-windows/libwow64fex.dll" \
|
||||
"$F/lib/wine/aarch64-unix/libarm64ecfex.so" "$F/lib/wine/aarch64-unix/libwow64fex.so" 2>/dev/null | md5sum | cut -c1-16)
|
||||
if [ "$(cat "$COMPAT/pfx/.droiddeck-fex-cache" 2>/dev/null)" != "$fexid" ]; then
|
||||
for u in "$COMPAT/pfx/drive_c/users"/*; do
|
||||
c=$u/AppData/Local/fex-emu/DiskCache
|
||||
[ -L "$u" ] || [ ! -d "$c" ] && continue
|
||||
rm -rf "$c" && echo "$(date +%H:%M:%S) FEX code cache of ${u##*/} cleared (filled by another FEX build or unknown)"
|
||||
done
|
||||
echo "$fexid" > "$COMPAT/pfx/.droiddeck-fex-cache"
|
||||
fi
|
||||
|
||||
# Steam's Windows client files in the prefix, the ones Proton copies from Steam's legacycompat folder: a game's
|
||||
# steam_api loads C:\Program Files (x86)\Steam\steamclient64.dll, and a prefix this tool made has none.
|
||||
SC=$ROOTFS/root/.local/share/Steam/legacycompat
|
||||
D="$COMPAT/pfx/drive_c/Program Files (x86)/Steam"
|
||||
if [ -d "$SC" ]; then
|
||||
mkdir -p "$D"
|
||||
for c in steamclient.dll:steamclient.dll steamclient64.dll:steamclient64.dll GameOverlayRenderer64.dll:GameOverlayRenderer64.dll \
|
||||
SteamService.exe:steam.exe Steam.dll:Steam.dll; do
|
||||
s=$SC/${c%%:*}; d=$D/${c#*:}
|
||||
[ -f "$s" ] || continue
|
||||
[ -f "$d" ] && [ ! "$s" -nt "$d" ] && continue
|
||||
cp "$s" "$d.new" && mv -f "$d.new" "$d" && touch -r "$s" "$d" && echo "$(date +%H:%M:%S) Steam client file ${c#*:}"
|
||||
done
|
||||
fi
|
||||
|
||||
# DXVK and VKD3D-Proton: the prefix uses this tool's files, where DroidDeck puts its component choices. Another Proton
|
||||
# that ran this prefix left its own copies, which link_dir keeps as native DLLs. A name the tool's DXVK does not ship
|
||||
# (d3d10.dll, d3d10_1.dll) goes back to Wine's own.
|
||||
for a in aarch64-windows:system32 i386-windows:syswow64; do
|
||||
arch=${a%%:*}; W=$COMPAT/pfx/drive_c/windows/${a#*:}
|
||||
[ -d "$W" ] || continue
|
||||
for n in d3d8 d3d9 d3d10 d3d10_1 d3d10core d3d11 dxgi d3d12 d3d12core; do
|
||||
s=$F/lib/wine/dxvk/$arch/$n.dll
|
||||
[ -f "$s" ] || s=$F/lib/wine/vkd3d-proton/$arch/$n.dll
|
||||
[ -f "$s" ] || s=$F/lib/wine/$arch/$n.dll
|
||||
[ -f "$s" ] || continue
|
||||
t=$W/$n.dll
|
||||
[ -L "$t" ] && [ "$(readlink "$t")" = "$s" ] && continue
|
||||
rm -f "$t" && ln -s "$s" "$t" && echo "$(date +%H:%M:%S) ${a#*:}/$n.dll -> ${s#$F/lib/wine/}"
|
||||
done
|
||||
done
|
||||
|
||||
# D7VK (Direct3D 7 and older on Vulkan) for 32-bit games when PROTON_USE_D7VK is set and not 0, as DroidDeck-Proton:
|
||||
# its ddraw.dll in syswow64 with Wine's own beside it as ddraw_.dll. Switched off, Wine's link goes back. Only the
|
||||
# links in the prefix are removed, never the files they point to.
|
||||
S=$COMPAT/pfx/drive_c/windows/syswow64
|
||||
if [ -n "${PROTON_USE_D7VK:-}" ] && [ "$PROTON_USE_D7VK" != 0 ] && [ -f "$PACK/d7vk/ddraw.dll" ]; then
|
||||
rm -f "$S/ddraw.dll" "$S/ddraw_.dll"
|
||||
ln -s "$PACK/d7vk/ddraw.dll" "$S/ddraw.dll" && ln -s "$F/lib/wine/i386-windows/ddraw.dll" "$S/ddraw_.dll"
|
||||
export WINEDLLOVERRIDES="$WINEDLLOVERRIDES;ddraw=n,b"
|
||||
echo "$(date +%H:%M:%S) D7VK on (32-bit ddraw)"
|
||||
elif [ -L "$S/ddraw_.dll" ] || [ -e "$S/ddraw_.dll" ]; then
|
||||
rm -f "$S/ddraw.dll" "$S/ddraw_.dll"
|
||||
ln -s "$F/lib/wine/i386-windows/ddraw.dll" "$S/ddraw.dll"
|
||||
echo "$(date +%H:%M:%S) D7VK off: Wine's ddraw again"
|
||||
fi
|
||||
# A Windows path (an Xbox game on its own drive letter) starts in the folder Steam gave.
|
||||
case "$EXE" in [A-Za-z]:[\\/]*) ;; *) cd "$(dirname "$EXE")" || exit 1 ;; esac
|
||||
|
||||
if [ "$verb" = runinprefix ]; then
|
||||
wine_ "$EXE" "$@"
|
||||
exit $?
|
||||
fi
|
||||
|
||||
name=${EXE##*/}; name=${name##*\\}
|
||||
comm=$(echo "$name" | cut -c1-15)
|
||||
game_pids() { grep -lx "$comm" /proc/[0-9]*/comm 2>/dev/null | cut -d/ -f3; }
|
||||
# The game's windows go straight to gamescope's X server, as with DroidDeck-Proton (no Wine desktop): the game
|
||||
# sees gamescope's real modes and refresh rate, and gamescope manages its windows.
|
||||
wine_ "$EXE" "$@" &
|
||||
WP=$!
|
||||
# Steam's overlay library marks a game's windows with the app ID Steam tracks (STEAM_GAME); that library is
|
||||
# glibc-only, so this prefix's windows (WM_CLASS = the Windows program name) are tagged from outside, or gamescope
|
||||
# never shows them.
|
||||
GT=
|
||||
if [ "${SteamAppId:-0}" != 0 ]; then
|
||||
XD=${DISPLAY#*:}; XD=${XD%%.*}
|
||||
"$LINKER" "$PACK/bin/gstag" "${XD:-0}" "$SteamAppId" .exe 86400 > "$COMPAT/gstag.log" 2>&1 &
|
||||
GT=$!
|
||||
fi
|
||||
trap 'echo "$(date +%H:%M:%S) stopped by Steam"; [ -n "$GT" ] && kill $GT 2>/dev/null; stop_wine; exit 0' TERM INT HUP
|
||||
n=0
|
||||
while [ $n -lt 90 ] && [ -z "$(game_pids)" ]; do
|
||||
# A program that ended before it was seen (Steam's install-script step takes about a second) leaves nothing
|
||||
# to wait for; a launcher that left a game running is still waited for as before.
|
||||
if [ $n -ge 2 ] && ! kill -0 $WP 2>/dev/null && ! programs_left; then break; fi
|
||||
sleep 1; n=$((n + 1))
|
||||
done
|
||||
echo "$(date +%H:%M:%S) game process $(game_pids | tr '\n' ' ')after ${n}s"
|
||||
# The program Steam started counts while it runs: a program that names its main thread (Chromium-based games call
|
||||
# it CrBrowserMain) changes its process name, which Wine copies, and is then no longer found by name.
|
||||
while [ -n "$(game_pids)" ] || kill -0 $WP 2>/dev/null; do sleep 2; done
|
||||
echo "$(date +%H:%M:%S) game exited"
|
||||
[ -n "$GT" ] && kill $GT 2>/dev/null
|
||||
stop_wine
|
||||
wait $WP
|
||||
echo "$(date +%H:%M:%S) done"
|
||||
@@ -0,0 +1,86 @@
|
||||
#!/bin/bash
|
||||
# DroidDeck-Bionic: a Steam compatibility tool that runs Windows games on the bionic (Android libc) Proton layer
|
||||
# under files/, outside the Linux userland. Steam calls it inside DroidDeck's no-proot guest; it turns guest paths
|
||||
# into Android paths and hands over to bionic/launch.sh, an Android /system/bin/sh script.
|
||||
# Verbs: run/waitforexitandrun (start the game), runinprefix (run a program in the prefix), getcompatpath/
|
||||
# getnativepath (path conversion); the rest are accepted and ignored.
|
||||
set -u
|
||||
verb=${1:-}
|
||||
[ $# -gt 0 ] && shift
|
||||
|
||||
if [ -z "${DDNATV_ROOT:-}" ]; then
|
||||
echo "DroidDeck-Bionic needs Settings > Run without proot" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# guest path -> Android path: the longest no-proot bind whose guest side starts the path, else inside the rootfs
|
||||
real() {
|
||||
local p="$1" best="" host="" b g h
|
||||
local -a binds
|
||||
IFS='|' read -r -a binds <<< "${DDNATV_BINDS:-}"
|
||||
for b in "${binds[@]}"; do
|
||||
h="${b%%:*}"; g="${b#*:}"
|
||||
case "$p" in "$g"|"$g"/*) [ ${#g} -gt ${#best} ] && { best="$g"; host="$h"; } ;; esac
|
||||
done
|
||||
if [ -n "$best" ]; then echo "$host${p#"$best"}"; return; fi
|
||||
case "$p" in /data/*|/storage/*|/sdcard/*|/system/*|/apex/*|/vendor/*) echo "$p" ;; *) echo "$DDNATV_ROOT$p" ;; esac
|
||||
}
|
||||
|
||||
here=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
|
||||
tool=$(real "$here")
|
||||
compat=$(real "${STEAM_COMPAT_DATA_PATH:-$HOME/.local/share/Steam/steamapps/compatdata/0}")
|
||||
|
||||
case "$verb" in
|
||||
run|waitforexitandrun|runinprefix)
|
||||
[ $# -gt 0 ] || exit 0
|
||||
# A Windows path (DroidDeck's Xbox launch names the game on a drive letter of its own) or a bare program name
|
||||
# (DroidDeck's store steps run cmd.exe, which Wine finds in system32) goes to Wine unchanged.
|
||||
case "$1" in
|
||||
[A-Za-z]:[\\/]*) exe=$1 ;;
|
||||
/*) exe=$(real "$1") ;;
|
||||
*/*) exe=$(real "$PWD/$1") ;;
|
||||
*) exe=$1 ;;
|
||||
esac
|
||||
shift
|
||||
export DROIDDECK_BIONIC_ROOT="$DDNATV_ROOT"
|
||||
# The Xbox runtime's DLC and mount folders come as Z: paths of the guest; this Wine sees the Android side.
|
||||
zreal() {
|
||||
local out="" part p
|
||||
local -a parts
|
||||
IFS=';' read -r -a parts <<< "$1"
|
||||
for part in "${parts[@]}"; do
|
||||
case "$part" in [Zz]:\\*) p=${part:2}; p=$(real "${p//\\//}"); part="Z:${p//\//\\}" ;; esac
|
||||
out="${out:+$out;}$part"
|
||||
done
|
||||
echo "$out"
|
||||
}
|
||||
for v in XODUS_MOUNT_ROOT XODUS_CONTENT_ROOTS; do
|
||||
[ -n "${!v:-}" ] && { printf -v "$v" '%s' "$(zreal "${!v}")"; export "${v?}"; }
|
||||
done
|
||||
# The HUD's GPU-load folder is a guest path; the bionic game writes to it by its Android path.
|
||||
[ -n "${DROIDDECK_GPU_LOAD_DIR:-}" ] && { DROIDDECK_GPU_LOAD_DIR=$(real "$DROIDDECK_GPU_LOAD_DIR"); export DROIDDECK_GPU_LOAD_DIR; }
|
||||
# DroidDeck's game environment (shared entries and this game's), already applied by droiddeck-game-env: the
|
||||
# names launch.sh keeps when it drops the rest of the guest environment.
|
||||
DROIDDECK_BIONIC_KEEP=$(python3 - "${STEAM_COMPAT_DATA_PATH:-}" 2>/dev/null <<'PY'
|
||||
import json, os, re, sys
|
||||
try:
|
||||
config = json.load(open(os.path.expanduser("~/.config/droiddeck/game-environment.json"), encoding="utf-8"))
|
||||
except (OSError, ValueError):
|
||||
sys.exit(0)
|
||||
scope = os.path.basename(sys.argv[1].rstrip("/"))
|
||||
names = set((config.get("shared") or {}).keys())
|
||||
if re.fullmatch(r"[1-9][0-9]{0,9}", scope):
|
||||
names |= set(((config.get("games") or {}).get(scope) or {}).keys())
|
||||
print(" ".join(sorted(n for n in names if re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", n) and n in os.environ)))
|
||||
PY
|
||||
)
|
||||
export DROIDDECK_BIONIC_KEEP
|
||||
exec /system/bin/sh "$tool/bionic/launch.sh" "$verb" "$compat" "$exe" "$@" ;;
|
||||
getcompatpath)
|
||||
p=$(real "${1:-}")
|
||||
printf 'Z:%s\n' "${p//\//\\}" ;;
|
||||
getnativepath)
|
||||
p=${1:-}; p=${p#[Zz]:}; p=${p//\\//}
|
||||
echo "$p" ;;
|
||||
*) exit 0 ;;
|
||||
esac
|
||||
@@ -0,0 +1,5 @@
|
||||
"manifest"
|
||||
{
|
||||
"version" "2"
|
||||
"commandline" "/proton %verb%"
|
||||
}
|
||||
@@ -358,3 +358,13 @@ and clears the held flag. wlroots counts repeated presses of one button and send
|
||||
reaches zero, so a second finger touching before the first lifted left the button pressed in the seat for good: the
|
||||
game saw a held click, and later taps only raised and lowered the count. A finger now presses the button only when no
|
||||
earlier finger holds it. `tools/tests/test_gamescope_touch_click.py` compiles the rule from this patch.
|
||||
|
||||
## 0936 Android buffers pass through to the host (banner_ahb_v1)
|
||||
|
||||
A bionic game can allocate its swapchain images as Android buffers (AHardwareBuffer) and still share them as dma-bufs;
|
||||
`banner_ahb_v1` hands the Android buffer itself to the compositor once per wl_buffer, so the compositor can put it on a
|
||||
display layer without a copy. gamescope now advertises `banner_ahb_v1` version 2: it binds the host compositor's
|
||||
global, relays the host's mode (whether clients should allocate such buffers) to its clients, and keeps each attached
|
||||
socket with the client's dma-buf. When it creates the host wl_buffer for that dma-buf (`ImportDmabufToBackend`), it
|
||||
sends the socket on with it, unread. Clients that do not bind the global, and hosts that do not advertise it, see no
|
||||
change. `GAMESCOPE_BANNER_AHB=0` leaves the global out.
|
||||
@@ -0,0 +1,409 @@
|
||||
diff --git a/protocol/banner-ahb-v1.xml b/protocol/banner-ahb-v1.xml
|
||||
new file mode 100644
|
||||
index 0000000..1560c8f
|
||||
--- /dev/null
|
||||
+++ b/protocol/banner-ahb-v1.xml
|
||||
@@ -0,0 +1,105 @@
|
||||
+<?xml version="1.0" encoding="UTF-8"?>
|
||||
+<protocol name="banner_ahb_v1">
|
||||
+ <copyright>
|
||||
+ Copyright 2026 The412Banner
|
||||
+
|
||||
+ Permission is hereby granted, free of charge, to any person obtaining a
|
||||
+ copy of this software and associated documentation files (the "Software"),
|
||||
+ to deal in the Software without restriction, including without limitation
|
||||
+ the rights to use, copy, modify, merge, publish, distribute, sublicense,
|
||||
+ and/or sell copies of the Software, and to permit persons to whom the
|
||||
+ Software is furnished to do so, subject to the following conditions:
|
||||
+
|
||||
+ The above copyright notice and this permission notice (including the next
|
||||
+ paragraph) shall be included in all copies or substantial portions of the
|
||||
+ Software.
|
||||
+
|
||||
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
|
||||
+ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
+ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||
+ DEALINGS IN THE SOFTWARE.
|
||||
+ </copyright>
|
||||
+
|
||||
+ <interface name="banner_ahb_v1" version="2">
|
||||
+ <description summary="Android gralloc buffers behind dma-buf wl_buffers">
|
||||
+ Zero-copy window layers on Android. A Vulkan swapchain image that the
|
||||
+ client allocated as an Android AHardwareBuffer (gralloc) is still shared
|
||||
+ as a dma-buf through zwp_linux_dmabuf_v1, so the compositor can import
|
||||
+ and draw it the usual way. This interface additionally hands the
|
||||
+ compositor the AHardwareBuffer itself, once per wl_buffer, so the
|
||||
+ compositor can put the buffer straight on an Android SurfaceControl
|
||||
+ layer (SurfaceFlinger / the display hardware composite it) without
|
||||
+ copying it.
|
||||
+
|
||||
+ The AHardwareBuffer travels over a Unix socket: the client creates a
|
||||
+ socketpair, writes the buffer's handle into one end with
|
||||
+ AHardwareBuffer_sendHandleToUnixSocket, then sends the other end in the
|
||||
+ attach request. The compositor reads it with
|
||||
+ AHardwareBuffer_recvHandleFromUnixSocket and closes the socket. Its
|
||||
+ reference to the AHardwareBuffer lives as long as the wl_buffer (plus
|
||||
+ whatever the display still holds).
|
||||
+
|
||||
+ The compositor advertises this global whenever it can put buffers on a
|
||||
+ display layer at all; whether it WANTS gralloc buffers right now is the
|
||||
+ mode event (version 2), sent on bind and every time the user switches
|
||||
+ zero-copy on or off during the session. A client decides per swapchain,
|
||||
+ when it creates the swapchain, from the last mode it received, and a
|
||||
+ client whose live swapchain was built for the other mode retires it
|
||||
+ (VK_ERROR_OUT_OF_DATE_KHR on its next acquire or present) so the program
|
||||
+ rebuilds it for the new mode. Buffers of the old swapchain stay fully
|
||||
+ presentable until then: an attached AHardwareBuffer keeps its association
|
||||
+ for the wl_buffer's lifetime whatever the mode is now. A version 1
|
||||
+ client (no mode event) keeps deciding from its own environment. A
|
||||
+ client that does not see the global (or does not want it) allocates
|
||||
+ swapchain images the standard way; nothing else changes.
|
||||
+
|
||||
+ Synchronisation stays implicit: the dma-buf carries the client's render
|
||||
+ fence (DMA_BUF_IOCTL_IMPORT_SYNC_FILE by the client's driver), the
|
||||
+ compositor exports it as the layer's acquire fence, and the compositor
|
||||
+ imports the display's release fence into the dma-buf before it sends
|
||||
+ wl_buffer.release, so the client's next acquire waits on it.
|
||||
+ </description>
|
||||
+
|
||||
+ <request name="destroy" type="destructor">
|
||||
+ <description summary="destroy the object">
|
||||
+ Buffers already attached keep their AHardwareBuffer association.
|
||||
+ </description>
|
||||
+ </request>
|
||||
+
|
||||
+ <request name="attach">
|
||||
+ <description summary="hand the compositor a buffer's AHardwareBuffer">
|
||||
+ Associates the AHardwareBuffer readable from socket with the
|
||||
+ (already created) dma-buf wl_buffer. width, height and stride
|
||||
+ (pixels) describe the gralloc allocation; modifier_hi/lo is the DRM
|
||||
+ format modifier the dma-buf was shared with (the same value passed to
|
||||
+ zwp_linux_buffer_params_v1.add); image_count is the number of images
|
||||
+ in the swapchain this buffer belongs to (for the compositor's log).
|
||||
+ Sent once per wl_buffer, before the buffer is first attached to a
|
||||
+ surface.
|
||||
+ </description>
|
||||
+ <arg name="buffer" type="object" interface="wl_buffer" summary="the dma-buf wl_buffer"/>
|
||||
+ <arg name="socket" type="fd" summary="socket the AHardwareBuffer handle was written to"/>
|
||||
+ <arg name="width" type="uint" summary="buffer width in pixels"/>
|
||||
+ <arg name="height" type="uint" summary="buffer height in pixels"/>
|
||||
+ <arg name="stride" type="uint" summary="gralloc row stride in pixels"/>
|
||||
+ <arg name="modifier_hi" type="uint" summary="high 32 bits of the DRM format modifier"/>
|
||||
+ <arg name="modifier_lo" type="uint" summary="low 32 bits of the DRM format modifier"/>
|
||||
+ <arg name="image_count" type="uint" summary="images in the client's swapchain"/>
|
||||
+ </request>
|
||||
+
|
||||
+ <event name="mode" since="2">
|
||||
+ <description summary="whether the compositor wants gralloc swapchain images now">
|
||||
+ Sent once right after bind and again whenever the compositor's
|
||||
+ zero-copy state flips (the in-game switch). enabled = 1: swapchains
|
||||
+ created from now on should use gralloc AHardwareBuffers and attach
|
||||
+ them; 0: standard buffers. A live swapchain built for the other value
|
||||
+ should be retired by the client (out of date) so the program rebuilds
|
||||
+ it; until it is, its buffers are shown as before.
|
||||
+ </description>
|
||||
+ <arg name="enabled" type="uint" summary="1 = gralloc swapchain images wanted, 0 = not"/>
|
||||
+ </event>
|
||||
+ </interface>
|
||||
+</protocol>
|
||||
diff --git a/protocol/meson.build b/protocol/meson.build
|
||||
index cf8fbd1..a6ad1f8 100644
|
||||
--- a/protocol/meson.build
|
||||
+++ b/protocol/meson.build
|
||||
@@ -45,6 +45,9 @@ protocols = [
|
||||
|
||||
# wlroots protocols
|
||||
'wlr-layer-shell-unstable-v1.xml',
|
||||
+
|
||||
+ # Android buffers behind dma-buf wl_buffers (DroidDeck / Bannerlator zero-copy layers)
|
||||
+ 'banner-ahb-v1.xml',
|
||||
]
|
||||
|
||||
protocols_client_src = []
|
||||
diff --git a/src/Backends/WaylandBackend.cpp b/src/Backends/WaylandBackend.cpp
|
||||
index 372fc08..cfb5175 100644
|
||||
--- a/src/Backends/WaylandBackend.cpp
|
||||
+++ b/src/Backends/WaylandBackend.cpp
|
||||
@@ -38,6 +38,7 @@
|
||||
#include <primary-selection-unstable-v1-client-protocol.h>
|
||||
#include <fractional-scale-v1-client-protocol.h>
|
||||
#include <xdg-toplevel-icon-v1-client-protocol.h>
|
||||
+#include <banner-ahb-v1-client-protocol.h>
|
||||
#include "wlr_end.hpp"
|
||||
|
||||
#include "drm_include.h"
|
||||
@@ -818,6 +819,7 @@ namespace gamescope
|
||||
wp_single_pixel_buffer_manager_v1 *m_pSinglePixelBufferManager = nullptr;
|
||||
wl_subcompositor *m_pSubcompositor = nullptr;
|
||||
zwp_linux_dmabuf_v1 *m_pLinuxDmabuf = nullptr;
|
||||
+ banner_ahb_v1 *m_pBannerAhb = nullptr;
|
||||
xdg_wm_base *m_pXdgWmBase = nullptr;
|
||||
wp_viewporter *m_pViewporter = nullptr;
|
||||
wl_region *m_pEmptyRegion = nullptr;
|
||||
@@ -2340,6 +2342,15 @@ namespace gamescope
|
||||
|
||||
zwp_linux_buffer_params_v1_destroy( pBufferParams );
|
||||
|
||||
+ // A client's Android buffer behind this dma-buf goes to the host with the host's wl_buffer for it.
|
||||
+ wlserver_banner_ahb_attach ahb;
|
||||
+ if ( m_pBannerAhb && pDmaBuf->n_planes > 0 && wlserver_banner_ahb_take( pDmaBuf->fd[0], &ahb ) )
|
||||
+ {
|
||||
+ banner_ahb_v1_attach( m_pBannerAhb, pImportedBuffer, ahb.sock, ahb.width, ahb.height, ahb.stride,
|
||||
+ ahb.mod_hi, ahb.mod_lo, ahb.image_count );
|
||||
+ close( ahb.sock );
|
||||
+ }
|
||||
+
|
||||
return new CWaylandFb{ this, pImportedBuffer };
|
||||
}
|
||||
|
||||
@@ -2598,6 +2609,20 @@ namespace gamescope
|
||||
{
|
||||
m_pSinglePixelBufferManager = (wp_single_pixel_buffer_manager_v1 *)wl_registry_bind( pRegistry, uName, &wp_single_pixel_buffer_manager_v1_interface, 1u );
|
||||
}
|
||||
+ else if ( !strcmp( pInterface, banner_ahb_v1_interface.name ) )
|
||||
+ {
|
||||
+ // The host shows Android buffers on a display layer (banner_ahb_v1): its mode says whether clients
|
||||
+ // should allocate their swapchain images as such buffers; gamescope's own global relays it.
|
||||
+ static constexpr banner_ahb_v1_listener s_Listener =
|
||||
+ {
|
||||
+ .mode = []( void *pData, banner_ahb_v1 *pBannerAhb, uint32_t uEnabled )
|
||||
+ {
|
||||
+ wlserver_banner_ahb_set_mode( uEnabled != 0 );
|
||||
+ },
|
||||
+ };
|
||||
+ m_pBannerAhb = (banner_ahb_v1 *)wl_registry_bind( pRegistry, uName, &banner_ahb_v1_interface, std::min( uVersion, 2u ) );
|
||||
+ banner_ahb_v1_add_listener( m_pBannerAhb, &s_Listener, this );
|
||||
+ }
|
||||
else if ( !strcmp( pInterface, wl_subcompositor_interface.name ) )
|
||||
{
|
||||
m_pSubcompositor = (wl_subcompositor *)wl_registry_bind( pRegistry, uName, &wl_subcompositor_interface, 1u );
|
||||
diff --git a/src/wlserver.cpp b/src/wlserver.cpp
|
||||
index df352b0..a84f2af 100644
|
||||
--- a/src/wlserver.cpp
|
||||
+++ b/src/wlserver.cpp
|
||||
@@ -11,6 +11,11 @@
|
||||
#include <fcntl.h>
|
||||
#include <xf86drm.h>
|
||||
#include <sys/eventfd.h>
|
||||
+#include <sys/stat.h>
|
||||
+#include <atomic>
|
||||
+#include <mutex>
|
||||
+#include <unordered_map>
|
||||
+#include <vector>
|
||||
|
||||
#include <linux/input-event-codes.h>
|
||||
|
||||
@@ -48,6 +53,7 @@
|
||||
#include <wlr/types/wlr_pointer_constraints_v1.h>
|
||||
#include <wlr/types/wlr_layer_shell_v1.h>
|
||||
#include <wlr/types/wlr_data_device.h>
|
||||
+#include <wlr/types/wlr_linux_dmabuf_v1.h>
|
||||
#include <wlr/util/region.h>
|
||||
#include "wlr_end.hpp"
|
||||
|
||||
@@ -57,6 +63,7 @@
|
||||
#include "gamescope-private-protocol.h"
|
||||
#include "gamescope-swapchain-protocol.h"
|
||||
#include "presentation-time-protocol.h"
|
||||
+#include "banner-ahb-v1-protocol.h"
|
||||
|
||||
#include "wlserver.hpp"
|
||||
#include "hdmi.h"
|
||||
@@ -1157,6 +1164,165 @@ static void gamescope_swapchain_factory_v2_bind( struct wl_client *client, void
|
||||
wl_resource_set_implementation( resource, &gamescope_swapchain_factory_v2_impl, NULL, NULL );
|
||||
}
|
||||
|
||||
+// DroidDeck: banner_ahb_v1, Android buffers behind dma-buf wl_buffers. A bionic game can allocate its swapchain
|
||||
+// images as AHardwareBuffers and hand each one over once per wl_buffer (a socket the handle was written to).
|
||||
+// gamescope never reads it: when it creates the host wl_buffer for the same dma-buf it passes the socket on to the
|
||||
+// host compositor (CWaylandBackend::ImportDmabufToBackend), which can then show the buffer on a display layer
|
||||
+// without a copy. Whether clients should allocate such buffers is the host's mode, relayed here.
|
||||
+// GAMESCOPE_BANNER_AHB=0 leaves the global out.
|
||||
+struct banner_ahb_pending
|
||||
+{
|
||||
+ int sock = -1;
|
||||
+ uint32_t width = 0, height = 0, stride = 0, mod_hi = 0, mod_lo = 0, image_count = 0;
|
||||
+ ino_t ino = 0;
|
||||
+ bool queued = false;
|
||||
+ wl_listener destroy;
|
||||
+};
|
||||
+
|
||||
+static std::mutex g_BannerAhbMutex;
|
||||
+static std::unordered_map<ino_t, banner_ahb_pending *> g_BannerAhbPending;
|
||||
+static std::vector<wl_resource *> g_BannerAhbResources;
|
||||
+static std::atomic<int> g_nBannerAhbMode{ 0 };
|
||||
+
|
||||
+static void banner_ahb_buffer_destroyed( wl_listener *pListener, void * )
|
||||
+{
|
||||
+ banner_ahb_pending *pPending = wl_container_of( pListener, pPending, destroy );
|
||||
+ {
|
||||
+ std::scoped_lock lock( g_BannerAhbMutex );
|
||||
+ if ( pPending->queued )
|
||||
+ {
|
||||
+ auto iter = g_BannerAhbPending.find( pPending->ino );
|
||||
+ if ( iter != g_BannerAhbPending.end() && iter->second == pPending )
|
||||
+ g_BannerAhbPending.erase( iter );
|
||||
+ }
|
||||
+ if ( pPending->sock >= 0 )
|
||||
+ close( pPending->sock );
|
||||
+ }
|
||||
+ wl_list_remove( &pPending->destroy.link );
|
||||
+ delete pPending;
|
||||
+}
|
||||
+
|
||||
+static void banner_ahb_handle_destroy( wl_client *, wl_resource *pResource )
|
||||
+{
|
||||
+ wl_resource_destroy( pResource );
|
||||
+}
|
||||
+
|
||||
+static void banner_ahb_handle_attach( wl_client *, wl_resource *, wl_resource *pBuffer, int32_t nSocket,
|
||||
+ uint32_t uWidth, uint32_t uHeight, uint32_t uStride, uint32_t uModHi, uint32_t uModLo, uint32_t uImageCount )
|
||||
+{
|
||||
+ wlr_dmabuf_v1_buffer *pDmabuf = wlr_dmabuf_v1_buffer_try_from_buffer_resource( pBuffer );
|
||||
+ struct stat st;
|
||||
+ if ( !pDmabuf || pDmabuf->attributes.n_planes < 1 || fstat( pDmabuf->attributes.fd[0], &st ) != 0 )
|
||||
+ {
|
||||
+ wl_log.errorf( "banner_ahb_v1: attach to a wl_buffer that is not a dma-buf, ignored" );
|
||||
+ close( nSocket );
|
||||
+ return;
|
||||
+ }
|
||||
+
|
||||
+ banner_ahb_pending *pPending = new banner_ahb_pending;
|
||||
+ pPending->sock = nSocket;
|
||||
+ pPending->width = uWidth;
|
||||
+ pPending->height = uHeight;
|
||||
+ pPending->stride = uStride;
|
||||
+ pPending->mod_hi = uModHi;
|
||||
+ pPending->mod_lo = uModLo;
|
||||
+ pPending->image_count = uImageCount;
|
||||
+ pPending->ino = st.st_ino;
|
||||
+ pPending->queued = true;
|
||||
+ pPending->destroy.notify = banner_ahb_buffer_destroyed;
|
||||
+ wl_resource_add_destroy_listener( pBuffer, &pPending->destroy );
|
||||
+
|
||||
+ std::scoped_lock lock( g_BannerAhbMutex );
|
||||
+ auto iter = g_BannerAhbPending.find( st.st_ino );
|
||||
+ if ( iter != g_BannerAhbPending.end() )
|
||||
+ {
|
||||
+ iter->second->queued = false;
|
||||
+ if ( iter->second->sock >= 0 )
|
||||
+ {
|
||||
+ close( iter->second->sock );
|
||||
+ iter->second->sock = -1;
|
||||
+ }
|
||||
+ }
|
||||
+ g_BannerAhbPending[ st.st_ino ] = pPending;
|
||||
+}
|
||||
+
|
||||
+static const struct banner_ahb_v1_interface banner_ahb_impl =
|
||||
+{
|
||||
+ .destroy = banner_ahb_handle_destroy,
|
||||
+ .attach = banner_ahb_handle_attach,
|
||||
+};
|
||||
+
|
||||
+static void banner_ahb_resource_destroyed( wl_resource *pResource )
|
||||
+{
|
||||
+ std::erase( g_BannerAhbResources, pResource );
|
||||
+}
|
||||
+
|
||||
+static void banner_ahb_bind( wl_client *pClient, void *, uint32_t uVersion, uint32_t uId )
|
||||
+{
|
||||
+ wl_resource *pResource = wl_resource_create( pClient, &banner_ahb_v1_interface, std::min( uVersion, 2u ), uId );
|
||||
+ if ( !pResource )
|
||||
+ {
|
||||
+ wl_client_post_no_memory( pClient );
|
||||
+ return;
|
||||
+ }
|
||||
+ wl_resource_set_implementation( pResource, &banner_ahb_impl, nullptr, banner_ahb_resource_destroyed );
|
||||
+ g_BannerAhbResources.push_back( pResource );
|
||||
+ if ( wl_resource_get_version( pResource ) >= BANNER_AHB_V1_MODE_SINCE_VERSION )
|
||||
+ banner_ahb_v1_send_mode( pResource, g_nBannerAhbMode.load() ? 1u : 0u );
|
||||
+}
|
||||
+
|
||||
+static void create_banner_ahb( void )
|
||||
+{
|
||||
+ const char *pszEnv = getenv( "GAMESCOPE_BANNER_AHB" );
|
||||
+ if ( pszEnv && pszEnv[0] == '0' )
|
||||
+ return;
|
||||
+ wl_global_create( wlserver.display, &banner_ahb_v1_interface, 2, nullptr, banner_ahb_bind );
|
||||
+}
|
||||
+
|
||||
+void wlserver_banner_ahb_set_mode( bool bEnabled )
|
||||
+{
|
||||
+ if ( g_nBannerAhbMode.exchange( bEnabled ? 1 : 0 ) == ( bEnabled ? 1 : 0 ) )
|
||||
+ return;
|
||||
+ wl_log.infof( "banner_ahb_v1: host compositor %s Android swapchain buffers", bEnabled ? "wants" : "does not want" );
|
||||
+ if ( !wlserver.display )
|
||||
+ return;
|
||||
+ wlserver_lock();
|
||||
+ for ( wl_resource *pResource : g_BannerAhbResources )
|
||||
+ {
|
||||
+ if ( wl_resource_get_version( pResource ) >= BANNER_AHB_V1_MODE_SINCE_VERSION )
|
||||
+ banner_ahb_v1_send_mode( pResource, bEnabled ? 1u : 0u );
|
||||
+ }
|
||||
+ wlserver_unlock();
|
||||
+}
|
||||
+
|
||||
+bool wlserver_banner_ahb_take( int nDmabufFd, wlserver_banner_ahb_attach *pOut )
|
||||
+{
|
||||
+ struct stat st;
|
||||
+ if ( fstat( nDmabufFd, &st ) != 0 )
|
||||
+ return false;
|
||||
+ std::scoped_lock lock( g_BannerAhbMutex );
|
||||
+ auto iter = g_BannerAhbPending.find( st.st_ino );
|
||||
+ if ( iter == g_BannerAhbPending.end() )
|
||||
+ return false;
|
||||
+ banner_ahb_pending *pPending = iter->second;
|
||||
+ g_BannerAhbPending.erase( iter );
|
||||
+ pPending->queued = false;
|
||||
+ if ( pPending->sock < 0 )
|
||||
+ return false;
|
||||
+ *pOut = wlserver_banner_ahb_attach
|
||||
+ {
|
||||
+ .sock = pPending->sock,
|
||||
+ .width = pPending->width,
|
||||
+ .height = pPending->height,
|
||||
+ .stride = pPending->stride,
|
||||
+ .mod_hi = pPending->mod_hi,
|
||||
+ .mod_lo = pPending->mod_lo,
|
||||
+ .image_count = pPending->image_count,
|
||||
+ };
|
||||
+ pPending->sock = -1;
|
||||
+ return true;
|
||||
+}
|
||||
+
|
||||
static void create_gamescope_swapchain_factory_v2( void )
|
||||
{
|
||||
uint32_t version = 1;
|
||||
@@ -2255,6 +2421,7 @@ bool wlserver_init( void ) {
|
||||
create_gamescope_xwayland();
|
||||
|
||||
create_gamescope_swapchain_factory_v2();
|
||||
+ create_banner_ahb();
|
||||
|
||||
new gamescope::WaylandServer::CGamescopeLimiterProtocol( wlserver.display );
|
||||
|
||||
diff --git a/src/wlserver.hpp b/src/wlserver.hpp
|
||||
index b35faca..6d92c23 100644
|
||||
--- a/src/wlserver.hpp
|
||||
+++ b/src/wlserver.hpp
|
||||
@@ -263,6 +263,16 @@ bool wlserver_init( void );
|
||||
|
||||
void wlserver_run(void);
|
||||
|
||||
+struct wlserver_banner_ahb_attach
|
||||
+{
|
||||
+ int sock;
|
||||
+ uint32_t width, height, stride, mod_hi, mod_lo, image_count;
|
||||
+};
|
||||
+// banner_ahb_v1: the host compositor's mode, relayed to clients; and the Android buffer a client attached to the
|
||||
+// dma-buf behind nDmabufFd, taken once (the caller owns pOut->sock).
|
||||
+void wlserver_banner_ahb_set_mode( bool bEnabled );
|
||||
+bool wlserver_banner_ahb_take( int nDmabufFd, wlserver_banner_ahb_attach *pOut );
|
||||
+
|
||||
void wlserver_lock(void);
|
||||
void wlserver_unlock(bool flush = true);
|
||||
bool wlserver_is_lock_held(void);
|
||||
@@ -855,18 +855,49 @@ def scripts_digest(scripts):
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def only_guarded_runs(items):
|
||||
# True when every action in the scripts is a "run process" entry. With all their hasrunkeys set, Steam's
|
||||
# evaluator would run nothing, so the scripts need no run even when Steam has rewritten the file (its
|
||||
# SteamID, language, install path or order change between launches).
|
||||
found = False
|
||||
for _, entries in items:
|
||||
if not isinstance(entries, list):
|
||||
return False
|
||||
for _, entry in entries:
|
||||
if not isinstance(entry, list):
|
||||
return False
|
||||
for _, block in entry:
|
||||
if not isinstance(block, list):
|
||||
continue
|
||||
for section, actions in block:
|
||||
if section.lower() != "run process" or not isinstance(actions, list):
|
||||
return False
|
||||
for _, action in actions:
|
||||
if not isinstance(action, list) or not any(
|
||||
isinstance(v, str) and re.fullmatch(r"process [0-9]+", n.lower()) for n, v in action):
|
||||
return False
|
||||
found = True
|
||||
return found
|
||||
|
||||
|
||||
def install_scripts_done(scripts, env):
|
||||
prefix = Path(env.get("STEAM_COMPAT_DATA_PATH", "/nonexistent")) / "pfx"
|
||||
try:
|
||||
if (prefix / INSTALL_STAMP).read_text().strip() != scripts_digest(scripts):
|
||||
return False
|
||||
keys = set()
|
||||
keys, parsed = set(), []
|
||||
for path in scripts:
|
||||
keys |= run_keys(read_vdf(Path(path).read_text(encoding="utf-8", errors="replace")))
|
||||
parsed.append(read_vdf(Path(path).read_text(encoding="utf-8", errors="replace")))
|
||||
keys |= run_keys(parsed[-1])
|
||||
values = registry_values(prefix / "system.reg")
|
||||
except (OSError, ValueError):
|
||||
return False
|
||||
return bool(keys) and all(has_run(key, value, values) for key, value in keys)
|
||||
if not keys or not all(has_run(key, value, values) for key, value in keys):
|
||||
return False
|
||||
try:
|
||||
if (prefix / INSTALL_STAMP).read_text().strip() == scripts_digest(scripts):
|
||||
return True
|
||||
except OSError:
|
||||
pass
|
||||
return all(only_guarded_runs(items) for items in parsed)
|
||||
|
||||
|
||||
def record_install_scripts(digest, env):
|
||||
|
||||
@@ -13,8 +13,10 @@ RELEASES = "https://api.github.com/repos/%s/releases"
|
||||
SOURCES = {
|
||||
"ge": ("GloriousEggroll/proton-ge-custom", re.compile(r"aarch64\.tar\.(gz|xz)$")),
|
||||
"cachyos": ("CachyOS/proton-cachyos", re.compile(r"arm64\.tar\.(gz|xz)$")),
|
||||
"droiddeck": ("Droid-Deck/DroidDeck-Proton", re.compile(r"aarch64\.tar\.(gz|xz)$")),
|
||||
"droiddeck": ("Droid-Deck/DroidDeck-Proton", re.compile(r"^DroidDeck-Proton-.*aarch64\.tar\.(gz|xz)$")),
|
||||
"bionic": ("Droid-Deck/DroidDeck-Proton", re.compile(r"^DroidDeck-Bionic-.*aarch64\.tar\.(gz|xz)$")),
|
||||
}
|
||||
PRERELEASES = {"bionic"}
|
||||
USER_AGENT = "droiddeck-proton-extra"
|
||||
NEED_BYTES = 4 * 1024 * 1024 * 1024
|
||||
|
||||
@@ -33,7 +35,7 @@ def fetch_json(url):
|
||||
def pick_asset(source):
|
||||
repo, pattern = SOURCES[source]
|
||||
for release in fetch_json(RELEASES % repo + "?per_page=15"):
|
||||
if release.get("draft") or release.get("prerelease"):
|
||||
if release.get("draft") or (release.get("prerelease") and source not in PRERELEASES):
|
||||
continue
|
||||
assets = {a["name"]: a["browser_download_url"] for a in release.get("assets", ())}
|
||||
for name in sorted(assets):
|
||||
|
||||
@@ -364,12 +364,6 @@ def rockstar_launcher_log(compat_data, limit=65536):
|
||||
return [line.strip() for line in data.decode("utf-8", "replace").splitlines() if line.strip()]
|
||||
|
||||
|
||||
def ships_sdk(root, exe):
|
||||
return any(directory.is_dir() and any(p.is_file() and not p.is_symlink() and p.name.lower() in ("socialclub.dll", "socialclub64.dll")
|
||||
for p in directory.iterdir())
|
||||
for directory in {root, exe.parent})
|
||||
|
||||
|
||||
def rockstar_sdk(folder, sidecar):
|
||||
if str(sidecar.get("id")) in ("gta4", "lanoire"):
|
||||
return True
|
||||
@@ -377,8 +371,10 @@ def rockstar_sdk(folder, sidecar):
|
||||
exe = (folder / str(sidecar.get("exe") or "").replace("\\", "/")).resolve()
|
||||
if not exe.is_relative_to(root):
|
||||
return False
|
||||
if ships_sdk(root, exe):
|
||||
return True
|
||||
for directory in {root, exe.parent}:
|
||||
if directory.is_dir() and any(p.is_file() and not p.is_symlink() and p.name.lower() in ("socialclub.dll", "socialclub64.dll")
|
||||
for p in directory.iterdir()):
|
||||
return True
|
||||
if str(sidecar.get("id")) in ROCKSTAR_TITLES:
|
||||
return False
|
||||
level = [root]
|
||||
@@ -547,15 +543,7 @@ def prepare_rockstar(folder, sidecar, compat_data, launch_dir, proton="", ask_ap
|
||||
return "prefix-" + made
|
||||
arch = "x86" if signature[4:] == b"\x4c\x01" else "x64"
|
||||
if sdk:
|
||||
runtime = rockstar_runtime(folder, exe, compat_data, arch)
|
||||
if runtime == "game-runtime" and not ships_sdk(root, exe):
|
||||
answer = (ask_app or ask)(Path(launch_dir) / "stores", {"op": "rockstar-sdk", "store": "rockstar", "id": str(sidecar.get("id"))},
|
||||
timeout=SERVICE_WAIT)
|
||||
if isinstance(answer, dict) and answer.get("ok"):
|
||||
runtime = rockstar_runtime(folder, exe, compat_data, arch)
|
||||
else:
|
||||
runtime = "sdk-" + (str(answer.get("reason") or "refused") if isinstance(answer, dict) else "timeout")
|
||||
log("rockstar runtime: " + runtime)
|
||||
log("rockstar runtime: " + rockstar_runtime(folder, exe, compat_data, arch))
|
||||
if not rockstar_registry(folder, title, compat_data, proton, sdk_arch=arch if sdk else None):
|
||||
return "registry-unavailable"
|
||||
target.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
@@ -187,6 +187,9 @@ dd_components() {
|
||||
# The selected system PowerVR runtime supplies DXVK at launch. Keep saved selections
|
||||
# for a later manual-driver session without rewriting this Proton's bundled files now.
|
||||
[ "$comp" = dxvk ] && [ -n "${DROIDDECK_POWERVR_RUNTIME:-}" ] && continue
|
||||
# DroidDeck-Bionic loads only Android-built FEX unix libraries: -bionic packages or its own saved copy.
|
||||
# A row without such a source (a glibc package, or a removal) is skipped and the tool keeps its FEX files.
|
||||
if [ "$comp" = fex ] && [[ "$cm_tool" == DroidDeck-Bionic* ]] && [[ "${src,,}" != *bionic* ]]; then continue; fi
|
||||
cm_rows+=("$comp"$'\\t'"$rel"$'\\t'"$sum"$'\\t'"$src")
|
||||
[ "$src" != "-" ] && [ -f "$base/$rel" ] && cm_files+=("$base/$rel")
|
||||
done <<< "$cm_selected"
|
||||
@@ -290,6 +293,21 @@ dd_vacdiag() {
|
||||
}
|
||||
"""
|
||||
|
||||
# DroidDeck-Bionic runs only without proot. With proot on, a launch Steam sends to a DroidDeck-Bionic tool goes to the
|
||||
# newest DroidDeck-Proton's wrapper before anything else runs, as if that Proton had been picked; the picks stay as set.
|
||||
DD_BIONIC_PROOT_FALLBACK = """
|
||||
if [ -f "$here/bionic/launch.sh" ] && [ -z "${DDNATV_ROOT:-}" ]; then
|
||||
dd_fallback=$(cd "$here/.." 2>/dev/null && for d in DroidDeck-Proton*; do
|
||||
[ -x "$d/droiddeck-proton-wrap" ] && [ ! -e "$d/bionic/launch.sh" ] || continue
|
||||
v=${d#DroidDeck-Proton}; printf '%s\\t%s/%s\\n' "${v#[ -]}" "$PWD" "$d"
|
||||
done | sort -V | tail -n 1 | cut -f 2-)
|
||||
if [ -n "$dd_fallback" ]; then
|
||||
echo "droiddeck-proton: DroidDeck-Bionic needs Run without proot; this launch uses ${dd_fallback##*/}" >&2
|
||||
exec "$dd_fallback/droiddeck-proton-wrap" "$verb" "$@"
|
||||
fi
|
||||
fi
|
||||
"""
|
||||
|
||||
DD_DRIVER_QUERY_SKIP = """
|
||||
case "$verb:${1##*/}:${STEAM_COMPAT_DATA_PATH%/}" in
|
||||
run:d3ddriverquery64.exe:*/compatdata/0 | run:d3ddriverquery.exe:*/compatdata/0)
|
||||
@@ -487,7 +505,7 @@ dd_run ${DD_TASKSET:-} /usr/local/bin/droiddeck-game-env "$DD_STORE_PROTON" "$ve
|
||||
def extra_wrapper_sh(entry_point):
|
||||
return (EXTRA_WRAPPER_SH % entry_point).replace(
|
||||
'here=$(dirname "$0")',
|
||||
'here=$(dirname "$0")\n' + DD_DRIVER_QUERY_SKIP + DD_DESKTOP_GPU_SETUP + DD_DIRECTAUDIO_SETUP + DD_GAME_CPUS_SETUP
|
||||
'here=$(dirname "$0")\n' + DD_BIONIC_PROOT_FALLBACK + DD_DRIVER_QUERY_SKIP + DD_DESKTOP_GPU_SETUP + DD_DIRECTAUDIO_SETUP + DD_GAME_CPUS_SETUP
|
||||
+ DD_IDTECH3_SETUP + DD_VACDIAG_SETUP + DD_COMPONENTS_SETUP + DD_LIBPATH_SETUP + DD_STORE_SETUP, 1)
|
||||
|
||||
|
||||
|
||||
@@ -111,9 +111,6 @@ typedef int (*accept4_fn)(int, struct sockaddr *, socklen_t *, int);
|
||||
static unsigned guarded_port(void);
|
||||
|
||||
__attribute__((visibility("hidden"))) int dd_udevmon_stand_in(int fd);
|
||||
__attribute__((visibility("hidden"))) int dd_udevmon_bind(int fd, const struct sockaddr *addr, socklen_t len,
|
||||
int (*real_bind)(int, const struct sockaddr *, socklen_t),
|
||||
int *rc);
|
||||
__attribute__((visibility("hidden"))) int dd_nl_bind(int fd, const struct sockaddr *addr,
|
||||
socklen_t len, int *rc);
|
||||
__attribute__((visibility("hidden"))) int dd_nl_connect(int fd, const struct sockaddr *addr,
|
||||
@@ -124,7 +121,6 @@ int bind(int fd, const struct sockaddr *addr, socklen_t len) {
|
||||
int nl_rc;
|
||||
if (!real) real = (bind_fn)dlsym(RTLD_NEXT, "bind");
|
||||
if (dd_nl_bind(fd, addr, len, &nl_rc)) return nl_rc;
|
||||
if (dd_udevmon_bind(fd, addr, len, real, &nl_rc)) return nl_rc;
|
||||
if (dd_udevmon_stand_in(fd)) {
|
||||
if (addr == NULL || len < sizeof(struct sockaddr_nl) || addr->sa_family != AF_NETLINK) {
|
||||
errno = EINVAL;
|
||||
|
||||
@@ -14,7 +14,6 @@
|
||||
#include <sys/stat.h>
|
||||
#include <endian.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <unistd.h>
|
||||
|
||||
struct stand_in {
|
||||
@@ -147,61 +146,6 @@ __attribute__((visibility("hidden"))) int dd_udevmon_stand_in(int fd) {
|
||||
return is_stand_in(fd);
|
||||
}
|
||||
|
||||
static int subscribed(int fd) {
|
||||
#ifdef UDEVMON_TEST
|
||||
if (getenv("DD_UDEVMON_REFUSE") != NULL) return 0;
|
||||
#endif
|
||||
struct sockaddr_nl nl;
|
||||
socklen_t len = sizeof(nl);
|
||||
memset(&nl, 0, sizeof(nl));
|
||||
return getsockname(fd, (struct sockaddr *)&nl, &len) == 0 && nl.nl_groups != 0;
|
||||
}
|
||||
|
||||
/* Android lets an app open a uevent socket but not join its multicast groups, and libudev joins none
|
||||
when no udev daemon runs, so a monitor bound there hears nothing. Such a socket is replaced, under
|
||||
the same descriptor, by a stand-in. */
|
||||
__attribute__((visibility("hidden"))) int dd_udevmon_bind(int fd, const struct sockaddr *addr, socklen_t len,
|
||||
int (*real_bind)(int, const struct sockaddr *, socklen_t),
|
||||
int *rc) {
|
||||
int protocol = -1;
|
||||
socklen_t protocol_len = sizeof(protocol);
|
||||
if (addr == NULL || len < sizeof(struct sockaddr_nl) || addr->sa_family != AF_NETLINK) return 0;
|
||||
if (is_stand_in(fd) || is_wine_process()) return 0;
|
||||
if (getsockopt(fd, SOL_SOCKET, SO_PROTOCOL, &protocol, &protocol_len) != 0 || protocol != NETLINK_KOBJECT_UEVENT)
|
||||
return 0;
|
||||
*rc = real_bind(fd, addr, len);
|
||||
int refused = errno;
|
||||
if (*rc == 0 && subscribed(fd)) return 1;
|
||||
int status = fcntl(fd, F_GETFL);
|
||||
int descriptor = fcntl(fd, F_GETFD);
|
||||
int sv[2];
|
||||
if (status < 0 || descriptor < 0 || socketpair(AF_UNIX, SOCK_DGRAM | SOCK_CLOEXEC, 0, sv) != 0) {
|
||||
errno = refused;
|
||||
return 1;
|
||||
}
|
||||
pthread_mutex_lock(&lock);
|
||||
size_t slot = sizeof(stand_ins) / sizeof(stand_ins[0]);
|
||||
for (size_t i = 0; i < sizeof(stand_ins) / sizeof(stand_ins[0]); i++) {
|
||||
if (stand_ins[i].fd == -1) { slot = i; break; }
|
||||
}
|
||||
if (slot == sizeof(stand_ins) / sizeof(stand_ins[0]) ||
|
||||
dup3(sv[0], fd, (descriptor & FD_CLOEXEC) ? O_CLOEXEC : 0) < 0) {
|
||||
pthread_mutex_unlock(&lock);
|
||||
close(sv[0]);
|
||||
close(sv[1]);
|
||||
errno = refused;
|
||||
return 1;
|
||||
}
|
||||
close(sv[0]);
|
||||
if (status & O_NONBLOCK) fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) | O_NONBLOCK);
|
||||
stand_ins[slot].fd = fd;
|
||||
stand_ins[slot].peer = sv[1];
|
||||
stand_ins[slot].inode = socket_inode(fd);
|
||||
pthread_mutex_unlock(&lock);
|
||||
*rc = 0;
|
||||
return 1;
|
||||
}
|
||||
|
||||
int getsockname(int fd, struct sockaddr *addr, socklen_t *len) {
|
||||
static int (*real_getsockname)(int, struct sockaddr *, socklen_t *);
|
||||
struct sockaddr_nl nl;
|
||||
|
||||
+20
-72
@@ -26,52 +26,30 @@ PACKAGE = "com.droiddeck.launcher"
|
||||
SESSION = f"{PACKAGE}/.SessionActivity"
|
||||
HOG_PATH = "/data/local/tmp/dd-memory-hog.sh"
|
||||
HOG_MOUNT = "/dev/dd-memory-hog"
|
||||
SEED_PATH = "/data/local/tmp/dd-memory-burst.bin"
|
||||
|
||||
# oom_score_adj is read without su: under pressure lmkd kills the root manager app, and each su call
|
||||
# can then open its request screen on top of the game.
|
||||
# Incompressible data in a private tmpfs: zram cannot shrink it and no app owns it, so lmkd keeps
|
||||
# killing by oom_score_adj while it is held.
|
||||
HOG = f"""#!/system/bin/sh
|
||||
stop_mb=$1; hold=$2; mode=$3
|
||||
cleanup() {{ kill $(jobs -p) 2>/dev/null; rm -f {HOG_MOUNT}/f*; umount {HOG_MOUNT} 2>/dev/null; }}
|
||||
stop_mb=$1; hold=$2
|
||||
cleanup() {{ rm -f {HOG_MOUNT}/f*; umount {HOG_MOUNT} 2>/dev/null; }}
|
||||
trap 'cleanup; exit 1' HUP INT TERM
|
||||
mkdir -p {HOG_MOUNT}
|
||||
grep -q ' {HOG_MOUNT} ' /proc/mounts || mount -t tmpfs -o size=16g tmpfs {HOG_MOUNT}
|
||||
i=0; failed=0
|
||||
if [ "$mode" = burst ]; then
|
||||
[ "$(stat -c %s {SEED_PATH} 2>/dev/null)" = 268435456 ] ||
|
||||
{{ head -c 268435456 /dev/urandom > {SEED_PATH}.tmp && mv {SEED_PATH}.tmp {SEED_PATH}; }} ||
|
||||
{{ rm -f {SEED_PATH}.tmp; cleanup; exit 1; }}
|
||||
cat {SEED_PATH} > /dev/null
|
||||
avail=$(awk '/MemAvailable/ {{print int($2/1024)}}' /proc/meminfo)
|
||||
echo "avail=$avail"
|
||||
take=$((avail - stop_mb))
|
||||
[ "$take" -gt 0 ] || {{ echo "nothing to take"; cleanup; exit 2; }}
|
||||
n=$((take / 256)); rest=$((take % 256)); pids=""
|
||||
echo "burst_mb=$take start=$(date +%s%N)"
|
||||
while [ $i -lt $n ]; do cat {SEED_PATH} > {HOG_MOUNT}/f$i & pids="$pids $!"; i=$((i+1)); done
|
||||
[ "$rest" -gt 0 ] && {{ head -c $((rest * 1048576)) {SEED_PATH} > {HOG_MOUNT}/f$i & pids="$pids $!"; }}
|
||||
for pid in $pids; do wait "$pid" || failed=1; done
|
||||
echo "burst_done=$(date +%s%N)"
|
||||
echo "avail=$(awk '/MemAvailable/ {{print int($2/1024)}}' /proc/meminfo)"
|
||||
i=512
|
||||
fi
|
||||
i=0
|
||||
while [ $i -lt 512 ]; do
|
||||
avail=$(awk '/MemAvailable/ {{print int($2/1024)}}' /proc/meminfo)
|
||||
echo "avail=$avail"
|
||||
[ "$avail" -le "$stop_mb" ] && break
|
||||
head -c 33554432 /dev/urandom > {HOG_MOUNT}/f$i || {{ failed=1; break; }}
|
||||
head -c 33554432 /dev/urandom > {HOG_MOUNT}/f$i || break
|
||||
i=$((i+1))
|
||||
done
|
||||
[ "$failed" = 0 ] || {{ echo "write failed"; cleanup; exit 1; }}
|
||||
sleep "$hold"
|
||||
cleanup
|
||||
echo released
|
||||
"""
|
||||
# Stops a writer left by an interrupted run before its files go, so the unmount does not fail. The
|
||||
# bracketed patterns keep pkill from matching the shell that runs this line.
|
||||
HOG_CLEANUP = (f"pkill -f '[d]d-memory-hog.sh'; pkill -f '[h]ead -c 33554432'; pkill -f '[d]d-memory-burst.bin'; sleep 1; rm -f {HOG_MOUNT}/f*; "
|
||||
HOG_CLEANUP = (f"pkill -f '[d]d-memory-hog.sh'; pkill -f '[h]ead -c 33554432'; sleep 1; rm -f {HOG_MOUNT}/f*; "
|
||||
f"umount {HOG_MOUNT} 2>/dev/null; true")
|
||||
|
||||
def focused_display(input_dump: str) -> int | None:
|
||||
@@ -80,7 +58,7 @@ def focused_display(input_dump: str) -> int | None:
|
||||
|
||||
|
||||
def activity_count(activities_dump: str, activity: str) -> int:
|
||||
return len(re.findall(r"Hist\s+#\d+: ActivityRecord\{\S+ u\d+ " + re.escape(activity) + r"[ }]", activities_dump))
|
||||
return len(re.findall(r"Hist\s+#\d+: ActivityRecord\{\S+ u\d+ " + re.escape(activity) + r" ", activities_dump))
|
||||
|
||||
|
||||
def guard_count(activities_dump: str) -> int:
|
||||
@@ -107,8 +85,7 @@ def panel_windows(windows_dump: str, display: int) -> int:
|
||||
|
||||
|
||||
def bottom_home(activities_dump: str, session_display: int) -> tuple[int, str] | None:
|
||||
"""The visible home on another display, else the visible app on top of it."""
|
||||
display, top = None, None
|
||||
display = None
|
||||
for line in activities_dump.splitlines():
|
||||
section = re.match(r"Display #(\d+) \(activities", line)
|
||||
if section:
|
||||
@@ -119,10 +96,7 @@ def bottom_home(activities_dump: str, session_display: int) -> tuple[int, str] |
|
||||
home = re.search(r"type=home A=\d+:(\S+) .*visible=true", line)
|
||||
if home:
|
||||
return display, home.group(1)
|
||||
app = re.search(r"type=standard A=\d+:([\w.]+) .*visible=true", line)
|
||||
if app and top is None and not app.group(1).startswith(PACKAGE):
|
||||
top = display, app.group(1)
|
||||
return top
|
||||
return None
|
||||
|
||||
|
||||
def logical_size(displays_dump: str, display: int) -> tuple[int, int] | None:
|
||||
@@ -177,11 +151,8 @@ class Device:
|
||||
return self.sh(f"su -c {shlex.quote(command)}", timeout=timeout)
|
||||
|
||||
def ctl(self, *args: str, timeout: int = 300) -> subprocess.CompletedProcess[str]:
|
||||
command = [str(TOOLS / "droiddeckctl"), "--adb", self.adb, "--serial", self.serial, *args]
|
||||
try:
|
||||
return subprocess.run(command, capture_output=True, text=True, timeout=timeout)
|
||||
except subprocess.TimeoutExpired:
|
||||
return subprocess.CompletedProcess(command, -1, "", f"timed out after {timeout} s")
|
||||
return subprocess.run([str(TOOLS / "droiddeckctl"), "--adb", self.adb, "--serial", self.serial, *args],
|
||||
capture_output=True, text=True, timeout=timeout)
|
||||
|
||||
def phase(self) -> str | None:
|
||||
match = re.search(r'"phase":\s*"(\w+)"', self.ctl("state").stdout)
|
||||
@@ -237,8 +208,7 @@ class Bench:
|
||||
|
||||
def prepare(self, apk: str | None):
|
||||
self.d.sh("input keyevent KEYCODE_WAKEUP")
|
||||
if self.d.ctl("stop", timeout=120).returncode != 0:
|
||||
self.d.sh(f"am force-stop {PACKAGE}")
|
||||
self.d.ctl("stop")
|
||||
if apk:
|
||||
env = dict(os.environ, ADB_SERIAL=self.d.serial)
|
||||
subprocess.run([str(TOOLS / "deploy_local.sh"), apk], env=env, check=True, capture_output=True)
|
||||
@@ -264,7 +234,7 @@ class Bench:
|
||||
"guards": guard_count(activities),
|
||||
"sessions": session_count(activities),
|
||||
"panel": panel_windows(self.d.sh("dumpsys window windows"), display),
|
||||
"adj": int(self.d.sh(f"cat /proc/{pid}/oom_score_adj").strip() or -9999),
|
||||
"adj": int(self.d.su(f"cat /proc/{pid}/oom_score_adj").strip() or -9999),
|
||||
"pid": pid,
|
||||
}
|
||||
|
||||
@@ -281,8 +251,7 @@ class Bench:
|
||||
before = self.snapshot()
|
||||
_, home = self.bottom()
|
||||
self.d.run("logcat", "-b", "events", "-c")
|
||||
self.d.su(f"kill -9 $(pidof {home})")
|
||||
samples = self.d.sh(f"for i in $(seq 50); do cat /proc/{before['pid']}/oom_score_adj"
|
||||
samples = self.d.su(f"kill -9 $(pidof {home}); for i in $(seq 50); do cat /proc/{before['pid']}/oom_score_adj"
|
||||
" 2>/dev/null || echo DEAD; sleep 0.1; done").split()
|
||||
events = self.d.run("logcat", "-b", "events", "-d")
|
||||
(self.out / f"{self.label}-{state}-events.txt").write_text(events)
|
||||
@@ -328,7 +297,7 @@ class Bench:
|
||||
self.probe("using_bottom_now")
|
||||
self.game_front()
|
||||
|
||||
def pressure(self, run: str, stop_mb: int, hold: int, burst: bool = False) -> bool:
|
||||
def pressure(self, run: str, stop_mb: int, hold: int):
|
||||
with tempfile.NamedTemporaryFile("w", suffix=".sh", delete=False) as script:
|
||||
script.write(HOG)
|
||||
try:
|
||||
@@ -336,18 +305,16 @@ class Bench:
|
||||
finally:
|
||||
os.unlink(script.name)
|
||||
self.d.sh(f"chmod 755 {HOG_PATH}")
|
||||
self.close_panel()
|
||||
self.game_front()
|
||||
self.tap(self.session_display, (0.36, 0.11))
|
||||
time.sleep(2)
|
||||
self.close_panel()
|
||||
before = self.snapshot()
|
||||
self.d.run("logcat", "-b", "events", "-c")
|
||||
hog = subprocess.Popen([self.d.adb, "-s", self.d.serial, "shell", f"su -c '{HOG_PATH} {int(stop_mb)} {int(hold)} {'burst' if burst else 'fill'}'"],
|
||||
hog = subprocess.Popen([self.d.adb, "-s", self.d.serial, "shell", f"su -c '{HOG_PATH} {int(stop_mb)} {int(hold)}'"],
|
||||
stdout=subprocess.PIPE, text=True)
|
||||
samples = []
|
||||
try:
|
||||
while hog.poll() is None:
|
||||
samples.append(self.d.sh(f"cat /proc/{before['pid']}/oom_score_adj 2>/dev/null || echo DEAD").strip())
|
||||
samples.append(self.d.su(f"cat /proc/{before['pid']}/oom_score_adj 2>/dev/null || echo DEAD").strip())
|
||||
time.sleep(0.5)
|
||||
output = hog.stdout.read() if hog.stdout else ""
|
||||
finally:
|
||||
@@ -357,19 +324,12 @@ class Bench:
|
||||
time.sleep(3)
|
||||
events = self.d.run("logcat", "-b", "events", "-d")
|
||||
(self.out / f"{self.label}-{run}-events.txt").write_text(events)
|
||||
workload_ok = hog.returncode == 0 and "released" in output.splitlines()
|
||||
if not workload_ok:
|
||||
print(f"memory-guard-ab: {run}: the memory hog failed (exit {hog.returncode}): "
|
||||
f"{output.strip().splitlines()[-1] if output.strip() else 'no output'}", file=sys.stderr)
|
||||
available = [int(value) for value in re.findall(r"avail=(\d+)", output)]
|
||||
took = re.search(r"start=(\d+).*?burst_done=(\d+)", output, re.S)
|
||||
self.write("pressure", {
|
||||
"run": run, "workload_ok": workload_ok, "mode": "burst" if burst else "fill", "stop_mb": stop_mb, "hold_s": hold,
|
||||
"burst_ms": (int(took.group(2)) - int(took.group(1))) // 1_000_000 if took else None, **{k: v for k, v in before.items() if k != "pid"},
|
||||
"run": run, "stop_mb": stop_mb, "hold_s": hold, **{k: v for k, v in before.items() if k != "pid"},
|
||||
"min_available_mb": min(available) if available else None, "adj_max": max_adj(samples),
|
||||
"droiddeck_alive": self.d.pid() == before["pid"], "phase": self.d.phase(), **summarize_events(events),
|
||||
})
|
||||
return workload_ok
|
||||
|
||||
|
||||
def fraction_pair(text: str) -> tuple[float, float]:
|
||||
@@ -395,8 +355,6 @@ def main() -> int:
|
||||
pressure.add_argument("--stop-mb", type=int, default=650, help="stop filling at this MemAvailable")
|
||||
pressure.add_argument("--hold", type=int, default=30)
|
||||
pressure.add_argument("--runs", type=int, default=1)
|
||||
pressure.add_argument("--burst", action="store_true",
|
||||
help="take everything above --stop-mb at once instead of filling 32 MiB at a time")
|
||||
summarize = commands.add_parser("summarize", help="summarize a saved events log")
|
||||
summarize.add_argument("events", type=Path)
|
||||
args = parser.parse_args()
|
||||
@@ -418,19 +376,9 @@ def main() -> int:
|
||||
bench.prepare(args.apk)
|
||||
bench.states()
|
||||
else:
|
||||
completed = 0
|
||||
for run in range(args.runs):
|
||||
try:
|
||||
bench.prepare(args.apk if run == 0 else None)
|
||||
except RuntimeError as exc:
|
||||
print(f"memory-guard-ab: run {run + 1} skipped: {exc}", file=sys.stderr)
|
||||
continue
|
||||
if bench.pressure(f"{'burst' if args.burst else 'stop'}{args.stop_mb}-{run + 1}", args.stop_mb,
|
||||
args.hold, args.burst):
|
||||
completed += 1
|
||||
if completed == 0:
|
||||
print("memory-guard-ab: no pressure run completed", file=sys.stderr)
|
||||
return 1
|
||||
bench.prepare(args.apk if run == 0 else None)
|
||||
bench.pressure(f"stop{args.stop_mb}-{run + 1}", args.stop_mb, args.hold)
|
||||
except RuntimeError as exc:
|
||||
print(f"memory-guard-ab: {exc}", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
+1
-19
@@ -11,8 +11,6 @@ linuxfs="$repo/app/src/main/assets/linuxfs/usr/local/lib"
|
||||
source "$here/tracking/release.env"
|
||||
# shellcheck source=butler/release.env
|
||||
source "$here/butler/release.env"
|
||||
# shellcheck source=zstd/release.env
|
||||
source "$here/zstd/release.env"
|
||||
|
||||
work=$(mktemp -d)
|
||||
trap 'rm -rf "$work"' EXIT
|
||||
@@ -23,22 +21,6 @@ fetch() {
|
||||
bash "$here/fetch-verified.sh" "$@"
|
||||
}
|
||||
|
||||
zstd_version() { "$1" -V 2>/dev/null | sed -n 's/.* v\([0-9][0-9.]*\),.*/\1/p'; }
|
||||
zstd=$(command -v zstd || true)
|
||||
if [ -z "$zstd" ] || [ "$(zstd_version "$zstd")" != "$ZSTD_VERSION" ]; then
|
||||
zstd="${DROIDDECK_PACK_CACHE:-"$HOME/.cache/droiddeck-pack-inputs"}/zstd-$ZSTD_VERSION/zstd"
|
||||
if [ ! -x "$zstd" ] || [ "$(zstd_version "$zstd")" != "$ZSTD_VERSION" ]; then
|
||||
fetch "https://github.com/facebook/zstd/releases/download/v$ZSTD_VERSION/zstd-$ZSTD_VERSION.tar.gz" \
|
||||
"$ZSTD_SHA256" "$work/zstd.tar.gz"
|
||||
tar -xzf "$work/zstd.tar.gz" -C "$work"
|
||||
make -s -C "$work/zstd-$ZSTD_VERSION" -j"$(getconf _NPROCESSORS_ONLN 2>/dev/null || echo 2)" zstd-release >/dev/null
|
||||
mkdir -p "$(dirname "$zstd")"
|
||||
install -m755 "$work/zstd-$ZSTD_VERSION/programs/zstd" "$zstd.part.$$"
|
||||
mv -f "$zstd.part.$$" "$zstd"
|
||||
fi
|
||||
fi
|
||||
[ "$(zstd_version "$zstd")" = "$ZSTD_VERSION" ] || { echo "packs need zstd $ZSTD_VERSION, $zstd is not it" >&2; exit 1; }
|
||||
|
||||
pack() {
|
||||
local name=$1 src=$2
|
||||
shift 2
|
||||
@@ -65,7 +47,7 @@ with tarfile.open(dest, "w", format=tarfile.USTAR_FORMAT) as tar:
|
||||
with open(path, "rb") as f:
|
||||
tar.addfile(info, f)
|
||||
EOF
|
||||
"$zstd" -q -19 -f "$work/$name.tar" -o "$out/$name.tar.zst"
|
||||
zstd -q -19 -f "$work/$name.tar" -o "$out/$name.tar.zst"
|
||||
echo "$name $(sha256 "$out/$name.tar.zst") $(wc -c < "$out/$name.tar.zst" | tr -d ' ')"
|
||||
}
|
||||
|
||||
|
||||
@@ -1,2 +0,0 @@
|
||||
ZSTD_VERSION=1.5.5
|
||||
ZSTD_SHA256=9c4396cc829cfae319a6e2615202e82aad41372073482fce286fac78646d3ee4
|
||||
@@ -6,7 +6,7 @@ The handoff is mode 0600, expires after 90 seconds and is deleted before startin
|
||||
|
||||
GTA III, Vice City and San Andreas use body-length MTLX replies. GTA IV and L.A. Noire use total-length, terminated replies. Titles with installed Social Club metadata or SDK binaries use the SDK IPC adapter, including user-info, login, ticket, initialization and authorized title-state synchronization. The title metadata supplies the ROS identity and principal executable; it is checked against Rockstar's catalog before title authorization. Other titles retain Play and Steam shortcuts and attempt the normal executable launch path.
|
||||
|
||||
The SDK runtime is extracted from the game's own Social-Club-Setup.exe when present. A title that ships neither the installer nor `socialclub.dll` gets the installer from the account's Rockstar Games Launcher build, downloaded by the app into the game's `Redistributables` folder with each chunk's hash checked. Architecture-specific payloads are staged into the prefix, archive paths and sizes are checked, interrupted copies are retried, and both registry views are registered. The helper discovers launcher identity pipe names in the game executable and the executables beside it, because protected game executables resolve that name only at run time, and answers bounded INIT challenges from the launched process. No vendor executables or runtime files are bundled with this tool. SDK initialization has a 90-second deadline. SDK wire tests and fixture clients do not establish gameplay compatibility for every title; per-title ROS ticket exchange and secondary SDK channels remain unverified.
|
||||
The SDK runtime is extracted from the game's own Social-Club-Setup.exe when present. Architecture-specific payloads are staged into the prefix, archive paths and sizes are checked, interrupted copies are retried, and both registry views are registered. The helper discovers launcher identity pipe names in the game executable and the executables beside it, because protected game executables resolve that name only at run time, and answers bounded INIT challenges from the launched process. No vendor executables or runtime files are bundled with this tool. SDK initialization has a 90-second deadline. SDK wire tests and fixture clients do not establish gameplay compatibility for every title; per-title ROS ticket exchange and secondary SDK channels remain unverified.
|
||||
|
||||
GTA III defaults to full x87 precision for FEX before Wine starts, because reduced precision crashed new-game initialization on the test device. San Andreas defaults to WineD3D, because DXVK intermittently corrupted its textures; full precision and conservative memory ordering did not prevent that corruption. These defaults use DroidDeck's per-game settings and preserve explicit per-game overrides.
|
||||
|
||||
|
||||
@@ -19,8 +19,7 @@ class CdpGuardTest(unittest.TestCase):
|
||||
subprocess.run(["cc", "-shared", "-fPIC", "-O2", str(SOURCE), str(SOURCE.parent / "binfmt.c"), str(SOURCE.parent / "webhelper.c"),
|
||||
str(Path(__file__).with_name("netlink_stubs.c")), "-x", "c", "-", "-ldl",
|
||||
"-o", str(cls.library)],
|
||||
input=b"int dd_udevmon_stand_in(int fd) { return 0; }\n"
|
||||
b"int dd_udevmon_bind(int fd, const void *addr, unsigned len, void *real, int *rc) { return 0; }", check=True, capture_output=True)
|
||||
input=b"int dd_udevmon_stand_in(int fd) { return 0; }", check=True, capture_output=True)
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
|
||||
@@ -1168,12 +1168,35 @@ class GameEnvironmentTest(unittest.TestCase):
|
||||
self.assertFalse(done([str(script)], env))
|
||||
(prefix / "system.reg").write_text(self.REDIST + self.SETUP)
|
||||
self.assertTrue(done([str(script)], env))
|
||||
# Steam rewrote the file: only marked "run process" entries, so its evaluator would run nothing either
|
||||
script.write_text(self.SCRIPT.replace("x64.cmd", "x64-update.cmd"))
|
||||
self.assertTrue(done([str(script)], env))
|
||||
script.write_text(self.SCRIPT.replace('"Setup"', '"Setup 2"'))
|
||||
self.assertFalse(done([str(script)], env))
|
||||
script.write_text('"InstallScript" { "Registry" { "HKEY_LOCAL_MACHINE\\\\Software\\\\Game" { "string" { "Path" "%INSTALLDIR%" } } } }')
|
||||
MODULE["record_install_scripts"](MODULE["scripts_digest"]([str(script)]), env)
|
||||
self.assertFalse(done([str(script)], env))
|
||||
|
||||
def test_marked_run_process_scripts_count_as_done_without_a_record(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
script = Path(tmp) / "evaluatorscript_291550.vdf"
|
||||
script.write_text(self.SCRIPT.replace('"0" { "appid" "228980"',
|
||||
'"0" { "appid" "228980" "mode" "1" "language" "english" '
|
||||
'"install_path" "/root/x" "SteamID" "7656"'))
|
||||
prefix = Path(tmp) / "compat/pfx"
|
||||
prefix.mkdir(parents=True)
|
||||
env = {"STEAM_COMPAT_DATA_PATH": str(prefix.parent)}
|
||||
done = MODULE["install_scripts_done"]
|
||||
(prefix / "system.reg").write_text(self.REDIST)
|
||||
self.assertFalse(done([str(script)], env))
|
||||
(prefix / "system.reg").write_text(self.REDIST + self.SETUP)
|
||||
self.assertTrue(done([str(script)], env))
|
||||
(prefix / MODULE["INSTALL_STAMP"]).write_text("an older digest\n")
|
||||
self.assertTrue(done([str(script)], env))
|
||||
script.write_text(self.SCRIPT.replace('"run process" {',
|
||||
'"registry" { "HKEY_LOCAL_MACHINE\\\\Software\\\\Game" { "string" { "Path" "x" } } } "run process" {'))
|
||||
self.assertFalse(done([str(script)], env))
|
||||
|
||||
def test_the_evaluator_is_skipped_once_it_finished_the_same_scripts(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
@@ -1189,8 +1212,12 @@ class GameEnvironmentTest(unittest.TestCase):
|
||||
proton.write_text("#!/bin/sh\necho run >> %s\nexit ${EXIT_CODE:-0}\n" % shlex.quote(str(runs)))
|
||||
proton.chmod(0o755)
|
||||
|
||||
def evaluate(exit_code="0"):
|
||||
script.write_text(self.SCRIPT if exit_code != "changed" else self.SCRIPT.replace("setup.exe", "setup-update.exe"))
|
||||
# a registry action besides the marked runs: Steam's evaluator has work to do, so it runs once
|
||||
with_registry = self.SCRIPT.replace(
|
||||
'"run process" {', '"registry" { "HKEY_LOCAL_MACHINE\\\\Software\\\\Game" { "string" { "Path" "x" } } } "run process" {')
|
||||
|
||||
def evaluate(exit_code="0", text=None):
|
||||
script.write_text(text or (with_registry if exit_code != "changed" else with_registry.replace("setup.exe", "setup-update.exe")))
|
||||
env = dict(os.environ, HOME=tmp, STEAM_COMPAT_CLIENT_INSTALL_PATH=str(root),
|
||||
STEAM_COMPAT_DATA_PATH=str(prefix.parent), EXIT_CODE="0" if exit_code == "changed" else exit_code)
|
||||
result = subprocess.run([sys.executable, str(BIN / "droiddeck-game-env"), str(proton), "run",
|
||||
@@ -1203,6 +1230,8 @@ class GameEnvironmentTest(unittest.TestCase):
|
||||
self.assertEqual(evaluate(), (0, 2))
|
||||
self.assertEqual(evaluate(), (0, 2))
|
||||
self.assertEqual(evaluate("changed"), (0, 3))
|
||||
# only marked "run process" entries, all set: skipped even though the file differs from the recorded one
|
||||
self.assertEqual(evaluate(text=self.SCRIPT.replace("x64.cmd", "x64-update.cmd")), (0, 3))
|
||||
|
||||
def test_the_mali_bridge_caps_the_vkd3d_feature_level(self):
|
||||
bridge = {"DD_VKBRIDGE": "1", "VKD3D_FEATURE_LEVEL": "12_2"}
|
||||
@@ -1392,6 +1421,61 @@ class GameEnvironmentTest(unittest.TestCase):
|
||||
self.assertFalse(leftover.exists())
|
||||
self.assertEqual(selection.read_bytes(), saved)
|
||||
|
||||
def test_droiddeck_bionic_takes_only_android_fex_rows(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
home = root / "home"
|
||||
component_dir = home / ".local/share/droiddeck-components"
|
||||
store = component_dir / "store"
|
||||
component_dir.mkdir(parents=True)
|
||||
unix = "files/lib/wine/aarch64-unix/libwow64fex.so"
|
||||
other = "files/lib/wine/aarch64-unix/libarm64ecfex.so"
|
||||
dll = "files/lib/wine/aarch64-windows/libwow64fex.dll"
|
||||
digest = lambda path: hashlib.sha256(path.read_bytes()).hexdigest()
|
||||
|
||||
def source(key, rel, text):
|
||||
path = store / key / rel
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(text)
|
||||
return path
|
||||
|
||||
def row(scope, tool, rel, path):
|
||||
return "%s\t%s\tbuild-1\tfex\t%s\t%s\t%s\n" % (scope, tool, rel, digest(path), path)
|
||||
|
||||
bionic, glibc_tool = "DroidDeck-Bionic-12.8-r24", "DroidDeck-Proton-11-12.8"
|
||||
for tool in (bionic, glibc_tool):
|
||||
for rel in (unix, other, dll):
|
||||
(root / tool / rel).parent.mkdir(parents=True, exist_ok=True)
|
||||
(root / tool / rel).write_text("bundled " + rel)
|
||||
(root / tool / "version").write_text("1 build-1\n")
|
||||
glibc = source("FEXCore-2611-linux", unix, "glibc so")
|
||||
android = source("FEXCore-2611-bionic", unix, "android so")
|
||||
android_dll = source("FEXCore-2611-Bionic", dll, "android dll")
|
||||
saved = source("original-%s-%s-fex" % (bionic, bionic), unix, "saved android so")
|
||||
rows = []
|
||||
for tool in (bionic, glibc_tool):
|
||||
rows += [row("42", tool, unix, glibc), "42\t%s\tbuild-1\tfex\t%s\t-\t-\n" % (tool, other)]
|
||||
rows += [row("43", tool, unix, android), row("43", tool, dll, android_dll)]
|
||||
rows += [row("*", tool, unix, saved)]
|
||||
(component_dir / "desired.tsv").write_text("".join(rows))
|
||||
script = COMPAT["DD_COMPONENTS_SETUP"] + '\nverb=waitforexitandrun; dd_components "$1"\n'
|
||||
run = lambda tool, app: subprocess.run(
|
||||
["bash", "-c", script, "test", str(root / tool)], check=True, capture_output=True,
|
||||
env=dict(os.environ, HOME=str(home), STEAM_COMPAT_DATA_PATH="/steam/compatdata/" + app))
|
||||
|
||||
run(bionic, "42")
|
||||
self.assertEqual((root / bionic / unix).read_text(), "bundled " + unix)
|
||||
self.assertEqual((root / bionic / other).read_text(), "bundled " + other)
|
||||
run(bionic, "43")
|
||||
self.assertEqual((root / bionic / unix).read_text(), "android so")
|
||||
self.assertEqual((root / bionic / dll).read_text(), "android dll")
|
||||
run(bionic, "44")
|
||||
self.assertEqual((root / bionic / unix).read_text(), "saved android so")
|
||||
|
||||
run(glibc_tool, "42")
|
||||
self.assertEqual((root / glibc_tool / unix).read_text(), "glibc so")
|
||||
self.assertFalse((root / glibc_tool / other).exists())
|
||||
|
||||
def test_component_scope_matches_environment_scope_for_shortcut_ids(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
@@ -2223,6 +2307,46 @@ class GameEnvironmentTest(unittest.TestCase):
|
||||
env=env, capture_output=True, text=True, check=True).stdout
|
||||
self.assertEqual(out, "continued\n", (verb, args, prefix))
|
||||
|
||||
def test_bionic_tool_starts_droiddeck_proton_when_proot_is_on(self):
|
||||
script = COMPAT["extra_wrapper_sh"]("proton")
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
tools = Path(tmp) / "compatibilitytools.d"
|
||||
|
||||
def tool(name, bionic=False):
|
||||
d = tools / name
|
||||
(d / "bionic").mkdir(parents=True)
|
||||
if bionic:
|
||||
(d / "bionic" / "launch.sh").write_text("")
|
||||
wrapper = d / "droiddeck-proton-wrap"
|
||||
wrapper.write_text(script if bionic else '#!/bin/sh\necho "ran ${0%/*}" "$@"\n')
|
||||
wrapper.chmod(0o755)
|
||||
return wrapper
|
||||
|
||||
bionic = tool("DroidDeck-Bionic-12.8-r37", bionic=True)
|
||||
tool("DroidDeck-Proton 11-12.8")
|
||||
tool("DroidDeck-Proton-11-12.10")
|
||||
tool("DroidDeck-Proton-12.8-bionic-test", bionic=True)
|
||||
tool("GE-Proton10-25")
|
||||
base = {"PATH": os.defpath, "HOME": "/nonexistent"}
|
||||
|
||||
def launch(extra=()):
|
||||
env = dict(base, **dict(extra))
|
||||
return subprocess.run([str(bionic), "waitforexitandrun", "/games/A B/game.exe", "-x"], env=env,
|
||||
capture_output=True, text=True, timeout=10)
|
||||
|
||||
result = launch()
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertEqual(result.stdout, "ran %s waitforexitandrun /games/A B/game.exe -x\n"
|
||||
% os.path.realpath(tools / "DroidDeck-Proton-11-12.10"))
|
||||
self.assertIn("this launch uses DroidDeck-Proton-11-12.10", result.stderr)
|
||||
|
||||
shutil.rmtree(tools / "DroidDeck-Proton-11-12.10")
|
||||
self.assertIn("ran %s " % os.path.realpath(tools / "DroidDeck-Proton 11-12.8"), launch().stdout)
|
||||
|
||||
self.assertNotIn("ran ", launch({"DDNATV_ROOT": "/data/rootfs"}).stdout)
|
||||
shutil.rmtree(tools / "DroidDeck-Proton 11-12.8")
|
||||
self.assertNotIn("this launch uses", launch().stderr)
|
||||
|
||||
def test_wrappers_preload_the_session_library_before_the_input_shim(self):
|
||||
overlay = "/root/.local/share/Steam/ubuntu12_64/gameoverlayrenderer.so"
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
|
||||
@@ -66,15 +66,6 @@ class DumpParsingTest(unittest.TestCase):
|
||||
def test_the_bottom_home_is_the_visible_home_on_another_display(self):
|
||||
self.assertEqual((2, "rip.moth.cocoonshell"), ab.bottom_home(ACTIVITIES, 0))
|
||||
|
||||
def test_android_13_activity_records_are_counted(self):
|
||||
self.assertEqual(1, ab.session_count(
|
||||
" * Hist #1: ActivityRecord{e1ec207 u0 com.droiddeck.launcher/.SessionActivity} t14519}\n"))
|
||||
|
||||
def test_the_visible_app_stands_in_when_no_home_is_on_the_other_display(self):
|
||||
dump = ("Display #4 (activities from top to bottom):\n"
|
||||
" * Task{21f60d6 #14493 type=standard A=10113:com.discord U=0 visible=true visibleRequested=true mode=fullscreen}\n")
|
||||
self.assertEqual((4, "com.discord"), ab.bottom_home(dump, 0))
|
||||
|
||||
def test_no_bottom_home_without_another_display(self):
|
||||
self.assertIsNone(ab.bottom_home(ACTIVITIES.split("\n\n")[1], 0))
|
||||
|
||||
@@ -89,25 +80,6 @@ class DumpParsingTest(unittest.TestCase):
|
||||
self.assertIsNone(ab.logical_size(DISPLAYS, 5))
|
||||
|
||||
|
||||
class HogScriptTest(unittest.TestCase):
|
||||
def test_both_modes_start_the_fill_counter(self):
|
||||
script = ab.HOG.splitlines()
|
||||
counter = next(n for n, line in enumerate(script) if line.startswith("i=0"))
|
||||
self.assertLess(counter, script.index('if [ "$mode" = burst ]; then'))
|
||||
self.assertLess(counter, next(n for n, line in enumerate(script) if line.startswith("while [ $i -lt 512 ]")))
|
||||
|
||||
|
||||
def test_a_failed_write_never_reports_released(self):
|
||||
script = ab.HOG.splitlines()
|
||||
check = script.index('[ "$failed" = 0 ] || { echo "write failed"; cleanup; exit 1; }')
|
||||
self.assertLess(check, script.index("echo released"))
|
||||
self.assertIn("failed=1", ab.HOG.split("echo released")[0])
|
||||
|
||||
def test_a_burst_takes_the_remainder_below_one_chunk(self):
|
||||
self.assertIn("rest=$((take % 256))", ab.HOG)
|
||||
self.assertIn('echo "nothing to take"', ab.HOG)
|
||||
|
||||
|
||||
class SummaryTest(unittest.TestCase):
|
||||
def test_max_adj_skips_samples_after_death(self):
|
||||
self.assertEqual(50, ab.max_adj(["0", "50", "DEAD", ""]))
|
||||
|
||||
@@ -27,13 +27,26 @@ def droiddeck_release(ver, prerelease=False, draft=False):
|
||||
|
||||
class ProtonExtraTest(unittest.TestCase):
|
||||
def test_sources_and_their_arm64_assets(self):
|
||||
self.assertEqual(list(EXTRA["SOURCES"]), ["ge", "cachyos", "droiddeck"])
|
||||
self.assertEqual(list(EXTRA["SOURCES"]), ["ge", "cachyos", "droiddeck", "bionic"])
|
||||
repo, pattern = EXTRA["SOURCES"]["droiddeck"]
|
||||
self.assertEqual(repo, "Droid-Deck/DroidDeck-Proton")
|
||||
self.assertTrue(pattern.search("DroidDeck-Proton-11-7.5-aarch64.tar.gz"))
|
||||
self.assertTrue(pattern.search("DroidDeck-Proton-11-8-aarch64.tar.xz"))
|
||||
self.assertFalse(pattern.search("DroidDeck-Proton-11-7.5-aarch64.sha512sum"))
|
||||
self.assertFalse(pattern.search("DroidDeck-Proton-11-7.5-aarch64.build-info.json"))
|
||||
self.assertFalse(pattern.search("DroidDeck-Bionic-12.8-r3-aarch64.tar.xz"))
|
||||
repo, pattern = EXTRA["SOURCES"]["bionic"]
|
||||
self.assertEqual(repo, "Droid-Deck/DroidDeck-Proton")
|
||||
self.assertTrue(pattern.search("DroidDeck-Bionic-12.8-r3-aarch64.tar.xz"))
|
||||
self.assertFalse(pattern.search("DroidDeck-Proton-11-7.5-aarch64.tar.gz"))
|
||||
|
||||
def test_bionic_takes_its_prerelease(self):
|
||||
stem = "DroidDeck-Bionic-12.8-r3-aarch64"
|
||||
releases = [{"tag_name": "DroidDeck-Bionic-12.8-r3", "prerelease": True, "draft": False,
|
||||
"assets": [asset(stem + ".sha512sum"), asset(stem + ".tar.xz")]}, droiddeck_release("11-7.5")]
|
||||
with mock.patch.dict(GLOBALS, {"fetch_json": lambda url: releases}):
|
||||
self.assertEqual(EXTRA["pick_asset"]("bionic")[0], "DroidDeck-Bionic-12.8-r3")
|
||||
self.assertEqual(EXTRA["pick_asset"]("droiddeck")[0], "DroidDeck-Proton-11-7.5")
|
||||
|
||||
def test_the_newest_full_release_with_its_sha512_file(self):
|
||||
releases = [droiddeck_release("11-8", prerelease=True), droiddeck_release("11-7.9", draft=True), droiddeck_release("11-7.5")]
|
||||
|
||||
@@ -234,66 +234,6 @@ class RockstarLaunch(unittest.TestCase):
|
||||
self.assertEqual('ready', result)
|
||||
self.assertEqual([False], stale)
|
||||
|
||||
def sdk_launch(self, root, runtimes, sdk_answer=None, ships_runtime=False, ident='gta5'):
|
||||
folder, sidecar, prefix, service, answer = self.setup_game(root)
|
||||
sidecar['id'] = ident
|
||||
(folder / 'title.rgl').write_bytes(b'RGLM' + bytes(108))
|
||||
if ships_runtime:
|
||||
(folder / 'socialclub.dll').write_bytes(b'game-runtime')
|
||||
answer['session'] = {'accountId': '123', 'identity': 'player@example.invalid', 'ticket': 'game-session'}
|
||||
requests, lines, states = [], [], list(runtimes)
|
||||
|
||||
def ask(channel, request, timeout):
|
||||
requests.append(request['op'])
|
||||
return sdk_answer if request['op'] == 'rockstar-sdk' else answer
|
||||
|
||||
with patch.object(store, 'ROCKSTAR_SERVICE', service), patch.object(store, 'rockstar_registry', return_value=True), \
|
||||
patch.object(store, 'rockstar_runtime', side_effect=lambda *args: states.pop(0)), \
|
||||
patch.object(store, 'log', lines.append):
|
||||
result = store.prepare_rockstar(folder, sidecar, str(prefix), str(Path(root) / 'channel'), ask_app=ask)
|
||||
return result, requests, lines, states
|
||||
|
||||
def test_a_title_without_a_social_club_installer_gets_one_from_the_app_before_its_session(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
result, requests, lines, states = self.sdk_launch(root, ['game-runtime', 'installed'], {'ok': True})
|
||||
self.assertEqual('ready', result)
|
||||
self.assertEqual(['rockstar-sdk', 'rockstar-launch'], requests)
|
||||
self.assertIn('rockstar runtime: installed', lines)
|
||||
self.assertEqual([], states)
|
||||
|
||||
def test_classic_sdk_titles_without_a_social_club_installer_also_get_one_from_the_app(self):
|
||||
for ident in ('gta4', 'lanoire'):
|
||||
with self.subTest(ident=ident), tempfile.TemporaryDirectory() as root:
|
||||
result, requests, lines, states = self.sdk_launch(root, ['game-runtime', 'installed'], {'ok': True}, ident=ident)
|
||||
self.assertEqual('ready', result)
|
||||
self.assertEqual(['rockstar-sdk', 'rockstar-launch'], requests)
|
||||
self.assertIn('rockstar runtime: installed', lines)
|
||||
self.assertEqual([], states)
|
||||
|
||||
def test_an_unavailable_social_club_installer_is_logged_and_the_launch_continues(self):
|
||||
for sdk_answer, reason in (({'ok': False, 'reason': 'no-launcher-build'}, 'sdk-no-launcher-build'), (None, 'sdk-timeout')):
|
||||
with self.subTest(reason=reason), tempfile.TemporaryDirectory() as root:
|
||||
result, requests, lines, _ = self.sdk_launch(root, ['game-runtime'], sdk_answer)
|
||||
self.assertEqual('ready', result)
|
||||
self.assertEqual(['rockstar-sdk', 'rockstar-launch'], requests)
|
||||
self.assertIn('rockstar runtime: ' + reason, lines)
|
||||
|
||||
def test_an_installed_or_bundled_social_club_does_not_ask_the_app(self):
|
||||
for runtimes, ships in ((['present'], False), (['installed'], False), (['game-runtime'], True)):
|
||||
with self.subTest(runtimes=runtimes, ships=ships), tempfile.TemporaryDirectory() as root:
|
||||
result, requests, lines, _ = self.sdk_launch(root, runtimes, ships_runtime=ships)
|
||||
self.assertEqual('ready', result)
|
||||
self.assertEqual(['rockstar-launch'], requests)
|
||||
self.assertIn('rockstar runtime: ' + runtimes[0], lines)
|
||||
|
||||
def test_classic_titles_without_the_sdk_never_ask_for_the_social_club_installer(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
with patch.object(store, 'rockstar_runtime') as runtime:
|
||||
result, _, requests = self.prepare(root)
|
||||
self.assertEqual('ready', result)
|
||||
self.assertEqual(['rockstar-launch'], [request['op'] for request in requests])
|
||||
runtime.assert_not_called()
|
||||
|
||||
def exit_game(self, root, store_id, log_text=None, link=None):
|
||||
folder = game(root, store_id=store_id, ident='gta5')
|
||||
prefix = Path(root) / 'prefix'
|
||||
|
||||
@@ -1,89 +0,0 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
PRELOAD = Path(__file__).resolve().parents[1] / "linuxfs/preload"
|
||||
|
||||
PROGRAM = r"""
|
||||
#define _GNU_SOURCE
|
||||
#include <dlfcn.h>
|
||||
#include <fcntl.h>
|
||||
#include <linux/netlink.h>
|
||||
#include <poll.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <sys/socket.h>
|
||||
#include <unistd.h>
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
unsigned groups = argc > 1 ? (unsigned)atoi(argv[1]) : 2;
|
||||
int fd = socket(AF_NETLINK, SOCK_RAW | SOCK_CLOEXEC | SOCK_NONBLOCK, NETLINK_KOBJECT_UEVENT);
|
||||
if (fd < 0) { printf("socket failed\n"); return 2; }
|
||||
struct sockaddr_nl nl = {.nl_family = AF_NETLINK, .nl_groups = groups};
|
||||
printf("bind %d\n", bind(fd, (struct sockaddr *)&nl, sizeof(nl)));
|
||||
printf("cloexec %d nonblock %d\n", (fcntl(fd, F_GETFD) & FD_CLOEXEC) != 0, (fcntl(fd, F_GETFL) & O_NONBLOCK) != 0);
|
||||
int (*inject)(const char *, const char *, const char *, const char *, unsigned, unsigned) =
|
||||
(int (*)(const char *, const char *, const char *, const char *, unsigned, unsigned))dlsym(RTLD_DEFAULT, "dd_udevmon_inject");
|
||||
int sent = inject("add", "/devices/droiddeck/usb4/4-1:1.3/0003:054C:09CC.0005/hidraw/hidraw20", "hidraw",
|
||||
"/dev/hidraw20", 245, 20);
|
||||
printf("sent %d\n", sent);
|
||||
struct pollfd p = {.fd = fd, .events = POLLIN};
|
||||
if (sent > 0 && poll(&p, 1, 1000) == 1) {
|
||||
char buf[2048];
|
||||
struct sockaddr_nl from;
|
||||
struct iovec iov = {.iov_base = buf, .iov_len = sizeof(buf)};
|
||||
struct msghdr msg = {.msg_name = &from, .msg_namelen = sizeof(from), .msg_iov = &iov, .msg_iovlen = 1};
|
||||
ssize_t n = recvmsg(fd, &msg, 0);
|
||||
int found = 0;
|
||||
for (ssize_t i = 0; n > 0 && i < n; i += (ssize_t)strlen(buf + i) + 1)
|
||||
if (!strcmp(buf + i, "ACTION=add") || !strcmp(buf + i, "DEVNAME=/dev/hidraw20")) found++;
|
||||
printf("received %s fields %d\n", n > 0 && !memcmp(buf, "libudev", 8) ? "libudev" : "nothing", found);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
@unittest.skipUnless(shutil.which("gcc") and os.uname().machine == "x86_64", "needs gcc on an x86-64 host")
|
||||
class UdevMonitorPreloadTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.tmp = Path(tempfile.mkdtemp())
|
||||
cls.library = cls.tmp / "libudevmon.so"
|
||||
subprocess.run(["gcc", "-shared", "-fPIC", "-O2", "-Wall", "-Wextra", "-Werror", "-DUDEVMON_TEST", "-DBINFMT_TEST",
|
||||
'-DBINFMT_HANDLER="/bin/false"', "-o", str(cls.library), "-pthread"]
|
||||
+ [str(PRELOAD / name) for name in ("binfmt.c", "net.c", "udevmon.c", "pathcache.c", "perms.c", "webhelper.c")]
|
||||
+ [str(Path(__file__).with_name("netlink_stubs.c")), "-ldl"], check=True)
|
||||
source = cls.tmp / "program.c"
|
||||
source.write_text(PROGRAM.replace("#include <unistd.h>", "#include <unistd.h>\n#include <stdlib.h>"))
|
||||
cls.program = cls.tmp / "program"
|
||||
subprocess.run(["gcc", "-O2", "-o", str(cls.program), str(source), "-ldl"], check=True)
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
shutil.rmtree(cls.tmp, True)
|
||||
|
||||
def run_program(self, *args, refuse=False):
|
||||
env = dict(os.environ, LD_PRELOAD=str(self.library))
|
||||
env.pop("DD_UDEVMON_REFUSE", None)
|
||||
if refuse:
|
||||
env["DD_UDEVMON_REFUSE"] = "1"
|
||||
return subprocess.run([str(self.program), *args], env=env, capture_output=True, text=True, check=True).stdout.splitlines()
|
||||
|
||||
def test_a_monitor_the_system_will_not_subscribe_hears_the_sessions_events(self):
|
||||
out = self.run_program(refuse=True)
|
||||
self.assertEqual(["bind 0", "cloexec 1 nonblock 1", "sent 1", "received libudev fields 2"], out)
|
||||
|
||||
def test_a_monitor_the_system_subscribes_stays_on_the_real_socket(self):
|
||||
self.assertEqual(["bind 0", "cloexec 1 nonblock 1", "sent 0"], self.run_program())
|
||||
|
||||
def test_a_monitor_bound_without_groups_hears_the_sessions_events(self):
|
||||
out = self.run_program("0")
|
||||
self.assertEqual(["bind 0", "cloexec 1 nonblock 1", "sent 1", "received libudev fields 2"], out)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user