mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-12-05 20:45:43 +00:00
Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
49381484dd | ||
|
|
f17d3ddaad | ||
|
|
2aae4b2284 | ||
|
|
dca443e3aa |
No files matched your search
@@ -0,0 +1,35 @@
|
|||||||
|
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'
|
||||||
|
- 'tools/gpuload/**'
|
||||||
|
- '.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/*
|
||||||
@@ -70,7 +70,7 @@ DroidDeck is [GPL-3.0](LICENSE). Steam and Proton belong to Valve Corporation. V
|
|||||||
|
|
||||||
- Runtime, shim, input and controller work build on WinNative and Bannerlator by maxjivi05.
|
- Runtime, shim, input and controller work build on WinNative and Bannerlator by maxjivi05.
|
||||||
- mmap ring buffer controller input by ribbit384 ([WinNative #345](https://github.com/WinNative-Emu/WinNative/pull/345)).
|
- mmap ring buffer controller input by ribbit384 ([WinNative #345](https://github.com/WinNative-Emu/WinNative/pull/345)).
|
||||||
- [FEX](https://github.com/FEX-Emu/FEX) (MIT) runs x86 code. DroidDeck's build puts the platform name under `AT_PLATFORM` so [sharun](https://github.com/VHSgunzo/sharun) AppImages by VHSgunzo (MIT) start through its [userland-execve](https://crates.io/crates/userland-execve) loader (MIT), and its GL thunk hands X errors to the program's own error handler. FEX's code disk cache was checked in its source. The fix for host stack left behind when a program leaves a signal handler without returning follows the approach suggested in [FEX-Emu/FEX#2487](https://github.com/FEX-Emu/FEX/issues/2487). The host stack fix for system calls that end a block is a backport of Ryan Houdek's [FEX-Emu/FEX#6122](https://github.com/FEX-Emu/FEX/pull/6122).
|
- [FEX](https://github.com/FEX-Emu/FEX) (MIT) runs x86 code. DroidDeck's build puts the platform name under `AT_PLATFORM` so [sharun](https://github.com/VHSgunzo/sharun) AppImages by VHSgunzo (MIT) start through its [userland-execve](https://crates.io/crates/userland-execve) loader (MIT), and its GL thunk hands X errors to the program's own error handler. FEX's code disk cache was checked in its source.
|
||||||
- x86 AppImages, and arm64 ones whose runtime can't unpack on Android, are unpacked with [uruntime](https://github.com/VHSgunzo/uruntime) by VHSgunzo (MIT), shipped unmodified with its licence.
|
- x86 AppImages, and arm64 ones whose runtime can't unpack on Android, are unpacked with [uruntime](https://github.com/VHSgunzo/uruntime) by VHSgunzo (MIT), shipped unmodified with its licence.
|
||||||
- x86 programs linking OpenSSL 3 use the copy in the [Steam Linux Runtime 4.0](https://gitlab.steamos.cloud/steamrt/steamrt). x86 Linux games get the `/etc/asound.conf` that [pressure-vessel](https://gitlab.steamos.cloud/steamrt/steam-runtime-tools) writes.
|
- x86 programs linking OpenSSL 3 use the copy in the [Steam Linux Runtime 4.0](https://gitlab.steamos.cloud/steamrt/steamrt). x86 Linux games get the `/etc/asound.conf` that [pressure-vessel](https://gitlab.steamos.cloud/steamrt/steam-runtime-tools) writes.
|
||||||
- `WriteProcessMemory` hooks fall back to `/proc/<pid>/mem` the way [Wine](https://gitlab.winehq.org/wine/wine)'s `server/ptrace.c` did before Wine 11.
|
- `WriteProcessMemory` hooks fall back to `/proc/<pid>/mem` the way [Wine](https://gitlab.winehq.org/wine/wine)'s `server/ptrace.c` did before Wine 11.
|
||||||
|
|||||||
@@ -15,7 +15,6 @@ private fun Launcher(tab: String, games: List<com.droiddeck.launcher.frontend.Li
|
|||||||
PreviewHost { FrontEndScreen(sampleState(games = games, navigate = tab, ready = ready), sampleActions) }
|
PreviewHost { FrontEndScreen(sampleState(games = games, navigate = tab, ready = ready), sampleActions) }
|
||||||
|
|
||||||
@DroidDeckPreviews @Composable private fun SteamTabPreview() = Launcher("steam")
|
@DroidDeckPreviews @Composable private fun SteamTabPreview() = Launcher("steam")
|
||||||
@DroidDeckPreviews @Composable private fun SteamEmptyPreview() = Launcher("steam", games = emptyList())
|
|
||||||
@DroidDeckPreviews @Composable private fun LibraryPreview() = Launcher("games")
|
@DroidDeckPreviews @Composable private fun LibraryPreview() = Launcher("games")
|
||||||
@DroidDeckPreviews @Composable private fun LibraryEmptyPreview() = Launcher("games", games = emptyList())
|
@DroidDeckPreviews @Composable private fun LibraryEmptyPreview() = Launcher("games", games = emptyList())
|
||||||
@DroidDeckPreviews @Composable private fun StoresPreview() = Launcher("stores")
|
@DroidDeckPreviews @Composable private fun StoresPreview() = Launcher("stores")
|
||||||
|
|||||||
@@ -205,6 +205,11 @@ static void controller_fork_prepare();
|
|||||||
static void controller_fork_parent();
|
static void controller_fork_parent();
|
||||||
static void controller_fork_child();
|
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 {
|
struct FakeConfig {
|
||||||
const char *hook_dir;
|
const char *hook_dir;
|
||||||
const char *udev_data_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
|
// 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.
|
// reentry on the initializing thread gets them while other threads wait for the fork handlers.
|
||||||
static FakeConfig &config() {
|
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 FakeConfig cfg;
|
||||||
static std::atomic<int> state{0};
|
static std::atomic<int> state{0};
|
||||||
static __thread bool initializing __attribute__((tls_model("initial-exec")));
|
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() {
|
__attribute__((visibility("hidden"))) static void load_ring_paths() {
|
||||||
std::lock_guard<std::recursive_mutex> guard(controller_mutex());
|
std::lock_guard<std::recursive_mutex> guard(controller_mutex());
|
||||||
if (ring_paths_loaded)
|
if (ring_paths_loaded || !env_ready())
|
||||||
return;
|
return;
|
||||||
|
|
||||||
const char *spec = getenv("FAKE_EVDEV_MEMFD_PATHS");
|
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() {
|
__attribute__((visibility("hidden"))) static bool presents_steam_virtual() {
|
||||||
static int known;
|
static int known;
|
||||||
if (known == 0) {
|
if (known == 0) {
|
||||||
|
if (!env_ready()) return false;
|
||||||
const char *enabled = getenv("FAKE_EVDEV_STEAM_VIRTUAL");
|
const char *enabled = getenv("FAKE_EVDEV_STEAM_VIRTUAL");
|
||||||
known = enabled && atoi(enabled) && !is_steam_client() ? 1 : -1;
|
known = enabled && atoi(enabled) && !is_steam_client() ? 1 : -1;
|
||||||
}
|
}
|
||||||
return known == 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
|
__attribute__((visibility("hidden"))) static bool
|
||||||
presents_xbox_triggers(const FakeController &fake) {
|
presents_xbox_triggers(const FakeController &fake) {
|
||||||
return fake.uinput || !is_steam_client();
|
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 bool fake_deck_enabled() {
|
||||||
static int enabled = -1;
|
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;
|
if (enabled < 0) enabled = getenv("FAKE_EVDEV_DECK") && atoi(getenv("FAKE_EVDEV_DECK")) ? 1 : 0;
|
||||||
return enabled == 1;
|
return enabled == 1;
|
||||||
}
|
}
|
||||||
@@ -1398,6 +1421,7 @@ static bool fake_deck_enabled() {
|
|||||||
__attribute__((visibility("hidden"))) static uint32_t session_pad_type() {
|
__attribute__((visibility("hidden"))) static uint32_t session_pad_type() {
|
||||||
static int type = -1;
|
static int type = -1;
|
||||||
if (type < 0) {
|
if (type < 0) {
|
||||||
|
if (!env_ready()) return PAD_TYPE_DECK;
|
||||||
const char *env = getenv("FAKE_EVDEV_PAD_TYPE");
|
const char *env = getenv("FAKE_EVDEV_PAD_TYPE");
|
||||||
type = env && !strcmp(env, "steamcontroller") ? PAD_TYPE_STEAM
|
type = env && !strcmp(env, "steamcontroller") ? PAD_TYPE_STEAM
|
||||||
: env && !strcmp(env, "xbox360") ? PAD_TYPE_XBOX
|
: 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 bool fake_triton_enabled() {
|
||||||
static int enabled = -1;
|
static int enabled = -1;
|
||||||
|
if (enabled < 0 && !env_ready()) return false;
|
||||||
if (enabled < 0)
|
if (enabled < 0)
|
||||||
enabled = fake_deck_enabled() && getenv("FAKE_EVDEV_TRITON") && atoi(getenv("FAKE_EVDEV_TRITON")) ? 1 : 0;
|
enabled = fake_deck_enabled() && getenv("FAKE_EVDEV_TRITON") && atoi(getenv("FAKE_EVDEV_TRITON")) ? 1 : 0;
|
||||||
return enabled == 1;
|
return enabled == 1;
|
||||||
@@ -2091,6 +2116,7 @@ static_assert(sizeof(TouchRingFile) <= TOUCH_RING_SIZE, "TouchRingFile layout");
|
|||||||
|
|
||||||
__attribute__((visibility("hidden"))) static TouchRingFile *touch_ring() {
|
__attribute__((visibility("hidden"))) static TouchRingFile *touch_ring() {
|
||||||
static TouchRingFile *ring = nullptr;
|
static TouchRingFile *ring = nullptr;
|
||||||
|
if (!env_ready()) return nullptr;
|
||||||
static std::once_flag once;
|
static std::once_flag once;
|
||||||
std::call_once(once, [] {
|
std::call_once(once, [] {
|
||||||
const char *path = getenv("FAKE_TOUCHCTL_RING");
|
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;
|
static constexpr long SYSFS_FS_MAGIC = 0x62656572;
|
||||||
|
|
||||||
__attribute__((visibility("hidden"))) static const char *deck_listing_dir() {
|
__attribute__((visibility("hidden"))) static const char *deck_listing_dir() {
|
||||||
|
if (!env_ready()) return nullptr;
|
||||||
static const char *dir = getenv("FAKE_DECK_SYSFS_LISTING");
|
static const char *dir = getenv("FAKE_DECK_SYSFS_LISTING");
|
||||||
return dir && *dir ? dir : nullptr;
|
return dir && *dir ? dir : nullptr;
|
||||||
}
|
}
|
||||||
@@ -3689,6 +3716,10 @@ EXPORT int ioctl(int fd, ioctl_request_t op, ...) {
|
|||||||
id.bustype = 0x03;
|
id.bustype = 0x03;
|
||||||
if (made) {
|
if (made) {
|
||||||
id = made->id;
|
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()) {
|
} else if (presents_steam_virtual()) {
|
||||||
id.vendor = STEAM_VIRTUAL_VENDOR_ID;
|
id.vendor = STEAM_VIRTUAL_VENDOR_ID;
|
||||||
id.product = STEAM_VIRTUAL_PRODUCT_ID;
|
id.product = STEAM_VIRTUAL_PRODUCT_ID;
|
||||||
|
|||||||
@@ -187,7 +187,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
|||||||
private var gpuClockPin by mutableStateOf(false)
|
private var gpuClockPin by mutableStateOf(false)
|
||||||
private var prootNoSeccomp by mutableStateOf(false)
|
private var prootNoSeccomp by mutableStateOf(false)
|
||||||
private var prootFastPath by mutableStateOf(true)
|
private var prootFastPath by mutableStateOf(true)
|
||||||
private var nativeUserland by mutableStateOf(true)
|
private var nativeUserland by mutableStateOf(false)
|
||||||
private var cursorComposite by mutableStateOf(false)
|
private var cursorComposite by mutableStateOf(false)
|
||||||
private var guestHostname by mutableStateOf(SessionPrefs.DEFAULT_GUEST_HOSTNAME)
|
private var guestHostname by mutableStateOf(SessionPrefs.DEFAULT_GUEST_HOSTNAME)
|
||||||
private var phantomWarning by mutableStateOf<String?>(null)
|
private var phantomWarning by mutableStateOf<String?>(null)
|
||||||
@@ -1531,7 +1531,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
|||||||
onAddonImport = { sg, target -> importAddons(sg.name, target) },
|
onAddonImport = { sg, target -> importAddons(sg.name, target) },
|
||||||
onAddonDelete = { target, name ->
|
onAddonDelete = { target, name ->
|
||||||
saveAction(getString(R.string.main_addons_deleting, name)) {
|
saveAction(getString(R.string.main_addons_deleting, name)) {
|
||||||
com.droiddeck.launcher.ui.deleteAddon(this, target, name)
|
com.droiddeck.launcher.runtime.WowAddons.delete(target, name)
|
||||||
getString(R.string.main_addons_deleted, name)
|
getString(R.string.main_addons_deleted, name)
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -149,7 +149,7 @@ internal class ProtonMenu(
|
|||||||
|
|
||||||
fun refreshProtons() {
|
fun refreshProtons() {
|
||||||
refreshExperimental()
|
refreshExperimental()
|
||||||
protonRows = ProtonExtras.tools.map {
|
protonRows = ProtonExtras.offered(activity).map {
|
||||||
val all = ProtonExtras.installedAll(activity, it)
|
val all = ProtonExtras.installedAll(activity, it)
|
||||||
ProtonRow(it.id, it.name, all.lastOrNull(), ProtonExtras.queued(activity, it), all, ProtonExtras.update(activity, it))
|
ProtonRow(it.id, it.name, all.lastOrNull(), ProtonExtras.queued(activity, it), all, ProtonExtras.update(activity, it))
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2846,17 +2846,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
|||||||
if (!SessionState.running) {
|
if (!SessionState.running) {
|
||||||
SessionEvents.transition(SessionPhase.STARTING_COMPOSITOR, "compositor.starting")
|
SessionEvents.transition(SessionPhase.STARTING_COMPOSITOR, "compositor.starting")
|
||||||
}
|
}
|
||||||
val runtimeDir = File(filesDir, ".wayland-rt").apply { mkdirs() }
|
val output = CompositorHost.prepare(this)
|
||||||
FileUtils.copyAsset(this, "wayland/keymap.xkb", File(runtimeDir, "keymap.xkb"))
|
|
||||||
com.droiddeck.launcher.input.VrControllers.publish(this)
|
|
||||||
|
|
||||||
val turnip = TurnipDriver(this)
|
|
||||||
com.droiddeck.launcher.gpu.DriverSetupLog.write(this, "surface.driver-setup")
|
|
||||||
if (!CompositorHost.isStarted) {
|
|
||||||
CompositorHost.displayChoice = SessionPrefs.androidDriver(this)
|
|
||||||
com.droiddeck.launcher.gpu.AutoDriverTrial.displayStarting(this, SessionPrefs.androidDriver(this))
|
|
||||||
}
|
|
||||||
val driverId = if (CompositorHost.isStarted) null else turnip.install()
|
|
||||||
|
|
||||||
val previous = SessionState.outputSize
|
val previous = SessionState.outputSize
|
||||||
val live = windowOutputSize(holder.surfaceFrame.width(), holder.surfaceFrame.height())
|
val live = windowOutputSize(holder.surfaceFrame.width(), holder.surfaceFrame.height())
|
||||||
@@ -2883,15 +2873,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
|||||||
pushCardboard(activeCardboard)
|
pushCardboard(activeCardboard)
|
||||||
WaylandCompositor.nativeSetCardboardPoseFile(File(filesDir, ".wayland-rt/droiddeck-headpose").path)
|
WaylandCompositor.nativeSetCardboardPoseFile(File(filesDir, ".wayland-rt/droiddeck-headpose").path)
|
||||||
com.droiddeck.launcher.glasses.SpatialTracking.attachPublisher(File(filesDir, ".wayland-rt/droiddeck-spatialpose").path)
|
com.droiddeck.launcher.glasses.SpatialTracking.attachPublisher(File(filesDir, ".wayland-rt/droiddeck-spatialpose").path)
|
||||||
if (!SessionState.running) {
|
if (!SessionState.running) CompositorHost.logToSession(this)
|
||||||
val waylandLog = File(SessionPaths.beginOrCurrent(this), "wayland.log")
|
|
||||||
WaylandCompositor.setSessionLogFile(waylandLog)
|
|
||||||
try {
|
|
||||||
android.system.Os.setenv("DD_WAYLAND_LOG", waylandLog.path, true)
|
|
||||||
} catch (e: Exception) {
|
|
||||||
Log.w(TAG, "could not point the compositor's log at $waylandLog", e)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
val mode = hdrPrefMode()
|
val mode = hdrPrefMode()
|
||||||
if (probe != null) {
|
if (probe != null) {
|
||||||
WaylandCompositor.nativeSetHdrDisplay(
|
WaylandCompositor.nativeSetHdrDisplay(
|
||||||
@@ -2911,19 +2893,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
|||||||
)
|
)
|
||||||
Log.i(TAG, "hdr: " + (if (tonemap) "tone-mapped (${probe.reason})" else if (capable) "available" else "unavailable") + " · display ${probe.formats.ifEmpty { "SDR" }}")
|
Log.i(TAG, "hdr: " + (if (tonemap) "tone-mapped (${probe.reason})" else if (capable) "available" else "unavailable") + " · display ${probe.formats.ifEmpty { "SDR" }}")
|
||||||
}
|
}
|
||||||
if (!SessionState.running) {
|
if (!SessionState.running) CompositorHost.applyHdr(this, mode)
|
||||||
val on = SessionState.hdrCapable && SessionPrefs.hdr(this, mode)
|
CompositorHost.start(this, output, holder.surface, size, refreshHz(holder), outputFpsLimit())
|
||||||
SessionState.hdr = on
|
|
||||||
WaylandCompositor.nativeSetHdrOutput(on)
|
|
||||||
WaylandCompositor.nativeSetZeroCopy(on || SessionPrefs.zeroCopy(this, mode))
|
|
||||||
Log.i(TAG, "hdr: " + (if (on) "on" else "off") + " for this $mode session")
|
|
||||||
}
|
|
||||||
com.droiddeck.launcher.gpu.DriverSetupLog.write(this, "compositor.start driver=$driverId")
|
|
||||||
CompositorHost.startOrAttach(
|
|
||||||
this, holder.surface, runtimeDir.path,
|
|
||||||
driverId?.let { turnip.driverPath(it) }, driverId?.let { turnip.libraryName(it) },
|
|
||||||
applicationInfo.nativeLibraryDir, size.first, size.second, refreshHz(holder), outputFpsLimit(),
|
|
||||||
)
|
|
||||||
onOutputAttached(holder)
|
onOutputAttached(holder)
|
||||||
if (SessionState.running && size != previous) {
|
if (SessionState.running && size != previous) {
|
||||||
Log.i(TAG, "output resized: ${previous.first}x${previous.second} -> ${size.first}x${size.second} on a new surface")
|
Log.i(TAG, "output resized: ${previous.first}x${previous.second} -> ${size.first}x${size.second} on a new surface")
|
||||||
|
|||||||
@@ -36,8 +36,6 @@ class SteamControllerBle(private val context: Context, router: InputRouter? = nu
|
|||||||
private var lizardOffSent = false
|
private var lizardOffSent = false
|
||||||
private var reportedNone = false
|
private var reportedNone = false
|
||||||
private var discoveries = 0
|
private var discoveries = 0
|
||||||
private var subscribed = false
|
|
||||||
private var linkChecks = 0
|
|
||||||
private var outputSequence = 0L
|
private var outputSequence = 0L
|
||||||
private var outputWritePending = false
|
private var outputWritePending = false
|
||||||
private var featureRead = 0L
|
private var featureRead = 0L
|
||||||
@@ -96,7 +94,7 @@ class SteamControllerBle(private val context: Context, router: InputRouter? = nu
|
|||||||
}
|
}
|
||||||
val adapter = (context.getSystemService(Context.BLUETOOTH_SERVICE) as? BluetoothManager)?.adapter
|
val adapter = (context.getSystemService(Context.BLUETOOTH_SERVICE) as? BluetoothManager)?.adapter
|
||||||
val bonded = runCatching { adapter?.takeIf(BluetoothAdapter::isEnabled)?.bondedDevices }
|
val bonded = runCatching { adapter?.takeIf(BluetoothAdapter::isEnabled)?.bondedDevices }
|
||||||
.onFailure { if (!reportedNone) Log.w(TAG, "paired devices unreadable", it) }
|
.onFailure { Log.w(TAG, "paired devices unreadable", it) }
|
||||||
.getOrNull()
|
.getOrNull()
|
||||||
val device = bonded?.firstOrNull(::isSteamController)
|
val device = bonded?.firstOrNull(::isSteamController)
|
||||||
if (device == null) {
|
if (device == null) {
|
||||||
@@ -116,8 +114,6 @@ class SteamControllerBle(private val context: Context, router: InputRouter? = nu
|
|||||||
val g = gatt ?: return
|
val g = gatt ?: return
|
||||||
gatt = null
|
gatt = null
|
||||||
discoveries = 0
|
discoveries = 0
|
||||||
subscribed = false
|
|
||||||
linkChecks = 0
|
|
||||||
input = null
|
input = null
|
||||||
lizardOffSent = false
|
lizardOffSent = false
|
||||||
outputWritePending = false
|
outputWritePending = false
|
||||||
@@ -166,18 +162,26 @@ class SteamControllerBle(private val context: Context, router: InputRouter? = nu
|
|||||||
}
|
}
|
||||||
|
|
||||||
override fun onDescriptorWrite(g: BluetoothGatt, descriptor: BluetoothGattDescriptor, status: Int) {
|
override fun onDescriptorWrite(g: BluetoothGatt, descriptor: BluetoothGattDescriptor, status: Int) {
|
||||||
if (g !== gatt || descriptor.characteristic.uuid != input) return
|
withSlot {
|
||||||
if (status == BluetoothGatt.GATT_SUCCESS) onSubscribed("status $status")
|
if (g !== gatt || descriptor.characteristic.uuid != input) return
|
||||||
else Log.w(TAG, "report 0x%02x subscription failed (status %d)".format(reportId, status))
|
Log.i(TAG, "subscribed to report 0x%02x (status %d)".format(reportId, status))
|
||||||
|
connected = status == BluetoothGatt.GATT_SUCCESS
|
||||||
|
FakeInputWriter.setTritonConnected(SLOT, connected)
|
||||||
|
}
|
||||||
|
listener?.invoke()
|
||||||
|
if (connected) {
|
||||||
|
refreshLizardMode()
|
||||||
|
pollOutput()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onCharacteristicWrite(g: BluetoothGatt, characteristic: BluetoothGattCharacteristic, status: Int) {
|
override fun onCharacteristicWrite(g: BluetoothGatt, characteristic: BluetoothGattCharacteristic, status: Int) {
|
||||||
if (g !== gatt) return
|
if (g !== gatt) return
|
||||||
if (status != BluetoothGatt.GATT_SUCCESS) {
|
if (characteristic.uuid == REPORT && !lizardOffSent) {
|
||||||
Log.w(TAG, "output report write failed for ${characteristic.uuid} (status $status)")
|
|
||||||
} else if (characteristic.uuid == REPORT && !lizardOffSent) {
|
|
||||||
lizardOffSent = true
|
lizardOffSent = true
|
||||||
Log.i(TAG, "lizard mode off")
|
Log.i(TAG, "lizard mode off (status $status)")
|
||||||
|
} else if (status != BluetoothGatt.GATT_SUCCESS) {
|
||||||
|
Log.w(TAG, "output report write failed for ${characteristic.uuid} (status $status)")
|
||||||
}
|
}
|
||||||
outputWritePending = false
|
outputWritePending = false
|
||||||
writeNextOutput()
|
writeNextOutput()
|
||||||
@@ -237,40 +241,11 @@ class SteamControllerBle(private val context: Context, router: InputRouter? = nu
|
|||||||
Log.i(TAG, "found Triton haptic reports: ${outputReports.keys.sorted().joinToString { "0x%02x".format(it) }}")
|
Log.i(TAG, "found Triton haptic reports: ${outputReports.keys.sorted().joinToString { "0x%02x".format(it) }}")
|
||||||
input = chr.uuid
|
input = chr.uuid
|
||||||
g.setCharacteristicNotification(chr, true)
|
g.setCharacteristicNotification(chr, true)
|
||||||
watchLink(g, chr)
|
val cccd = chr.getDescriptor(CCCD) ?: return disconnect("state report cannot notify")
|
||||||
}
|
@Suppress("DEPRECATION")
|
||||||
|
cccd.value = BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE
|
||||||
private fun watchLink(g: BluetoothGatt, chr: BluetoothGattCharacteristic) {
|
@Suppress("DEPRECATION")
|
||||||
if (g !== gatt || lizardOffSent) return
|
g.writeDescriptor(cccd)
|
||||||
if (linkChecks++ == LINK_CHECKS) {
|
|
||||||
disconnect(if (subscribed) "lizard mode off never acknowledged" else "report 0x%02x never subscribed".format(reportId))
|
|
||||||
if (running) handler.postDelayed(::connect, RETRY_MS)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if (!subscribed) {
|
|
||||||
val cccd = chr.getDescriptor(CCCD) ?: return disconnect("state report cannot notify")
|
|
||||||
@Suppress("DEPRECATION")
|
|
||||||
cccd.value = BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE
|
|
||||||
@Suppress("DEPRECATION")
|
|
||||||
if (!g.writeDescriptor(cccd)) Log.w(TAG, "report 0x%02x subscription refused (attempt %d)".format(reportId, linkChecks))
|
|
||||||
}
|
|
||||||
handler.postDelayed({ watchLink(g, chr) }, LINK_CHECK_MS)
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun onSubscribed(how: String) {
|
|
||||||
var fresh = false
|
|
||||||
withSlot {
|
|
||||||
if (subscribed || gatt == null) return@withSlot
|
|
||||||
subscribed = true
|
|
||||||
fresh = true
|
|
||||||
Log.i(TAG, "subscribed to report 0x%02x (%s)".format(reportId, how))
|
|
||||||
connected = true
|
|
||||||
FakeInputWriter.setTritonConnected(SLOT, true)
|
|
||||||
}
|
|
||||||
if (!fresh) return
|
|
||||||
listener?.invoke()
|
|
||||||
refreshLizardMode()
|
|
||||||
pollOutput()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun refreshCache(g: BluetoothGatt) {
|
private fun refreshCache(g: BluetoothGatt) {
|
||||||
@@ -286,14 +261,11 @@ class SteamControllerBle(private val context: Context, router: InputRouter? = nu
|
|||||||
handler.postDelayed(::refreshLizardMode, LIZARD_REFRESH_MS)
|
handler.postDelayed(::refreshLizardMode, LIZARD_REFRESH_MS)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun onState(data: ByteArray) {
|
private fun onState(data: ByteArray) = withSlot {
|
||||||
withSlot {
|
if (data.size < STATE_BYTES) return@withSlot
|
||||||
if (data.size < STATE_BYTES) return
|
val timing = InputTiming.begin()
|
||||||
val timing = InputTiming.begin()
|
FakeInputWriter.writeTritonState(SLOT, reportId, routedInput?.route(data) ?: data)
|
||||||
FakeInputWriter.writeTritonState(SLOT, reportId, routedInput?.route(data) ?: data)
|
InputTiming.end(timing)
|
||||||
InputTiming.end(timing)
|
|
||||||
}
|
|
||||||
if (!subscribed) onSubscribed("input before the subscription reply")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun release() = synchronized(inputLock) {
|
private fun release() = synchronized(inputLock) {
|
||||||
@@ -385,8 +357,6 @@ class SteamControllerBle(private val context: Context, router: InputRouter? = nu
|
|||||||
private const val SLOT = 0
|
private const val SLOT = 0
|
||||||
private const val RETRY_MS = 5_000L
|
private const val RETRY_MS = 5_000L
|
||||||
private const val LIZARD_REFRESH_MS = 3_000L
|
private const val LIZARD_REFRESH_MS = 3_000L
|
||||||
private const val LINK_CHECK_MS = 1_000L
|
|
||||||
private const val LINK_CHECKS = 3
|
|
||||||
private const val OUTPUT_POLL_MS = 4L
|
private const val OUTPUT_POLL_MS = 4L
|
||||||
private const val OUTPUT_RETRY_MS = 10L
|
private const val OUTPUT_RETRY_MS = 10L
|
||||||
private const val FEATURE_BYTES = 62
|
private const val FEATURE_BYTES = 62
|
||||||
|
|||||||
@@ -1,33 +1,25 @@
|
|||||||
package com.droiddeck.launcher.runtime
|
package com.droiddeck.launcher.runtime
|
||||||
|
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
import com.droiddeck.launcher.stores.battlenet.BattleNetInstall
|
import com.droiddeck.launcher.agent.AgentException
|
||||||
|
import com.droiddeck.launcher.agent.AgentGuest
|
||||||
import org.json.JSONArray
|
import org.json.JSONArray
|
||||||
import org.json.JSONObject
|
import org.json.JSONObject
|
||||||
import java.io.File
|
|
||||||
import java.time.Instant
|
import java.time.Instant
|
||||||
import java.util.concurrent.ConcurrentHashMap
|
|
||||||
import java.util.concurrent.LinkedBlockingQueue
|
|
||||||
import java.util.concurrent.TimeUnit
|
|
||||||
import java.util.concurrent.atomic.AtomicBoolean
|
|
||||||
|
|
||||||
object CurseForgeApp {
|
object CurseForgeApp {
|
||||||
const val NAME = "CurseForge"
|
const val NAME = "CurseForge"
|
||||||
const val FEED = "https://curseforge.overwolf.com/electron/linux/latest-linux.yml"
|
const val FEED = "https://curseforge.overwolf.com/electron/linux/latest-linux.yml"
|
||||||
internal const val WOW = 1
|
internal const val WOW = 1
|
||||||
const val HELPER = "/usr/local/bin/droiddeck-curseforge"
|
const val HELPER = "/usr/local/bin/droiddeck-curseforge"
|
||||||
internal const val AGENT = "/usr/local/bin/droiddeck-agent"
|
|
||||||
private const val READY_MS = 120_000L
|
private const val READY_MS = 120_000L
|
||||||
private const val INSTALL_MS = 300_000L
|
private const val INSTALL_MS = 300_000L
|
||||||
private const val OUT_OF_DATE = 2
|
|
||||||
|
|
||||||
enum class Start { READY, BUSY, FAILED }
|
enum class Start { READY, BUSY, NO_DISPLAY, FAILED }
|
||||||
|
|
||||||
class Started(val state: Start, val inspector: String? = null)
|
class Started(val state: Start, val inspector: String? = null)
|
||||||
|
|
||||||
class Project(val id: String, val installedModId: String, val folders: List<String>, val update: Boolean)
|
private val INSPECTOR = Regex("ws://127\\.0\\.0\\.1:[0-9]{4,5}/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")
|
||||||
|
|
||||||
internal val INSPECTOR = Regex("ws://127\\.0\\.0\\.1:[0-9]{4,5}/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")
|
|
||||||
|
|
||||||
class Failure(message: String, val code: String? = null) : Exception(message) {
|
class Failure(message: String, val code: String? = null) : Exception(message) {
|
||||||
val gone get() = code == "DEVTOOLS_UNREACHABLE"
|
val gone get() = code == "DEVTOOLS_UNREACHABLE"
|
||||||
@@ -39,19 +31,14 @@ object CurseForgeApp {
|
|||||||
|
|
||||||
internal fun dir(app: UserApps.App): String? = app.args.firstOrNull()?.takeIf { it.startsWith("/") }
|
internal fun dir(app: UserApps.App): String? = app.args.firstOrNull()?.takeIf { it.startsWith("/") }
|
||||||
|
|
||||||
internal fun helperArgv(command: String, dir: String): List<String> = listOf(HELPER, command, dir)
|
fun holdArgs(app: UserApps.App): List<String>? = dir(app)?.let { listOf("hold", it) }
|
||||||
|
|
||||||
internal fun evalArgv(inspector: String, expression: String, timeoutMs: Long): List<String> =
|
|
||||||
listOf(AGENT, "--cdp-inspector", inspector, (timeoutMs / 1000.0).toString(), expression)
|
|
||||||
|
|
||||||
internal fun lastJson(lines: List<String>): JSONObject? =
|
|
||||||
lines.asReversed().firstNotNullOfOrNull { line -> runCatching { JSONObject(line.trim()) }.getOrNull() }
|
|
||||||
|
|
||||||
internal fun inspectorUrl(stdout: String): String? = stdout.lineSequence().map { it.trim() }.lastOrNull { INSPECTOR.matches(it) }
|
internal fun inspectorUrl(stdout: String): String? = stdout.lineSequence().map { it.trim() }.lastOrNull { INSPECTOR.matches(it) }
|
||||||
|
|
||||||
internal fun startState(exitCode: Int): Start = when (exitCode) {
|
internal fun startState(exitCode: Int): Start = when (exitCode) {
|
||||||
0 -> Start.READY
|
0 -> Start.READY
|
||||||
3 -> Start.BUSY
|
3 -> Start.BUSY
|
||||||
|
4 -> Start.NO_DISPLAY
|
||||||
else -> Start.FAILED
|
else -> Start.FAILED
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -145,94 +132,52 @@ object CurseForgeApp {
|
|||||||
return detected?.takeIf { it.isNotBlank() }
|
return detected?.takeIf { it.isNotBlank() }
|
||||||
}
|
}
|
||||||
|
|
||||||
internal fun parseProjects(value: Any?): List<Project> {
|
internal fun projectIds(value: Any?): Set<String> {
|
||||||
val list = value as? JSONArray ?: return emptyList()
|
val list = value as? JSONArray ?: return emptySet()
|
||||||
return (0 until list.length()).mapNotNull { list.optJSONObject(it) }.mapNotNull { p ->
|
return (0 until list.length()).mapNotNull { list.opt(it)?.toString()?.takeIf { id -> id.isNotBlank() && id != "null" } }.toSet()
|
||||||
val id = p.optString("id").takeIf { it.isNotBlank() && it != "null" } ?: return@mapNotNull null
|
|
||||||
val folders = p.optJSONArray("folders")?.let { f -> (0 until f.length()).mapNotNull { f.optString(it).takeIf(String::isNotBlank) } }.orEmpty()
|
|
||||||
Project(id, p.optString("installedModId"), folders, p.optInt("status") == OUT_OF_DATE && !p.optBoolean("locked"))
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
internal fun owner(projects: List<Project>, folder: String): Project? =
|
private fun call(context: Context, inspector: String, service: String, method: String, args: JSONArray?, timeoutMs: Long, pick: String = "r => r"): Any? {
|
||||||
projects.firstOrNull { project -> project.folders.any { it.equals(folder, ignoreCase = true) } }
|
val request = JSONObject().put("kind", "cdp").put("inspector", inspector).put("commandLineApi", true)
|
||||||
|
.put("expression", expression(service, method, args, pick)).put("timeout", timeoutMs / 1000.0)
|
||||||
internal fun byFolder(projects: List<Project>): Map<String, Project> = projects.flatMap { project -> project.folders.map { it.lowercase() to project } }.toMap()
|
return unwrap(AgentGuest.call(context, request, timeoutMs + 3_000, trusted = true))
|
||||||
|
|
||||||
internal fun onDisk(projects: List<Project>, addOns: File): List<Project> {
|
|
||||||
val names = addOns.listFiles().orEmpty().filter { it.isDirectory && !it.name.startsWith(".") }.map { it.name.lowercase() }.toSet()
|
|
||||||
return projects.filter { project -> WowAddons.present(project.folders) { it.lowercase() in names } }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
internal var guest: (Context, List<String>, AtomicBoolean?, (String) -> Unit) -> Int = { context, argv, cancelled, onLine ->
|
private fun helper(context: Context, command: String, dir: String, timeoutMs: Long): JSONObject? {
|
||||||
GuestCommand.run(context, argv, logName = "curseforge", extraBinds = BattleNetInstall.binds(context), fastPath = true,
|
val request = JSONObject().put("kind", "exec").put("argv", JSONArray(listOf(HELPER, command, dir))).put("timeout", timeoutMs / 1000.0)
|
||||||
cancelled = cancelled, redact = INSPECTOR, onLine = onLine)
|
return runCatching { AgentGuest.call(context, request, timeoutMs + 5_000, trusted = true) }.getOrNull()
|
||||||
}
|
}
|
||||||
|
|
||||||
private val holds = ConcurrentHashMap<String, AtomicBoolean>()
|
fun start(context: Context, app: UserApps.App): Started {
|
||||||
|
|
||||||
private fun lines(context: Context, argv: List<String>): List<String> {
|
|
||||||
val out = ArrayList<String>()
|
|
||||||
guest(context, argv, null) { out += it }
|
|
||||||
return out
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun call(context: Context, inspector: String, service: String, method: String, args: JSONArray?, timeoutMs: Long, pick: String = "r => r"): Any? =
|
|
||||||
unwrap(lastJson(lines(context, evalArgv(inspector, expression(service, method, args, pick), timeoutMs))) ?: throw Failure("CurseForge gave no answer"))
|
|
||||||
|
|
||||||
private sealed class Launch {
|
|
||||||
class Url(val inspector: String) : Launch()
|
|
||||||
class Exit(val code: Int) : Launch()
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun launch(context: Context, dir: String, hold: AtomicBoolean): Launch? {
|
|
||||||
val first = LinkedBlockingQueue<Launch>()
|
|
||||||
Thread({
|
|
||||||
val code = runCatching {
|
|
||||||
guest(context, helperArgv("start", dir), hold) { line -> inspectorUrl(line)?.let { first.offer(Launch.Url(it)) } }
|
|
||||||
}.getOrDefault(-1)
|
|
||||||
first.offer(Launch.Exit(code))
|
|
||||||
}, "curseforge-headless").apply { isDaemon = true; start() }
|
|
||||||
return first.poll(READY_MS, TimeUnit.MILLISECONDS)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun start(context: Context, app: UserApps.App, hold: AtomicBoolean): Started {
|
|
||||||
val dir = dir(app) ?: return Started(Start.FAILED)
|
val dir = dir(app) ?: return Started(Start.FAILED)
|
||||||
if (hold.get()) return Started(Start.FAILED)
|
val answer = helper(context, "start", dir, 90_000)
|
||||||
holds.put(dir, hold)?.takeIf { it !== hold }?.let {
|
if (answer == null || !answer.optBoolean("ok") || answer.optBoolean("timedOut")) {
|
||||||
it.set(true)
|
stop(context, app, null)
|
||||||
runCatching { lines(context, helperArgv("stop", dir)) }
|
return Started(Start.FAILED)
|
||||||
}
|
}
|
||||||
val inspector = when (val first = launch(context, dir, hold)) {
|
val state = startState(answer.optInt("exitCode", -1))
|
||||||
is Launch.Url -> first.inspector
|
if (state == Start.BUSY || state == Start.NO_DISPLAY) return Started(state)
|
||||||
is Launch.Exit -> if (startState(first.code) == Start.BUSY) {
|
val inspector = inspectorUrl(answer.optJSONObject("stdout")?.optString("text").orEmpty())
|
||||||
holds.remove(dir, hold)
|
if (state != Start.READY || inspector == null) {
|
||||||
return Started(Start.BUSY)
|
stop(context, app, null)
|
||||||
} else null
|
|
||||||
null -> null
|
|
||||||
}
|
|
||||||
if (inspector == null) {
|
|
||||||
stop(context, app, null, hold)
|
|
||||||
return Started(Start.FAILED)
|
return Started(Start.FAILED)
|
||||||
}
|
}
|
||||||
val deadline = System.currentTimeMillis() + READY_MS
|
val deadline = System.currentTimeMillis() + READY_MS
|
||||||
while (System.currentTimeMillis() < deadline && !hold.get()) {
|
while (System.currentTimeMillis() < deadline) {
|
||||||
if (runCatching { call(context, inspector, "InstalledProjectsAppService", "installAddon", null, 10_000) }.isSuccess) return Started(Start.READY, inspector)
|
val ready = runCatching { call(context, inspector, "InstalledProjectsAppService", "installAddon", null, 10_000) }
|
||||||
|
if (ready.isSuccess) return Started(Start.READY, inspector)
|
||||||
|
val error = ready.exceptionOrNull()
|
||||||
|
if (error is AgentException && error.code == "NO_ACTIVE_SESSION") break
|
||||||
Thread.sleep(1_000)
|
Thread.sleep(1_000)
|
||||||
}
|
}
|
||||||
stop(context, app, inspector, hold)
|
stop(context, app, inspector)
|
||||||
return Started(Start.FAILED)
|
return Started(Start.FAILED)
|
||||||
}
|
}
|
||||||
|
|
||||||
fun stop(context: Context, app: UserApps.App, inspector: String?, hold: AtomicBoolean) {
|
fun stop(context: Context, app: UserApps.App, inspector: String?) {
|
||||||
val dir = dir(app) ?: return
|
val dir = dir(app) ?: return
|
||||||
if (holds[dir] !== hold) {
|
|
||||||
hold.set(true)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if (inspector != null) runCatching { call(context, inspector, "CoreService", "shutdown", JSONArray(), 30_000, "r => true") }
|
if (inspector != null) runCatching { call(context, inspector, "CoreService", "shutdown", JSONArray(), 30_000, "r => true") }
|
||||||
hold.set(true)
|
helper(context, "stop", dir, 30_000)
|
||||||
if (holds.remove(dir, hold)) runCatching { lines(context, helperArgv("stop", dir)) }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun connect(context: Context, inspector: String) {
|
private fun connect(context: Context, inspector: String) {
|
||||||
@@ -250,44 +195,22 @@ object CurseForgeApp {
|
|||||||
fun search(context: Context, inspector: String, guid: String, text: String, sort: WowAddonCatalog.Sort, page: Int): WowAddonCatalog.Page =
|
fun search(context: Context, inspector: String, guid: String, text: String, sort: WowAddonCatalog.Sort, page: Int): WowAddonCatalog.Page =
|
||||||
parseSearch(call(context, inspector, "ProjectAppService", "search", JSONArray().put(searchRequest(guid, text, sort, page)), 60_000))
|
parseSearch(call(context, inspector, "ProjectAppService", "search", JSONArray().put(searchRequest(guid, text, sort, page)), 60_000))
|
||||||
|
|
||||||
fun projects(context: Context, inspector: String, guid: String, rescan: Boolean = false): List<Project> {
|
fun installed(context: Context, inspector: String, guid: String): Set<String> {
|
||||||
connect(context, inspector)
|
connect(context, inspector)
|
||||||
if (rescan) call(context, inspector, "GameDetectionAppService", "scanGameInstance", JSONArray().put(guid), 120_000)
|
return projectIds(call(context, inspector, "InstalledProjectsAppService", "getProjects", JSONArray().put(guid), 30_000, "r => (r || []).map(p => String(p.id))"))
|
||||||
return parseProjects(call(context, inspector, "InstalledProjectsAppService", "getProjects", JSONArray().put(guid), 30_000, PROJECTS))
|
|
||||||
}
|
|
||||||
|
|
||||||
private const val PROJECTS = "r => (r || []).map(p => ({ id: String(p.id), installedModId: p.installedModId, status: p.status, " +
|
|
||||||
"locked: !!(p.installedVersion && p.installedVersion.isLocked), " +
|
|
||||||
"folders: ((p.installedVersion && p.installedVersion.addonFolders) || []).map(f => f.name) }))"
|
|
||||||
|
|
||||||
private fun settle(context: Context, inspector: String, guid: String, done: (List<Project>) -> Boolean): Boolean {
|
|
||||||
val deadline = System.currentTimeMillis() + INSTALL_MS
|
|
||||||
while (System.currentTimeMillis() < deadline) {
|
|
||||||
val listed = runCatching { projects(context, inspector, guid) }
|
|
||||||
val error = listed.exceptionOrNull()
|
|
||||||
if (error is Failure && error.gone) throw error
|
|
||||||
listed.getOrNull()?.let { if (done(it)) return true }
|
|
||||||
Thread.sleep(1_000)
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fun install(context: Context, inspector: String, guid: String, projectId: String): Boolean {
|
fun install(context: Context, inspector: String, guid: String, projectId: String): Boolean {
|
||||||
connect(context, inspector)
|
connect(context, inspector)
|
||||||
if (call(context, inspector, "InstalledProjectsAppService", "installAddon", JSONArray().put(installRequest(guid, projectId)), 300_000) != true) return false
|
if (call(context, inspector, "InstalledProjectsAppService", "installAddon", JSONArray().put(installRequest(guid, projectId)), 300_000) != true) return false
|
||||||
return settle(context, inspector, guid) { list -> list.any { it.id == projectId } }
|
val deadline = System.currentTimeMillis() + INSTALL_MS
|
||||||
}
|
while (System.currentTimeMillis() < deadline) {
|
||||||
|
val listed = runCatching { installed(context, inspector, guid) }
|
||||||
fun update(context: Context, inspector: String, guid: String, projectId: String): Boolean {
|
val error = listed.exceptionOrNull()
|
||||||
connect(context, inspector)
|
if (error is Failure && error.gone || error is AgentException && error.code == "NO_ACTIVE_SESSION") throw error
|
||||||
if (call(context, inspector, "InstalledProjectsAppService", "updateMod", JSONArray().put(guid).put(projectId.toLong()), 300_000) != true) return false
|
if (projectId in listed.getOrDefault(emptySet())) return true
|
||||||
return settle(context, inspector, guid) { list -> list.any { it.id == projectId && !it.update } }
|
Thread.sleep(1_000)
|
||||||
}
|
}
|
||||||
|
return false
|
||||||
fun uninstall(context: Context, inspector: String, guid: String, project: Project): Boolean {
|
|
||||||
connect(context, inspector)
|
|
||||||
val failed = call(context, inspector, "InstalledProjectsAppService", "deleteMods", JSONArray().put(guid).put(JSONArray().put(project.installedModId)), 120_000) as? JSONArray
|
|
||||||
if (failed == null || failed.length() > 0) return false
|
|
||||||
return settle(context, inspector, guid) { list -> list.none { it.id == project.id } }
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -14,22 +14,20 @@ import java.util.concurrent.atomic.AtomicBoolean
|
|||||||
object GuestCommand {
|
object GuestCommand {
|
||||||
fun run(context: Context, argv: List<String>, fakeRoot: Boolean = false, logName: String? = null,
|
fun run(context: Context, argv: List<String>, fakeRoot: Boolean = false, logName: String? = null,
|
||||||
linkDir: File? = null, extraBinds: List<String>? = null, fastPath: Boolean = false, cancelled: AtomicBoolean? = null,
|
linkDir: File? = null, extraBinds: List<String>? = null, fastPath: Boolean = false, cancelled: AtomicBoolean? = null,
|
||||||
redact: Regex? = null, onLine: (String) -> Unit): Int {
|
onLine: (String) -> Unit): Int {
|
||||||
val log = logName?.let {
|
val log = logName?.let {
|
||||||
try {
|
try {
|
||||||
File(File(LinuxRuntime.logDir(context), SessionPaths.TOOLS_DIR).apply { mkdirs() }, "$it.log").printWriter()
|
File(File(LinuxRuntime.logDir(context), SessionPaths.TOOLS_DIR).apply { mkdirs() }, "$it.log").printWriter()
|
||||||
} catch (e: Exception) { null }
|
} catch (e: Exception) { null }
|
||||||
}
|
}
|
||||||
log?.println("== ${java.util.Date()} ${redacted(argv.joinToString(" "), redact)}")
|
log?.println("== ${java.util.Date()} ${argv.joinToString(" ")}")
|
||||||
try {
|
try {
|
||||||
return runLogged(context, argv, fakeRoot, linkDir, extraBinds, fastPath, cancelled) { line -> log?.println(redacted(line, redact)); log?.flush(); onLine(line) }
|
return runLogged(context, argv, fakeRoot, linkDir, extraBinds, fastPath, cancelled) { line -> log?.println(line); log?.flush(); onLine(line) }
|
||||||
} finally {
|
} finally {
|
||||||
log?.close()
|
log?.close()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
internal fun redacted(text: String, redact: Regex?): String = redact?.replace(text, "<redacted>") ?: text
|
|
||||||
|
|
||||||
private fun runLogged(context: Context, argv: List<String>, fakeRoot: Boolean, linkDir: File?, extraBinds: List<String>?,
|
private fun runLogged(context: Context, argv: List<String>, fakeRoot: Boolean, linkDir: File?, extraBinds: List<String>?,
|
||||||
fastPath: Boolean, cancelled: AtomicBoolean?, onLine: (String) -> Unit): Int {
|
fastPath: Boolean, cancelled: AtomicBoolean?, onLine: (String) -> Unit): Int {
|
||||||
val root = LinuxRuntime.rootDir(context)
|
val root = LinuxRuntime.rootDir(context)
|
||||||
|
|||||||
@@ -29,7 +29,6 @@ object WowAddonCatalog {
|
|||||||
val downloads: Long,
|
val downloads: Long,
|
||||||
val updated: Long,
|
val updated: Long,
|
||||||
val thumb: String?,
|
val thumb: String?,
|
||||||
val folders: List<String> = emptyList(),
|
|
||||||
)
|
)
|
||||||
|
|
||||||
class Page(val items: List<Addon>, val more: Boolean)
|
class Page(val items: List<Addon>, val more: Boolean)
|
||||||
@@ -115,11 +114,9 @@ object WowAddonCatalog {
|
|||||||
}
|
}
|
||||||
val thumbs = o.optJSONArray("UIIMG_Thumbs")
|
val thumbs = o.optJSONArray("UIIMG_Thumbs")
|
||||||
val thumb = if (thumbs != null && thumbs.length() > 0) thumbs.optString(0).ifEmpty { null } else null
|
val thumb = if (thumbs != null && thumbs.length() > 0) thumbs.optString(0).ifEmpty { null } else null
|
||||||
val dirs = o.optJSONArray("UIDir")
|
|
||||||
val folders = if (dirs == null) emptyList() else (0 until dirs.length()).map { dirs.optString(it).trim() }.filter { it.isNotEmpty() }
|
|
||||||
val addon = Addon(
|
val addon = Addon(
|
||||||
id, o.optString("UIName"), o.optString("UIAuthorName"), o.optString("UIVersion"),
|
id, o.optString("UIName"), o.optString("UIAuthorName"), o.optString("UIVersion"),
|
||||||
o.optString("UIDownloadTotal").toLongOrNull() ?: 0L, o.optLong("UIDate"), thumb, folders,
|
o.optString("UIDownloadTotal").toLongOrNull() ?: 0L, o.optLong("UIDate"), thumb,
|
||||||
)
|
)
|
||||||
out.add(Entry(addon, o.optString("UICATID"), flavors, o.optString("UIDownloadMonthly").toLongOrNull() ?: 0L))
|
out.add(Entry(addon, o.optString("UICATID"), flavors, o.optString("UIDownloadMonthly").toLongOrNull() ?: 0L))
|
||||||
}
|
}
|
||||||
@@ -244,32 +241,9 @@ object WowAddonCatalog {
|
|||||||
return details.version
|
return details.version
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun normVersion(v: String) = v.trim().removePrefix("v").removePrefix("V").trim().lowercase()
|
internal fun sameVersion(a: String, b: String): Boolean {
|
||||||
|
fun norm(v: String) = v.trim().removePrefix("v").removePrefix("V").trim().lowercase()
|
||||||
internal fun sameVersion(a: String, b: String): Boolean = normVersion(a) == normVersion(b)
|
return norm(a) == norm(b)
|
||||||
|
|
||||||
private val NUMERIC_VERSION = Regex("""^(\d+(?:\.\d+)*)(.*)$""")
|
|
||||||
|
|
||||||
private fun numericVersion(v: String): Pair<List<Long>, String>? {
|
|
||||||
val match = NUMERIC_VERSION.matchEntire(normVersion(v)) ?: return null
|
|
||||||
val parts = match.groupValues[1].split('.').map { it.toLongOrNull() ?: return null }
|
|
||||||
return parts to match.groupValues[2]
|
|
||||||
}
|
|
||||||
|
|
||||||
internal fun newer(have: String, latest: String): Boolean? {
|
|
||||||
val (a, aRest) = numericVersion(have) ?: return null
|
|
||||||
val (b, bRest) = numericVersion(latest) ?: return null
|
|
||||||
for (i in 0 until maxOf(a.size, b.size)) {
|
|
||||||
val x = a.getOrElse(i) { 0L }
|
|
||||||
val y = b.getOrElse(i) { 0L }
|
|
||||||
if (x != y) return y > x
|
|
||||||
}
|
|
||||||
return if (aRest == bRest) false else null
|
|
||||||
}
|
|
||||||
|
|
||||||
internal fun offersUpdate(have: String?, latest: String, sameSource: Boolean): Boolean {
|
|
||||||
if (have.isNullOrBlank() || latest.isBlank() || sameVersion(have, latest)) return false
|
|
||||||
return newer(have, latest) ?: sameSource
|
|
||||||
}
|
}
|
||||||
|
|
||||||
internal fun findUpdates(entries: List<Entry>, installed: List<WowAddons.Installed>): Map<String, Addon> {
|
internal fun findUpdates(entries: List<Entry>, installed: List<WowAddons.Installed>): Map<String, Addon> {
|
||||||
@@ -279,7 +253,7 @@ object WowAddonCatalog {
|
|||||||
val id = item.wowiId ?: return@mapNotNull null
|
val id = item.wowiId ?: return@mapNotNull null
|
||||||
val version = item.version ?: return@mapNotNull null
|
val version = item.version ?: return@mapNotNull null
|
||||||
val latest = byId[id]?.addon?.takeIf { it.summary.isNotBlank() } ?: return@mapNotNull null
|
val latest = byId[id]?.addon?.takeIf { it.summary.isNotBlank() } ?: return@mapNotNull null
|
||||||
if (!offersUpdate(version, latest.summary, sameSource = true) || !seen.add(id)) null else item.name to latest
|
if (sameVersion(version, latest.summary) || !seen.add(id)) null else item.name to latest
|
||||||
}.toMap()
|
}.toMap()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -40,15 +40,11 @@ object WowAddons {
|
|||||||
|
|
||||||
class Addon(val name: String, val root: String)
|
class Addon(val name: String, val root: String)
|
||||||
|
|
||||||
class Installed(val name: String, val version: String?, val wowiId: String?, val curseId: String? = null)
|
class Installed(val name: String, val version: String?, val wowiId: String?)
|
||||||
|
|
||||||
class Origin(val id: String, val version: String)
|
class Origin(val id: String, val version: String)
|
||||||
|
|
||||||
private const val ORIGINS = ".droiddeck-sources"
|
private const val ORIGINS = ".droiddeck-sources"
|
||||||
private const val TOC_VERSION = "Version"
|
|
||||||
private const val TOC_WOWI_ID = "X-WoWI-ID"
|
|
||||||
private const val TOC_CURSE_ID = "X-Curse-Project-ID"
|
|
||||||
private val TOC_KEYS = setOf(TOC_VERSION, TOC_WOWI_ID, TOC_CURSE_ID)
|
|
||||||
|
|
||||||
internal const val MAX_EXPANDED_BYTES = 4L * 1024 * 1024 * 1024
|
internal const val MAX_EXPANDED_BYTES = 4L * 1024 * 1024 * 1024
|
||||||
|
|
||||||
@@ -73,52 +69,33 @@ object WowAddons {
|
|||||||
target.addOns.listFiles().orEmpty().filter { it.isDirectory && !it.name.startsWith(".") }
|
target.addOns.listFiles().orEmpty().filter { it.isDirectory && !it.name.startsWith(".") }
|
||||||
.map { it.name }.sortedBy { it.lowercase() }
|
.map { it.name }.sortedBy { it.lowercase() }
|
||||||
|
|
||||||
fun present(folders: List<String>, exists: (String) -> Boolean): Boolean = folders.isNotEmpty() && folders.all(exists)
|
|
||||||
|
|
||||||
fun folder(addOns: File, name: String): File? {
|
|
||||||
val dirs = addOns.listFiles().orEmpty().filter { it.isDirectory && !it.name.startsWith(".") }
|
|
||||||
return dirs.firstOrNull { it.name == name } ?: dirs.firstOrNull { it.name.equals(name, ignoreCase = true) }
|
|
||||||
}
|
|
||||||
|
|
||||||
fun details(target: Target): List<Installed> {
|
fun details(target: Target): List<Installed> {
|
||||||
val origins = origins(target)
|
val origins = origins(target)
|
||||||
return installed(target).map { name ->
|
return installed(target).map { name ->
|
||||||
val toc = toc(File(target.addOns, name))
|
val toc = toc(File(target.addOns, name))
|
||||||
val origin = origins[name]
|
val origin = origins[name]
|
||||||
Installed(name, origin?.version ?: toc[TOC_VERSION], origin?.id ?: toc[TOC_WOWI_ID], toc[TOC_CURSE_ID])
|
Installed(name, origin?.version ?: toc["Version"], origin?.id ?: toc["X-WoWI-ID"])
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
internal fun tocFields(lines: Sequence<String>, keys: Set<String> = TOC_KEYS): Map<String, String> {
|
internal fun tocFields(text: String): Map<String, String> {
|
||||||
val out = LinkedHashMap<String, String>()
|
val out = LinkedHashMap<String, String>()
|
||||||
for (raw in lines) {
|
for (raw in text.lineSequence()) {
|
||||||
val line = raw.trim().removePrefix("\uFEFF")
|
val line = raw.trim().removePrefix("\uFEFF")
|
||||||
if (!line.startsWith("##") || ':' !in line) continue
|
if (!line.startsWith("##") || ':' !in line) continue
|
||||||
val key = line.removePrefix("##").substringBefore(':').trim()
|
val key = line.removePrefix("##").substringBefore(':').trim()
|
||||||
if (key !in keys || key in out) continue
|
|
||||||
val value = line.substringAfter(':').trim()
|
val value = line.substringAfter(':').trim()
|
||||||
if (value.isNotEmpty() && '@' !in value) out[key] = value
|
if (key.isNotEmpty() && value.isNotEmpty() && '@' !in value) out.putIfAbsent(key, value)
|
||||||
if (out.size == keys.size) break
|
|
||||||
}
|
}
|
||||||
return out
|
return out
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun toc(folder: File): Map<String, String> {
|
private fun toc(folder: File): Map<String, String> {
|
||||||
val tocs = folder.listFiles().orEmpty().filter { it.isFile && it.name.endsWith(".toc", ignoreCase = true) }.sortedWith(
|
val tocs = folder.listFiles().orEmpty().filter { it.isFile && it.name.endsWith(".toc", ignoreCase = true) }
|
||||||
compareBy<File>(
|
val main = tocs.firstOrNull { it.name.dropLast(4).equals(folder.name, ignoreCase = true) }
|
||||||
{ !it.name.dropLast(4).equals(folder.name, ignoreCase = true) },
|
?: tocs.firstOrNull { it.name.dropLast(4).replace(SUFFIX, "").equals(folder.name, ignoreCase = true) }
|
||||||
{ !it.name.dropLast(4).replace(SUFFIX, "").equals(folder.name, ignoreCase = true) },
|
?: tocs.minByOrNull { it.name.length } ?: return emptyMap()
|
||||||
{ it.name.length },
|
return runCatching { tocFields(main.readText()) }.getOrDefault(emptyMap())
|
||||||
{ it.name },
|
|
||||||
),
|
|
||||||
)
|
|
||||||
val out = LinkedHashMap<String, String>()
|
|
||||||
for (file in tocs) {
|
|
||||||
if (out.size == TOC_KEYS.size) break
|
|
||||||
val missing = TOC_KEYS - out.keys
|
|
||||||
runCatching { file.bufferedReader().useLines { tocFields(it, missing) } }.getOrNull()?.let(out::putAll)
|
|
||||||
}
|
|
||||||
return out
|
|
||||||
}
|
}
|
||||||
|
|
||||||
internal fun parseOrigins(text: String): Map<String, Origin> = text.lineSequence().mapNotNull { line ->
|
internal fun parseOrigins(text: String): Map<String, Origin> = text.lineSequence().mapNotNull { line ->
|
||||||
|
|||||||
@@ -0,0 +1,119 @@
|
|||||||
|
package com.droiddeck.launcher.session
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.graphics.PixelFormat
|
||||||
|
import android.media.ImageReader
|
||||||
|
import android.os.Handler
|
||||||
|
import android.os.Looper
|
||||||
|
import android.util.Log
|
||||||
|
import com.droiddeck.launcher.agent.AgentGuest
|
||||||
|
import com.droiddeck.launcher.runtime.LinuxRuntimeInstaller
|
||||||
|
import com.droiddeck.launcher.storage.StorageState
|
||||||
|
import com.droiddeck.launcher.wayland.CompositorHost
|
||||||
|
import java.util.concurrent.CountDownLatch
|
||||||
|
import java.util.concurrent.TimeUnit
|
||||||
|
import java.util.concurrent.atomic.AtomicBoolean
|
||||||
|
|
||||||
|
object BackgroundSession {
|
||||||
|
private const val TAG = "BackgroundSession"
|
||||||
|
private const val WIDTH = 1280
|
||||||
|
private const val HEIGHT = 720
|
||||||
|
private const val REFRESH_HZ = 60f
|
||||||
|
private const val BEGIN_MS = 30_000L
|
||||||
|
private const val AGENT_MS = 120_000L
|
||||||
|
private const val STOP_MS = 30_000L
|
||||||
|
private val ended = setOf(SessionPhase.IDLE, SessionPhase.FAILED)
|
||||||
|
private val main by lazy { Handler(Looper.getMainLooper()) }
|
||||||
|
private var reader: ImageReader? = null
|
||||||
|
|
||||||
|
fun start(context: Context, program: String, args: List<String>): String? {
|
||||||
|
val app = context.applicationContext
|
||||||
|
val claim = AtomicBoolean(false)
|
||||||
|
val began = CountDownLatch(1)
|
||||||
|
var own: String? = null
|
||||||
|
main.post {
|
||||||
|
if (claim.compareAndSet(false, true)) {
|
||||||
|
own = runCatching { begin(app, program, args) }
|
||||||
|
.onFailure { Log.w(TAG, "could not start a hidden session for $program", it) }
|
||||||
|
.getOrNull()
|
||||||
|
}
|
||||||
|
began.countDown()
|
||||||
|
}
|
||||||
|
if (!began.await(BEGIN_MS, TimeUnit.MILLISECONDS) && claim.compareAndSet(false, true)) return null
|
||||||
|
began.await()
|
||||||
|
val session = own ?: return null
|
||||||
|
val deadline = System.currentTimeMillis() + AGENT_MS
|
||||||
|
val settle = System.currentTimeMillis() + 5_000
|
||||||
|
while (System.currentTimeMillis() < deadline) {
|
||||||
|
if (SessionState.sessionId != session) return null
|
||||||
|
if (SessionState.running && AgentGuest.hello(app) != null && SessionState.sessionId == session) return session
|
||||||
|
if (SessionState.phase == SessionPhase.FAILED) break
|
||||||
|
if (!SessionState.running && SessionState.phase in ended && System.currentTimeMillis() > settle) break
|
||||||
|
Thread.sleep(250)
|
||||||
|
}
|
||||||
|
stop(app, session)
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
fun stop(context: Context, session: String) {
|
||||||
|
val app = context.applicationContext
|
||||||
|
if (SessionState.sessionId != session) return
|
||||||
|
main.post { if (SessionState.sessionId == session) SessionService.stop(app) }
|
||||||
|
val deadline = System.currentTimeMillis() + STOP_MS
|
||||||
|
while (live(session) && System.currentTimeMillis() < deadline) Thread.sleep(250)
|
||||||
|
if (!live(session)) {
|
||||||
|
main.post { release() }
|
||||||
|
return
|
||||||
|
}
|
||||||
|
Thread {
|
||||||
|
while (live(session)) Thread.sleep(1_000)
|
||||||
|
main.post { release() }
|
||||||
|
}.start()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun live(session: String) =
|
||||||
|
SessionState.sessionId == session && (SessionState.running || SessionState.phase !in ended)
|
||||||
|
|
||||||
|
private fun begin(context: Context, program: String, args: List<String>): String? {
|
||||||
|
if (SessionState.running || SessionState.phase !in ended || LinuxRuntimeInstaller.isBusy() ||
|
||||||
|
SessionState.installing != null || StorageState.cleaning) return null
|
||||||
|
release()
|
||||||
|
SessionEvents.begin(context, SessionService.MODE_RUN, SessionPaths.label(SessionService.MODE_RUN, program))
|
||||||
|
val session = SessionState.sessionId ?: return null
|
||||||
|
SessionState.stopRequested = false
|
||||||
|
SessionEvents.transition(SessionPhase.STARTING_COMPOSITOR, "compositor.starting")
|
||||||
|
var requested = false
|
||||||
|
try {
|
||||||
|
val output = CompositorHost.prepare(context)
|
||||||
|
val size = WIDTH to HEIGHT
|
||||||
|
SessionState.outputSize = size
|
||||||
|
SessionState.refreshHz = REFRESH_HZ
|
||||||
|
CompositorHost.logToSession(context)
|
||||||
|
CompositorHost.applyHdr(context, SessionPrefs.prefMode(SessionService.MODE_RUN))
|
||||||
|
val offscreen = ImageReader.newInstance(WIDTH, HEIGHT, PixelFormat.RGBA_8888, 2)
|
||||||
|
reader = offscreen
|
||||||
|
offscreen.setOnImageAvailableListener({ it.acquireLatestImage()?.close() }, main)
|
||||||
|
CompositorHost.start(context, output, offscreen.surface, size, REFRESH_HZ, 0)
|
||||||
|
CompositorHost.detach(offscreen.surface)
|
||||||
|
SessionEvents.record("compositor.started")
|
||||||
|
SessionEvents.transition(SessionPhase.STARTING_GUEST, "guest.starting")
|
||||||
|
requested = true
|
||||||
|
SessionService.start(context, SessionService.MODE_RUN, program, programArgs = args.toTypedArray())
|
||||||
|
return session
|
||||||
|
} catch (e: Exception) {
|
||||||
|
if (requested) SessionService.stop(context)
|
||||||
|
if (!SessionState.running) {
|
||||||
|
reader?.close()
|
||||||
|
reader = null
|
||||||
|
SessionEvents.transition(SessionPhase.FAILED, "hidden.failed", mapOf("error" to e.toString()))
|
||||||
|
}
|
||||||
|
throw e
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun release() {
|
||||||
|
if (SessionState.running) return
|
||||||
|
reader?.close()
|
||||||
|
reader = null
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -88,8 +88,8 @@ object ComponentUpdater {
|
|||||||
logLines(context).mapNotNull { STAMP.find(it)?.groupValues?.get(1) }.maxOrNull() ?: "0"
|
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? {
|
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 (!ComponentUpdates.autoFollows(p, comp) || !ComponentsManager.supports(p, comp)) return null
|
||||||
if (comp == "fex") return ComponentUpdates.line("fex", false)
|
if (comp == "fex") return ComponentUpdates.fexLine(p)
|
||||||
val key = "${p.id}|${p.version}"
|
val key = "${p.id}|${p.version}"
|
||||||
val flavors = state.obj("flavors").obj(key)
|
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) }
|
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 BOOTED_SECONDS = 60L
|
||||||
const val FAILED_BOOTS_BEFORE_ROLLBACK = 2
|
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(
|
val LINES = listOf(
|
||||||
Line("dxvk", "dxvk", "DD-dxvk-"),
|
Line("dxvk", "dxvk", "DD-dxvk-"),
|
||||||
@@ -21,12 +21,19 @@ object ComponentUpdates {
|
|||||||
Line("vkd3d", "vkd3d", "DD-vkd3d-proton-"),
|
Line("vkd3d", "vkd3d", "DD-vkd3d-proton-"),
|
||||||
Line("vkd3d-arm64ec", "vkd3d", "DD-vkd3d-proton-arm64ec-"),
|
Line("vkd3d-arm64ec", "vkd3d", "DD-vkd3d-proton-arm64ec-"),
|
||||||
Line("fex", "fex", "DD-FEXCore-"),
|
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
|
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 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 ownId(protonId: String): Boolean = protonId.startsWith(ComponentsManager.safeName(OWN_PREFIX))
|
||||||
|
|
||||||
fun strays(
|
fun strays(
|
||||||
@@ -34,8 +41,8 @@ object ComponentUpdates {
|
|||||||
choices: Map<String, Map<String, ComponentsManager.Choice>>,
|
choices: Map<String, Map<String, ComponentsManager.Choice>>,
|
||||||
placed: Set<String>,
|
placed: Set<String>,
|
||||||
): List<Pair<ComponentsManager.Proton, String>> =
|
): List<Pair<ComponentsManager.Proton, String>> =
|
||||||
protons.filterNot(::follows).flatMap { p ->
|
protons.flatMap { p ->
|
||||||
choices[p.id].orEmpty().filter { (_, c) -> !c.auto && c.protonVersion == p.version && c.file in placed }.keys.map { p to it }
|
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(
|
fun unseen(
|
||||||
@@ -53,13 +60,14 @@ object ComponentUpdates {
|
|||||||
|
|
||||||
fun pick(items: List<ComponentsManager.CatalogItem>, line: Line, bad: Set<String>): ComponentsManager.CatalogItem? {
|
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) }
|
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 }
|
.filter { newestBad == null || ProtonExtras.compareVersions(it.file, newestBad) > 0 }
|
||||||
.maxWithOrNull { a, b -> ProtonExtras.compareVersions(a.file, b.file) }
|
.maxWithOrNull { a, b -> ProtonExtras.compareVersions(a.file, b.file) }
|
||||||
}
|
}
|
||||||
|
|
||||||
fun belongs(file: String, line: Line): Boolean =
|
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 {
|
fun arm64ec(pe: ByteArray): Boolean? = runCatching {
|
||||||
val b = ByteBuffer.wrap(pe).order(ByteOrder.LITTLE_ENDIAN)
|
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> {
|
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) }
|
val ranked = line?.takeIf { belongs(current, it) }
|
||||||
fun newer(file: String) = ranked != null && belongs(file, ranked) && ProtonExtras.compareVersions(file, current) > 0
|
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()
|
.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 NIGHTLIES = "The412Banner/Nightlies"
|
||||||
private const val DD_COMPONENTS = "Droid-Deck/DroidDeck-Components"
|
private const val DD_COMPONENTS = "Droid-Deck/DroidDeck-Components"
|
||||||
internal const val DD_NIGHTLY = "linux-nightly"
|
internal const val DD_NIGHTLY = "linux-nightly"
|
||||||
|
internal const val DD_BIONIC = "bionic-stable"
|
||||||
private val RELEASES = linkedMapOf(
|
private val RELEASES = linkedMapOf(
|
||||||
"FexCore-Linux" to "fex",
|
"FexCore-Linux" to "fex",
|
||||||
"Dxvk-Linux" to "dxvk",
|
"Dxvk-Linux" to "dxvk",
|
||||||
@@ -37,9 +38,9 @@ object ComponentsManager {
|
|||||||
"Vkd3d-proton-Linux" to "vkd3d",
|
"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 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 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")
|
private val TYPE_OF = mapOf("fex" to "FEXCore-Linux", "dxvk" to "DXVK-Linux", "vkd3d" to "VKD3D-Linux")
|
||||||
val COMPONENTS = listOf("fex", "dxvk", "vkd3d")
|
val COMPONENTS = listOf("fex", "dxvk", "vkd3d")
|
||||||
val LABEL = mapOf("fex" to "FEX", "dxvk" to "DXVK", "vkd3d" to "VKD3D-Proton")
|
val LABEL = mapOf("fex" to "FEX", "dxvk" to "DXVK", "vkd3d" to "VKD3D-Proton")
|
||||||
@@ -201,8 +202,34 @@ object ComponentsManager {
|
|||||||
COMPONENTS.mapNotNull { comp -> profile.optString(comp).takeIf(String::isNotEmpty)?.let { comp to it } }.toMap()
|
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) }
|
setGameComponent(context, scope, comp, file) { runtimeManaged(context, it) }
|
||||||
|
if (comp == "fex" && file != null) fetchFexTwin(context, safeName(file))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Twin downloads in flight: one worker per name, so two profile changes cannot share one partial download.
|
||||||
|
private val twinDownloads = HashSet<String>()
|
||||||
|
|
||||||
|
private fun fetchFexTwin(context: Context, file: String) {
|
||||||
|
val twin = fexTwin(file) ?: return
|
||||||
|
if (protons(context).all { fexFits(it.dir.name, file) }) return
|
||||||
|
synchronized(lock) { if (isStored(context, twin) || !twinDownloads.add(twin)) return }
|
||||||
|
val app = context.applicationContext
|
||||||
|
Thread({
|
||||||
|
try {
|
||||||
|
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) }
|
||||||
|
} finally {
|
||||||
|
synchronized(lock) { twinDownloads.remove(twin) }
|
||||||
|
}
|
||||||
|
}, "fex-twin").start()
|
||||||
|
}
|
||||||
|
|
||||||
internal fun setGameComponent(context: Context, scope: String, comp: String, file: String?, managed: (String) -> Boolean) = synchronized(lock) {
|
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)
|
require(scope.matches(Regex("[1-9][0-9]{0,9}")) && scope.toLong() <= 4294967295L)
|
||||||
@@ -413,7 +440,7 @@ object ComponentsManager {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
require(File(staged, "files").isDirectory) { "${wcp.name} has no files/" }
|
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 ->
|
COMP_DIR[comp]?.let { compDir ->
|
||||||
for (arch in PE_ARCHES) {
|
for (arch in PE_ARCHES) {
|
||||||
val target = File(dir, "$compDir/$arch")
|
val target = File(dir, "$compDir/$arch")
|
||||||
@@ -603,7 +630,9 @@ object ComponentsManager {
|
|||||||
File(base, "files").walkTopDown().filter { it.isFile }.map { it.relativeTo(base).invariantSeparatorsPath }
|
File(base, "files").walkTopDown().filter { it.isFile }.map { it.relativeTo(base).invariantSeparatorsPath }
|
||||||
.filter { owned(comp, it) }.associateWith { File(base, it) }
|
.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)
|
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")
|
.append('\t').append(rel).append("\t-\t-\n")
|
||||||
}
|
}
|
||||||
@@ -620,7 +649,8 @@ object ComponentsManager {
|
|||||||
val version = safeName(file.removePrefix("original "))
|
val version = safeName(file.removePrefix("original "))
|
||||||
"original-${p.id}-$version-$comp" to File(originalsDir(context), "${p.id}/$version/$comp.wcp")
|
"original-${p.id}-$version-$comp" to File(originalsDir(context), "${p.id}/$version/$comp.wcp")
|
||||||
} else {
|
} 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 }
|
}.takeIf { it.second.isFile }
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -651,12 +681,14 @@ object ComponentsManager {
|
|||||||
for (scope in profiles.keys()) {
|
for (scope in profiles.keys()) {
|
||||||
val profile = profiles.optJSONObject(scope) ?: continue
|
val profile = profiles.optJSONObject(scope) ?: continue
|
||||||
for (comp in COMPONENTS) {
|
for (comp in COMPONENTS) {
|
||||||
val file = profile.optString(comp)
|
val chosen = profile.optString(comp)
|
||||||
if (file.isEmpty()) continue
|
if (chosen.isEmpty()) continue
|
||||||
val wcp = File(packagesDir(context), file)
|
for (p in all) {
|
||||||
if (!wcp.isFile) continue
|
val file = (if (comp == "fex") launchFex(p.dir.name, chosen) { File(packagesDir(context), it).isFile } else chosen) ?: continue
|
||||||
val key = safeName(file.removeSuffix(".wcp"))
|
val wcp = File(packagesDir(context), file)
|
||||||
for (p in all) append(scope, p, comp, key, wcp)
|
if (!wcp.isFile) continue
|
||||||
|
append(scope, p, comp, safeName(file.removeSuffix(".wcp")), wcp)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return PreparedLaunchState(lines.toString(), keep)
|
return PreparedLaunchState(lines.toString(), keep)
|
||||||
@@ -677,6 +709,7 @@ object ComponentsManager {
|
|||||||
val wcp = File(packagesDir(context), safeName(file))
|
val wcp = File(packagesDir(context), safeName(file))
|
||||||
val info = packageInfo(context, wcp)
|
val info = packageInfo(context, wcp)
|
||||||
requireSelectable(context, info.comp)
|
requireSelectable(context, info.comp)
|
||||||
|
requireFits(p, info)
|
||||||
val state = loadState(context)
|
val state = loadState(context)
|
||||||
if (inUse(context, p)) {
|
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)
|
state.sub("queued").sub(p.id).put(info.comp, JSONObject().put("kind", "package").put("file", wcp.name).put("label", info.version)
|
||||||
@@ -690,7 +723,11 @@ object ComponentsManager {
|
|||||||
context.getString(R.string.cmgr_swap_done, LABEL[info.comp], info.version, p.name)
|
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) {
|
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)
|
ensureOriginal(context, p, info.comp, state)
|
||||||
val hashes = installFiles(context, p.dir, info.comp, wcp)
|
val hashes = installFiles(context, p.dir, info.comp, wcp)
|
||||||
state.sub("active").sub(p.id).put(info.comp, JSONObject()
|
state.sub("active").sub(p.id).put(info.comp, JSONObject()
|
||||||
@@ -803,6 +840,18 @@ object ComponentsManager {
|
|||||||
internal fun liveOnAny(key: String, entry: JSONObject, installs: List<Proton>?): Boolean =
|
internal fun liveOnAny(key: String, entry: JSONObject, installs: List<Proton>?): Boolean =
|
||||||
installs?.any { liveSelection(key, entry, it) } == true
|
installs?.any { liveSelection(key, entry, it) } == true
|
||||||
|
|
||||||
|
// An installed tool that launches with `name` as the stored twin of a game's FEX choice (a Linux choice on
|
||||||
|
// DroidDeck-Bionic, a -bionic one on another Proton): deleting the twin would drop that choice for that tool.
|
||||||
|
internal fun twinUser(state: JSONObject, installed: List<Proton>, name: String): Proton? {
|
||||||
|
val profiles = state.optJSONObject("profiles") ?: return null
|
||||||
|
for (scope in profiles.keys()) {
|
||||||
|
val chosen = profiles.optJSONObject(scope)?.optString("fex")?.takeIf { it.isNotEmpty() } ?: continue
|
||||||
|
if (fexTwin(chosen) != name) continue
|
||||||
|
installed.firstOrNull { !fexFits(it.dir.name, chosen) }?.let { return it }
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
internal fun packagesInUse(state: JSONObject, installed: List<Proton>): Set<String> {
|
internal fun packagesInUse(state: JSONObject, installed: List<Proton>): Set<String> {
|
||||||
val byId = installed.groupBy { it.id }
|
val byId = installed.groupBy { it.id }
|
||||||
val names = HashSet<String>()
|
val names = HashSet<String>()
|
||||||
@@ -819,7 +868,11 @@ object ComponentsManager {
|
|||||||
val profiles = state.optJSONObject("profiles")
|
val profiles = state.optJSONObject("profiles")
|
||||||
for (scope in profiles?.keys() ?: emptyList<String>().iterator()) {
|
for (scope in profiles?.keys() ?: emptyList<String>().iterator()) {
|
||||||
val profile = profiles?.optJSONObject(scope) ?: continue
|
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
|
return names
|
||||||
}
|
}
|
||||||
@@ -890,6 +943,7 @@ object ComponentsManager {
|
|||||||
val queued = state.sub("queued").sub(target.id)
|
val queued = state.sub("queued").sub(target.id)
|
||||||
var changed = false
|
var changed = false
|
||||||
wanted.forEach { (comp, entry) ->
|
wanted.forEach { (comp, entry) ->
|
||||||
|
if (comp == "fex" && !fexFits(target.dir.name, entry.optString("file"))) return@forEach
|
||||||
if (active?.has(comp) != true && !queued.has(comp)) {
|
if (active?.has(comp) != true && !queued.has(comp)) {
|
||||||
queued.put(comp, entry)
|
queued.put(comp, entry)
|
||||||
changed = true
|
changed = true
|
||||||
@@ -970,6 +1024,8 @@ object ComponentsManager {
|
|||||||
fun deletePackage(context: Context, file: String): String = synchronized(lock) {
|
fun deletePackage(context: Context, file: String): String = synchronized(lock) {
|
||||||
val name = safeName(file)
|
val name = safeName(file)
|
||||||
val state = loadState(context)
|
val state = loadState(context)
|
||||||
|
val twinTool = twinUser(state, protons(context), name)
|
||||||
|
check(twinTool == null) { context.getString(R.string.cmgr_package_in_use, name, twinTool?.name ?: "") }
|
||||||
val installed = protons(context).groupBy { it.id }
|
val installed = protons(context).groupBy { it.id }
|
||||||
var changed = false
|
var changed = false
|
||||||
for (key in listOf("queued", "active")) {
|
for (key in listOf("queued", "active")) {
|
||||||
@@ -1066,8 +1122,11 @@ object ComponentsManager {
|
|||||||
return Catalog(items, o.optLong("fetchedAt"))
|
return Catalog(items, o.optLong("fetchedAt"))
|
||||||
}
|
}
|
||||||
|
|
||||||
internal fun assetComp(release: String, name: String): String? =
|
internal fun assetComp(release: String, name: String): String? = RELEASES[release] ?: when (release) {
|
||||||
RELEASES[release] ?: if (release == DD_NIGHTLY) NIGHTLY_PREFIXES.entries.firstOrNull { name.startsWith(it.key) }?.value else null
|
DD_NIGHTLY -> NIGHTLY_PREFIXES.entries.firstOrNull { name.startsWith(it.key) }?.value
|
||||||
|
DD_BIONIC -> "fex"
|
||||||
|
else -> null
|
||||||
|
}
|
||||||
|
|
||||||
internal val CATALOG_ORDER: Comparator<CatalogItem> =
|
internal val CATALOG_ORDER: Comparator<CatalogItem> =
|
||||||
compareBy<CatalogItem> { it.comp }.thenBy { it.release == DD_NIGHTLY }.then(newestFirst { it.file })
|
compareBy<CatalogItem> { it.comp }.thenBy { it.release == DD_NIGHTLY }.then(newestFirst { it.file })
|
||||||
@@ -1155,6 +1214,25 @@ object ComponentsManager {
|
|||||||
return runCatching { readWcpEntry(original, rel) }.getOrNull()
|
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 =
|
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
|
if (comp == "fex") File(p.dir, FEX_FILES.first()).isFile else File(p.dir, "${COMP_DIR.getValue(comp)}/aarch64-windows").isDirectory
|
||||||
|
|
||||||
|
|||||||
@@ -937,7 +937,7 @@ internal object EnhancedSessionLogShare {
|
|||||||
val value = entry.lowercase(Locale.US)
|
val value = entry.lowercase(Locale.US)
|
||||||
if (value.startsWith("battlenet/") || value.startsWith("stores/") || value.startsWith("tools/") ||
|
if (value.startsWith("battlenet/") || value.startsWith("stores/") || value.startsWith("tools/") ||
|
||||||
value.contains("droiddeck-esync/") || GAME_LOG.matches(value.substringAfterLast('/')) ||
|
value.contains("droiddeck-esync/") || GAME_LOG.matches(value.substringAfterLast('/')) ||
|
||||||
listOf("proton", "wine", "dxvk", "vkd3d", "battle.net", "game-debug").any(value::contains)) return Category.GAMES
|
listOf("proton", "wine", "dxvk", "vkd3d", "battle.net", "game-debug", "bionic").any(value::contains)) return Category.GAMES
|
||||||
if (listOf("wayland", "gamescope", "xwayland", "vulkan", "gpu", "mesa", "egl", "glx", "drm", "compositor", "frame-trace").any(value::contains)) return Category.GRAPHICS
|
if (listOf("wayland", "gamescope", "xwayland", "vulkan", "gpu", "mesa", "egl", "glx", "drm", "compositor", "frame-trace").any(value::contains)) return Category.GRAPHICS
|
||||||
return Category.SESSION
|
return Category.SESSION
|
||||||
}
|
}
|
||||||
@@ -948,7 +948,7 @@ internal object EnhancedSessionLogShare {
|
|||||||
"droiddeck", "droiddeck-esync", "session.log", "app.log", "wayland.log", "audio.log",
|
"droiddeck", "droiddeck-esync", "session.log", "app.log", "wayland.log", "audio.log",
|
||||||
"device.txt", "network.txt", "events.jsonl", "memory.csv", "capture.json", "crash.log",
|
"device.txt", "network.txt", "events.jsonl", "memory.csv", "capture.json", "crash.log",
|
||||||
"frame-trace.log", "process-trace.log", "game-lifecycle.log", "launches.log", "tools.tsv", "wanted.tsv", "prefixes.json",
|
"frame-trace.log", "process-trace.log", "game-lifecycle.log", "launches.log", "tools.tsv", "wanted.tsv", "prefixes.json",
|
||||||
"battlenet.log", "spawned.log", "flatpak-install.log", "cef_log.txt", "cef_log.previous.txt",
|
"battlenet.log", "spawned.log", "flatpak-install.log", "cef_log.txt", "cef_log.previous.txt", "droiddeck-bionic.log",
|
||||||
"console_log.txt", "webhelper_js.txt", "controller_support.txt", "systemperfmanager.txt",
|
"console_log.txt", "webhelper_js.txt", "controller_support.txt", "systemperfmanager.txt",
|
||||||
)
|
)
|
||||||
private val KNOWN_COMPONENT_PATTERNS = listOf(
|
private val KNOWN_COMPONENT_PATTERNS = listOf(
|
||||||
|
|||||||
@@ -74,10 +74,16 @@ object ExperimentalProtons {
|
|||||||
return PREFIX + base + (tag?.let { "-$it" } ?: "")
|
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>? {
|
fun refresh(context: Context): List<Release>? {
|
||||||
val tool = ProtonExtras.tools.first { it.id == ProtonExtras.OWN }
|
val tool = ProtonExtras.tools.first { it.id == ProtonExtras.OWN }
|
||||||
val fetched = ProtonExtras.releasesForRemoval(tool) ?: return null
|
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 }
|
val rows = assets.map { Release(it.tag, it.name, it.url, it.sha512, it.size, it.releaseName) }.distinctBy { it.tag }
|
||||||
if (!SessionState.running) {
|
if (!SessionState.running) {
|
||||||
reconcile(context, fetched)
|
reconcile(context, fetched)
|
||||||
|
|||||||
@@ -14,7 +14,8 @@ object ProtonDefault {
|
|||||||
|
|
||||||
data class Tool(val name: String, val display: String, val dir: String, val valve: Boolean)
|
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 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)
|
data class GameChoice(val valve: Boolean, val dir: String)
|
||||||
|
|
||||||
enum class Outcome { LIVE, NEXT_START, NOT_RUNNABLE }
|
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"))
|
Tool(t.optString("name"), t.optString("display"), t.optString("dir"), t.optBoolean("valve"))
|
||||||
}?.takeIf { it.name.isNotEmpty() }
|
}?.takeIf { it.name.isNotEmpty() }
|
||||||
},
|
},
|
||||||
|
source = o.optString("source").ifEmpty { null },
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -99,7 +101,13 @@ object ProtonDefault {
|
|||||||
if (!runnable(state, proton)) return Outcome.NOT_RUNNABLE
|
if (!runnable(state, proton)) return Outcome.NOT_RUNNABLE
|
||||||
val d = dir(context)
|
val d = dir(context)
|
||||||
val seq = nextSeq(System.currentTimeMillis(), state, parseRequest(read(File(d, "request.json"))))
|
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")
|
val staged = File(d, "request.json.staged")
|
||||||
try {
|
try {
|
||||||
d.mkdirs()
|
d.mkdirs()
|
||||||
@@ -110,8 +118,45 @@ object ProtonDefault {
|
|||||||
Log.w(TAG, "could not write the Proton request", e)
|
Log.w(TAG, "could not write the Proton request", e)
|
||||||
throw 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?>? {
|
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.Downloader
|
||||||
import com.droiddeck.launcher.core.FileUtils
|
import com.droiddeck.launcher.core.FileUtils
|
||||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||||
|
import com.droiddeck.launcher.runtime.NativeGuest
|
||||||
import java.io.File
|
import java.io.File
|
||||||
import java.util.Locale
|
import java.util.Locale
|
||||||
import org.json.JSONArray
|
import org.json.JSONArray
|
||||||
@@ -27,20 +28,27 @@ object ProtonExtras {
|
|||||||
@Volatile
|
@Volatile
|
||||||
private var replacing = false
|
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,
|
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)
|
val sha256: String? = null, val releaseName: String = tag)
|
||||||
internal data class ReleaseFetch(val releases: JSONArray, val complete: Boolean)
|
internal data class ReleaseFetch(val releases: JSONArray, val complete: Boolean)
|
||||||
|
|
||||||
const val OWN = "droiddeck"
|
const val OWN = "droiddeck"
|
||||||
|
const val BIONIC = "bionic"
|
||||||
|
|
||||||
val tools = listOf(
|
val tools = listOf(
|
||||||
Tool("ge", "GE-Proton", "GE-Proton", "GloriousEggroll/proton-ge-custom", Regex("aarch64\\.tar\\.(gz|xz)$")),
|
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("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 home(context: Context) = File(LinuxRuntime.rootDir(context), "root")
|
||||||
private fun requests(context: Context) = File(home(context), ".dd-proton-extra")
|
private fun requests(context: Context) = File(home(context), ".dd-proton-extra")
|
||||||
private fun toolsDir(context: Context) = File(home(context), ".local/share/Steam/compatibilitytools.d")
|
private fun toolsDir(context: Context) = File(home(context), ".local/share/Steam/compatibilitytools.d")
|
||||||
@@ -115,10 +123,11 @@ object ProtonExtras {
|
|||||||
private var lastAttempt = 0L
|
private var lastAttempt = 0L
|
||||||
|
|
||||||
fun checkLatest(context: Context, force: Boolean = false, now: Long = System.currentTimeMillis()): Boolean {
|
fun checkLatest(context: Context, force: Boolean = false, now: Long = System.currentTimeMillis()): Boolean {
|
||||||
|
keepBionicCurrent(context)
|
||||||
synchronized(checkLock) {
|
synchronized(checkLock) {
|
||||||
val file = latestFile(context)
|
val file = latestFile(context)
|
||||||
val cache = readJson(file)
|
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
|
val at = cache.optJSONObject(tool.id)?.optLong("at", 0L) ?: 0L
|
||||||
force || (now - at) !in 0 until CHECK_EVERY_MS
|
force || (now - at) !in 0 until CHECK_EVERY_MS
|
||||||
}
|
}
|
||||||
@@ -168,15 +177,32 @@ object ProtonExtras {
|
|||||||
|
|
||||||
fun remove(context: Context, tool: Tool, dir: String? = null) {
|
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
|
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) {
|
fun removeOlder(context: Context, tool: Tool) {
|
||||||
installedAll(context, tool).dropLast(1).forEach {
|
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) {
|
private fun replaceOlder(context: Context, tool: Tool) {
|
||||||
val all = installedAll(context, tool)
|
val all = installedAll(context, tool)
|
||||||
val newest = all.lastOrNull() ?: return
|
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 { 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 { 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 (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")
|
else Log.w(TAG, "could not remove $old")
|
||||||
}
|
}
|
||||||
} finally {
|
} finally {
|
||||||
@@ -308,7 +336,7 @@ object ProtonExtras {
|
|||||||
archive.delete()
|
archive.delete()
|
||||||
unqueue(context, tool)
|
unqueue(context, tool)
|
||||||
record(context, tool, placed, asset.tag)
|
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)) {
|
if (EsyncPacks.enabled(context)) {
|
||||||
onProgress(context.getString(R.string.esync_fetching), -1)
|
onProgress(context.getString(R.string.esync_fetching), -1)
|
||||||
try {
|
try {
|
||||||
@@ -393,7 +421,7 @@ object ProtonExtras {
|
|||||||
internal fun pickAsset(tool: Tool, array: JSONArray): Asset? {
|
internal fun pickAsset(tool: Tool, array: JSONArray): Asset? {
|
||||||
val candidates = (0 until array.length()).asSequence()
|
val candidates = (0 until array.length()).asSequence()
|
||||||
.mapNotNull { array.optJSONObject(it) }
|
.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) }
|
return candidates.firstNotNullOfOrNull { assetOf(tool, it) }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -181,7 +181,6 @@ object SessionFiles {
|
|||||||
"usr/local/bin/droiddeck-appimage-run" to "usr/local/bin/droiddeck-appimage-run",
|
"usr/local/bin/droiddeck-appimage-run" to "usr/local/bin/droiddeck-appimage-run",
|
||||||
"usr/local/bin/droiddeck-appimage-exec" to "usr/local/bin/droiddeck-appimage-exec",
|
"usr/local/bin/droiddeck-appimage-exec" to "usr/local/bin/droiddeck-appimage-exec",
|
||||||
"usr/local/bin/droiddeck-curseforge" to "usr/local/bin/droiddeck-curseforge",
|
"usr/local/bin/droiddeck-curseforge" to "usr/local/bin/droiddeck-curseforge",
|
||||||
"usr/local/bin/droiddeck-headless" to "usr/local/bin/droiddeck-headless",
|
|
||||||
"usr/local/bin/droiddeck-script-run" to "usr/local/bin/droiddeck-script-run",
|
"usr/local/bin/droiddeck-script-run" to "usr/local/bin/droiddeck-script-run",
|
||||||
"usr/local/bin/droiddeck-open" to "usr/local/bin/droiddeck-open",
|
"usr/local/bin/droiddeck-open" to "usr/local/bin/droiddeck-open",
|
||||||
"usr/local/bin/droiddeck-proton-run" to "usr/local/bin/droiddeck-proton-run",
|
"usr/local/bin/droiddeck-proton-run" to "usr/local/bin/droiddeck-proton-run",
|
||||||
|
|||||||
@@ -1011,7 +1011,7 @@ object SessionPrefs {
|
|||||||
prefs(context).edit().putBoolean("prootNoSeccomp", on).apply()
|
prefs(context).edit().putBoolean("prootNoSeccomp", on).apply()
|
||||||
}
|
}
|
||||||
|
|
||||||
fun nativeUserland(context: Context): Boolean = prefs(context).getBoolean("nativeUserland", true)
|
fun nativeUserland(context: Context): Boolean = prefs(context).getBoolean("nativeUserland", false)
|
||||||
|
|
||||||
fun setNativeUserland(context: Context, on: Boolean) {
|
fun setNativeUserland(context: Context, on: Boolean) {
|
||||||
prefs(context).edit().putBoolean("nativeUserland", on).apply()
|
prefs(context).edit().putBoolean("nativeUserland", on).apply()
|
||||||
|
|||||||
@@ -1033,6 +1033,9 @@ class SessionService : Service() {
|
|||||||
)
|
)
|
||||||
(if (bridge || venus) null else LinuxVulkanDriver.resolveIcdPath(this, linuxDriverId))
|
(if (bridge || venus) null else LinuxVulkanDriver.resolveIcdPath(this, linuxDriverId))
|
||||||
?.let { guest.add(LinuxVulkanDriver.ENV + "=" + it) }
|
?.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()) {
|
if (!com.droiddeck.launcher.core.DeviceSupport.adreno() && lastXwaylandCrashed()) {
|
||||||
guest.add("XWAYLAND_NO_GLAMOR=1")
|
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)")
|
Log.w(TAG, "xwayland: the last session's Xwayland crashed; glamor off for this one (XWAYLAND_NO_GLAMOR=1)")
|
||||||
|
|||||||
@@ -12,8 +12,11 @@ object StoreLaunch {
|
|||||||
const val EPIC_CODE = ".droiddeck-epic-code"
|
const val EPIC_CODE = ".droiddeck-epic-code"
|
||||||
const val EPIC_ARGS = ".droiddeck-epic-args"
|
const val EPIC_ARGS = ".droiddeck-epic-args"
|
||||||
const val UBISOFT_LAUNCH = ".droiddeck-ubisoft.json"
|
const val UBISOFT_LAUNCH = ".droiddeck-ubisoft.json"
|
||||||
private const val UBISOFT_SERVICE = "Z:\\usr\\local\\lib\\droiddeck-ubisoft\\droiddeck-upc.exe"
|
/** DroidDeck-Bionic's Wine has Android's root on Z:; that tool sets this to the guest's root as its Wine names it. */
|
||||||
const val EPIC_PARENT = "Z:\\usr\\local\\lib\\droiddeck-epic\\EpicGamesLauncher.exe"
|
const val GUEST_ROOT = "DROIDDECK_GUEST_ROOT"
|
||||||
|
private const val ROOT_VAR = "DD_R"
|
||||||
|
private const val UBISOFT_SERVICE = "%$ROOT_VAR%\\usr\\local\\lib\\droiddeck-ubisoft\\droiddeck-upc.exe"
|
||||||
|
const val EPIC_PARENT = "%$ROOT_VAR%\\usr\\local\\lib\\droiddeck-epic\\EpicGamesLauncher.exe"
|
||||||
/** Per-game environment switch: 1 starts any Epic game under [EPIC_PARENT], 0 never does. */
|
/** Per-game environment switch: 1 starts any Epic game under [EPIC_PARENT], 0 never does. */
|
||||||
const val EPIC_PARENT_SWITCH = "DD_EPIC_PARENT"
|
const val EPIC_PARENT_SWITCH = "DD_EPIC_PARENT"
|
||||||
/** Epic app names whose launchers treat the game as unowned unless a process named EpicGamesLauncher.exe started it. */
|
/** Epic app names whose launchers treat the game as unowned unless a process named EpicGamesLauncher.exe started it. */
|
||||||
@@ -47,6 +50,10 @@ object StoreLaunch {
|
|||||||
for ((k, v) in sidecar.env) if (ENV_NAME.matches(k)) lines += "set \"$k=${v.replace("\"", "")}\""
|
for ((k, v) in sidecar.env) if (ENV_NAME.matches(k)) lines += "set \"$k=${v.replace("\"", "")}\""
|
||||||
val args = sidecar.args.joinToString(" ") { if (sidecar.store == Store.ROCKSTAR) batchArg(it) else quoteArg(it) }
|
val args = sidecar.args.joinToString(" ") { if (sidecar.store == Store.ROCKSTAR) batchArg(it) else quoteArg(it) }
|
||||||
val run = "\"%~dp0$exe\"" + (if (args.isNotEmpty()) " $args" else "")
|
val run = "\"%~dp0$exe\"" + (if (args.isNotEmpty()) " $args" else "")
|
||||||
|
if (sidecar.store == Store.EPIC || sidecar.store == Store.UBISOFT) {
|
||||||
|
lines += "set \"$ROOT_VAR=Z:\""
|
||||||
|
lines += "if defined $GUEST_ROOT set \"$ROOT_VAR=%$GUEST_ROOT%\""
|
||||||
|
}
|
||||||
if (sidecar.store == Store.EPIC) {
|
if (sidecar.store == Store.EPIC) {
|
||||||
lines += "set \"$PARENT_VAR=${if (sidecar.id in EPIC_PARENT_TITLES) "1" else ""}\""
|
lines += "set \"$PARENT_VAR=${if (sidecar.id in EPIC_PARENT_TITLES) "1" else ""}\""
|
||||||
lines += "if \"%$EPIC_PARENT_SWITCH%\"==\"1\" set \"$PARENT_VAR=1\""
|
lines += "if \"%$EPIC_PARENT_SWITCH%\"==\"1\" set \"$PARENT_VAR=1\""
|
||||||
@@ -137,7 +144,6 @@ object StoreLaunch {
|
|||||||
if (sidecar.store !in listOf(Store.UBISOFT, Store.ROCKSTAR) || !sidecar.isInstalled) return sidecar
|
if (sidecar.store !in listOf(Store.UBISOFT, Store.ROCKSTAR) || !sidecar.isInstalled) return sidecar
|
||||||
if (sidecar.store == Store.ROCKSTAR && java.nio.file.Files.isSymbolicLink(File(folder, LAUNCHER).toPath())) return sidecar.copy(launcher = null)
|
if (sidecar.store == Store.ROCKSTAR && java.nio.file.Files.isSymbolicLink(File(folder, LAUNCHER).toPath())) return sidecar.copy(launcher = null)
|
||||||
val wrongExe = !sidecar.exeFile(folder).isFile || sidecar.exe.contains("installer", ignoreCase = true) || sidecar.exe.contains("autorun", ignoreCase = true)
|
val wrongExe = !sidecar.exeFile(folder).isFile || sidecar.exe.contains("installer", ignoreCase = true) || sidecar.exe.contains("autorun", ignoreCase = true)
|
||||||
if (sidecar.store == Store.UBISOFT && sidecar.launcher == LAUNCHER && !wrongExe) return sidecar
|
|
||||||
val metadataExe = if (sidecar.store == Store.ROCKSTAR) com.droiddeck.launcher.stores.rockstar.RockstarMetadata.find(folder)?.exe
|
val metadataExe = if (sidecar.store == Store.ROCKSTAR) com.droiddeck.launcher.stores.rockstar.RockstarMetadata.find(folder)?.exe
|
||||||
?.takeIf { File(folder, it).isFile && File(folder, it).canonicalPath.startsWith(folder.canonicalPath + File.separator) } else null
|
?.takeIf { File(folder, it).isFile && File(folder, it).canonicalPath.startsWith(folder.canonicalPath + File.separator) } else null
|
||||||
val exe = metadataExe ?: if (wrongExe) StoreExe.pick(folder, null, sidecar.title).ifEmpty { sidecar.exe } else sidecar.exe
|
val exe = metadataExe ?: if (wrongExe) StoreExe.pick(folder, null, sidecar.title).ifEmpty { sidecar.exe } else sidecar.exe
|
||||||
|
|||||||
@@ -330,7 +330,7 @@ public final class GogDownloadManager {
|
|||||||
rc = GuestCommand.INSTANCE.run(ctx, Arrays.asList(
|
rc = GuestCommand.INSTANCE.run(ctx, Arrays.asList(
|
||||||
"/usr/local/bin/droiddeck-innoextract", "--gog", "--silent",
|
"/usr/local/bin/droiddeck-innoextract", "--gog", "--silent",
|
||||||
"-d", guestDir, guestSetup),
|
"-d", guestDir, guestSetup),
|
||||||
false, "gog-innoextract", null, null, false, cancelled, null,
|
false, "gog-innoextract", null, null, false, cancelled,
|
||||||
line -> { cb.onLog("gog innoextract: " + line); return kotlin.Unit.INSTANCE; });
|
line -> { cb.onLog("gog innoextract: " + line); return kotlin.Unit.INSTANCE; });
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
throw new InstallException("The installer could not be extracted: " + e.getClass().getSimpleName());
|
throw new InstallException("The installer could not be extracted: " + e.getClass().getSimpleName());
|
||||||
|
|||||||
@@ -37,7 +37,6 @@ import androidx.compose.runtime.mutableStateOf
|
|||||||
import androidx.compose.runtime.produceState
|
import androidx.compose.runtime.produceState
|
||||||
import androidx.compose.runtime.remember
|
import androidx.compose.runtime.remember
|
||||||
import androidx.compose.runtime.rememberCoroutineScope
|
import androidx.compose.runtime.rememberCoroutineScope
|
||||||
import androidx.compose.runtime.withFrameNanos
|
|
||||||
import androidx.compose.runtime.setValue
|
import androidx.compose.runtime.setValue
|
||||||
import androidx.compose.runtime.snapshotFlow
|
import androidx.compose.runtime.snapshotFlow
|
||||||
import androidx.compose.ui.Alignment
|
import androidx.compose.ui.Alignment
|
||||||
@@ -54,7 +53,6 @@ import androidx.compose.ui.input.InputMode
|
|||||||
import androidx.compose.ui.layout.ContentScale
|
import androidx.compose.ui.layout.ContentScale
|
||||||
import androidx.compose.ui.platform.LocalContext
|
import androidx.compose.ui.platform.LocalContext
|
||||||
import androidx.compose.ui.platform.LocalInputModeManager
|
import androidx.compose.ui.platform.LocalInputModeManager
|
||||||
import androidx.compose.ui.platform.LocalLifecycleOwner
|
|
||||||
import androidx.compose.ui.res.stringResource
|
import androidx.compose.ui.res.stringResource
|
||||||
import androidx.compose.ui.text.font.FontWeight
|
import androidx.compose.ui.text.font.FontWeight
|
||||||
import androidx.compose.ui.text.input.ImeAction
|
import androidx.compose.ui.text.input.ImeAction
|
||||||
@@ -62,8 +60,6 @@ import androidx.compose.ui.text.input.KeyboardType
|
|||||||
import androidx.compose.ui.text.style.TextOverflow
|
import androidx.compose.ui.text.style.TextOverflow
|
||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
import androidx.compose.ui.unit.sp
|
import androidx.compose.ui.unit.sp
|
||||||
import androidx.lifecycle.Lifecycle
|
|
||||||
import androidx.lifecycle.LifecycleEventObserver
|
|
||||||
import coil.compose.AsyncImage
|
import coil.compose.AsyncImage
|
||||||
import com.droiddeck.launcher.R
|
import com.droiddeck.launcher.R
|
||||||
import com.droiddeck.launcher.frontend.AddedGames
|
import com.droiddeck.launcher.frontend.AddedGames
|
||||||
@@ -71,19 +67,14 @@ import com.droiddeck.launcher.runtime.CurseForgeApp
|
|||||||
import com.droiddeck.launcher.runtime.UserApps
|
import com.droiddeck.launcher.runtime.UserApps
|
||||||
import com.droiddeck.launcher.runtime.WowAddonCatalog
|
import com.droiddeck.launcher.runtime.WowAddonCatalog
|
||||||
import com.droiddeck.launcher.runtime.WowAddons
|
import com.droiddeck.launcher.runtime.WowAddons
|
||||||
|
import com.droiddeck.launcher.session.BackgroundSession
|
||||||
|
import com.droiddeck.launcher.session.SessionService
|
||||||
import com.droiddeck.launcher.session.SessionState
|
import com.droiddeck.launcher.session.SessionState
|
||||||
import kotlinx.coroutines.CoroutineScope
|
|
||||||
import kotlinx.coroutines.Dispatchers
|
import kotlinx.coroutines.Dispatchers
|
||||||
import kotlinx.coroutines.Job
|
|
||||||
import kotlinx.coroutines.SupervisorJob
|
|
||||||
import kotlinx.coroutines.delay
|
import kotlinx.coroutines.delay
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
import kotlinx.coroutines.withContext
|
import kotlinx.coroutines.withContext
|
||||||
import java.io.File
|
import java.io.File
|
||||||
import java.io.IOException
|
|
||||||
import java.util.concurrent.ConcurrentHashMap
|
|
||||||
import java.util.concurrent.atomic.AtomicBoolean
|
|
||||||
import java.util.concurrent.atomic.AtomicReference
|
|
||||||
|
|
||||||
private class AddonResults {
|
private class AddonResults {
|
||||||
val items = mutableStateListOf<WowAddonCatalog.Addon>()
|
val items = mutableStateListOf<WowAddonCatalog.Addon>()
|
||||||
@@ -93,46 +84,26 @@ private class AddonResults {
|
|||||||
var more by mutableStateOf(false)
|
var more by mutableStateOf(false)
|
||||||
}
|
}
|
||||||
|
|
||||||
internal enum class AddonStatus { INSTALL, UPDATE, INSTALLED }
|
private enum class AddonStatus { INSTALL, UPDATE, INSTALLED }
|
||||||
|
|
||||||
private enum class AddonSource { WOWI, CURSE }
|
private enum class AddonSource { WOWI, CURSE }
|
||||||
|
|
||||||
internal class CurseState(val notice: Int? = null) : Exception()
|
private class CurseState(val notice: Int? = null) : Exception()
|
||||||
|
|
||||||
internal class CurseLink(val app: UserApps.App) {
|
private class CurseLink(val app: UserApps.App) {
|
||||||
class Linked(val inspector: String, val guid: String)
|
class Linked(val inspector: String, val guid: String)
|
||||||
|
|
||||||
private val lock = Object()
|
private val lock = Object()
|
||||||
private val work = SupervisorJob()
|
|
||||||
@Volatile private var closed = false
|
@Volatile private var closed = false
|
||||||
@Volatile private var hold: AtomicBoolean? = null
|
private var held = false
|
||||||
|
private var ownSession: String? = null
|
||||||
|
private var started = false
|
||||||
|
@Volatile private var launching = false
|
||||||
@Volatile private var inspector: String? = null
|
@Volatile private var inspector: String? = null
|
||||||
private val guids = HashMap<String, String>()
|
private val guids = HashMap<String, String>()
|
||||||
private val scanLock = Object()
|
|
||||||
private val scans = HashMap<String, Pair<Any, List<CurseForgeApp.Project>>>()
|
|
||||||
var generation by mutableIntStateOf(0)
|
|
||||||
private set
|
|
||||||
|
|
||||||
fun refresh() {
|
fun <T> call(context: Context, target: WowAddons.Target, block: (Linked) -> T): T {
|
||||||
generation++
|
val linked = synchronized(lock) { link(context, target) }
|
||||||
}
|
|
||||||
|
|
||||||
fun installed(context: Context, target: WowAddons.Target, key: Any): List<CurseForgeApp.Project> = CurseForgeApp.onDisk(
|
|
||||||
synchronized(scanLock) {
|
|
||||||
scans[target.addOns.path]?.takeIf { it.first == key }?.second
|
|
||||||
?: call(context, target) { CurseForgeApp.projects(context, it.inspector, it.guid, rescan = true) }.also {
|
|
||||||
scans[target.addOns.path] = key to it
|
|
||||||
report(target, it)
|
|
||||||
}
|
|
||||||
},
|
|
||||||
target.addOns,
|
|
||||||
)
|
|
||||||
|
|
||||||
fun marks(context: Context, target: WowAddons.Target, key: Any): Map<String, String?> =
|
|
||||||
runCatching { installed(context, target, key).associate { it.id to curseMark(it) } }.getOrElse { lastReported(target) }
|
|
||||||
|
|
||||||
fun <T> call(context: Context, target: WowAddons.Target, launch: Boolean = true, block: (Linked) -> T): T {
|
|
||||||
val linked = synchronized(lock) { link(context, target, launch) }
|
|
||||||
try {
|
try {
|
||||||
return block(linked)
|
return block(linked)
|
||||||
} catch (e: CurseForgeApp.Failure) {
|
} catch (e: CurseForgeApp.Failure) {
|
||||||
@@ -140,25 +111,38 @@ internal class CurseLink(val app: UserApps.App) {
|
|||||||
if (inspector == linked.inspector) {
|
if (inspector == linked.inspector) {
|
||||||
inspector = null
|
inspector = null
|
||||||
guids.clear()
|
guids.clear()
|
||||||
current.compareAndSet(this, null)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
throw e
|
throw e
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun link(context: Context, target: WowAddons.Target, launch: Boolean): Linked {
|
private fun link(context: Context, target: WowAddons.Target): Linked {
|
||||||
if (closed) throw CurseState()
|
if (closed) throw CurseState()
|
||||||
|
if (!SessionState.running) {
|
||||||
|
started = false
|
||||||
|
launching = false
|
||||||
|
held = false
|
||||||
|
ownSession = null
|
||||||
|
inspector = null
|
||||||
|
guids.clear()
|
||||||
|
val args = CurseForgeApp.holdArgs(app) ?: throw CurseState()
|
||||||
|
ownSession = BackgroundSession.start(context, CurseForgeApp.HELPER, args) ?: throw CurseState()
|
||||||
|
}
|
||||||
|
if (closed) throw CurseState()
|
||||||
|
if (!held) {
|
||||||
|
held = true
|
||||||
|
SessionService.holdForSignIn(context, true)
|
||||||
|
}
|
||||||
|
val awake = System.currentTimeMillis() + 30_000
|
||||||
|
while ((SessionState.suspended || SessionState.suspending) && System.currentTimeMillis() < awake) Thread.sleep(250)
|
||||||
val url = inspector ?: run {
|
val url = inspector ?: run {
|
||||||
if (!launch) throw CurseState()
|
launching = true
|
||||||
val hold = AtomicBoolean(false)
|
val done = CurseForgeApp.start(context, app)
|
||||||
this.hold = hold
|
|
||||||
if (closed) throw CurseState()
|
|
||||||
val done = CurseForgeApp.start(context, app, hold)
|
|
||||||
when (done.state) {
|
when (done.state) {
|
||||||
CurseForgeApp.Start.READY -> {
|
CurseForgeApp.Start.READY -> {
|
||||||
|
started = true
|
||||||
inspector = done.inspector
|
inspector = done.inspector
|
||||||
if (!closed) current.set(this)
|
|
||||||
done.inspector ?: throw CurseState()
|
done.inspector ?: throw CurseState()
|
||||||
}
|
}
|
||||||
CurseForgeApp.Start.BUSY -> throw CurseState(R.string.addons_curse_busy)
|
CurseForgeApp.Start.BUSY -> throw CurseState(R.string.addons_curse_busy)
|
||||||
@@ -174,76 +158,29 @@ internal class CurseLink(val app: UserApps.App) {
|
|||||||
return Linked(url, guid)
|
return Linked(url, guid)
|
||||||
}
|
}
|
||||||
|
|
||||||
fun uninstall(context: Context, target: WowAddons.Target, folder: String): Boolean = call(context, target, launch = false) { linked ->
|
fun close(context: Context) {
|
||||||
val projects = CurseForgeApp.onDisk(CurseForgeApp.projects(context, linked.inspector, linked.guid), target.addOns)
|
|
||||||
val project = CurseForgeApp.owner(projects, folder) ?: return@call false
|
|
||||||
if (!CurseForgeApp.uninstall(context, linked.inspector, linked.guid, project)) throw CurseState()
|
|
||||||
true
|
|
||||||
}
|
|
||||||
|
|
||||||
internal val stopped: Job get() = work
|
|
||||||
|
|
||||||
fun close(context: Context): Job {
|
|
||||||
closed = true
|
closed = true
|
||||||
current.compareAndSet(this, null)
|
Thread {
|
||||||
val launch = hold
|
if (launching) CurseForgeApp.stop(context, app, inspector)
|
||||||
return CoroutineScope(work + Dispatchers.IO).launch {
|
|
||||||
if (launch != null) CurseForgeApp.stop(context, app, inspector, launch)
|
|
||||||
synchronized(lock) {
|
synchronized(lock) {
|
||||||
hold = null
|
if (started) CurseForgeApp.stop(context, app, inspector)
|
||||||
|
val owned = ownSession
|
||||||
|
if (owned != null) BackgroundSession.stop(context, owned)
|
||||||
|
else if (held) SessionService.holdForSignIn(context, false)
|
||||||
|
started = false
|
||||||
|
launching = false
|
||||||
|
ownSession = null
|
||||||
|
held = false
|
||||||
inspector = null
|
inspector = null
|
||||||
}
|
}
|
||||||
}.also { work.complete() }
|
}.start()
|
||||||
}
|
|
||||||
|
|
||||||
companion object {
|
|
||||||
private val current = AtomicReference<CurseLink?>()
|
|
||||||
private val reported = ConcurrentHashMap<String, List<CurseForgeApp.Project>>()
|
|
||||||
|
|
||||||
fun lastReported(target: WowAddons.Target, disk: () -> List<WowAddons.Installed> = { WowAddons.details(target) }): Map<String, String?> {
|
|
||||||
val last = reported[target.addOns.path] ?: return disk().mapNotNull { it.curseId }.associateWith { null }
|
|
||||||
return CurseForgeApp.onDisk(last, target.addOns).associate { it.id to null }
|
|
||||||
}
|
|
||||||
|
|
||||||
internal fun report(target: WowAddons.Target, projects: List<CurseForgeApp.Project>) {
|
|
||||||
reported[target.addOns.path] = projects
|
|
||||||
}
|
|
||||||
|
|
||||||
fun live(): CurseLink? = current.get()
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private const val PAGES_AHEAD = 8
|
private const val PAGES_AHEAD = 8
|
||||||
private const val CURSE_UPDATE = "update"
|
|
||||||
private const val UNINSTALLING = -1
|
|
||||||
|
|
||||||
private fun curseMark(project: CurseForgeApp.Project): String? = CURSE_UPDATE.takeIf { project.update }
|
|
||||||
|
|
||||||
private class Present(val curse: Map<String, String?> = emptyMap(), val disk: Map<String, WowAddons.Installed> = emptyMap())
|
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
internal fun rememberCurseLink(app: UserApps.App?, sessionRunning: Boolean): CurseLink? {
|
internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAddons.Target, curseForge: UserApps.App?, onDismiss: () -> Unit) {
|
||||||
val context = LocalContext.current.applicationContext
|
|
||||||
val owner = LocalLifecycleOwner.current
|
|
||||||
var visible by remember(owner) { mutableStateOf(owner.lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED)) }
|
|
||||||
DisposableEffect(owner) {
|
|
||||||
val observer = LifecycleEventObserver { _, event ->
|
|
||||||
if (event == Lifecycle.Event.ON_START) visible = true
|
|
||||||
if (event == Lifecycle.Event.ON_STOP) visible = false
|
|
||||||
}
|
|
||||||
owner.lifecycle.addObserver(observer)
|
|
||||||
onDispose { owner.lifecycle.removeObserver(observer) }
|
|
||||||
}
|
|
||||||
val active = visible && !sessionRunning
|
|
||||||
val link = remember(app?.key, active) { app?.takeIf { active }?.let(::CurseLink) }
|
|
||||||
DisposableEffect(link) {
|
|
||||||
onDispose { link?.close(context) }
|
|
||||||
}
|
|
||||||
return link
|
|
||||||
}
|
|
||||||
|
|
||||||
@Composable
|
|
||||||
internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAddons.Target, curseForge: UserApps.App?, link: CurseLink?, onDismiss: () -> Unit) {
|
|
||||||
val context = LocalContext.current.applicationContext
|
val context = LocalContext.current.applicationContext
|
||||||
val scope = rememberCoroutineScope()
|
val scope = rememberCoroutineScope()
|
||||||
val shown = rememberShown(onDismiss)
|
val shown = rememberShown(onDismiss)
|
||||||
@@ -253,8 +190,11 @@ internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAdd
|
|||||||
var category by remember { mutableStateOf<WowAddonCatalog.Category?>(null) }
|
var category by remember { mutableStateOf<WowAddonCatalog.Category?>(null) }
|
||||||
var sort by remember { mutableStateOf(WowAddonCatalog.Sort.POPULAR) }
|
var sort by remember { mutableStateOf(WowAddonCatalog.Sort.POPULAR) }
|
||||||
var source by remember { mutableStateOf(AddonSource.WOWI) }
|
var source by remember { mutableStateOf(AddonSource.WOWI) }
|
||||||
val curse = if (source == AddonSource.CURSE && link != null) curseForge else null
|
val curse = if (source == AddonSource.CURSE) curseForge else null
|
||||||
LaunchedEffect(link) { link?.refresh() }
|
val link = remember(curseForge?.key) { curseForge?.let(::CurseLink) }
|
||||||
|
DisposableEffect(link) {
|
||||||
|
onDispose { link?.close(context) }
|
||||||
|
}
|
||||||
var notice by remember { mutableStateOf<Int?>(null) }
|
var notice by remember { mutableStateOf<Int?>(null) }
|
||||||
var curseInstalls by remember { mutableIntStateOf(0) }
|
var curseInstalls by remember { mutableIntStateOf(0) }
|
||||||
val results = remember(text, category, sort, target, curse) { AddonResults() }
|
val results = remember(text, category, sort, target, curse) { AddonResults() }
|
||||||
@@ -264,21 +204,20 @@ internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAdd
|
|||||||
value = withContext(Dispatchers.IO) { runCatching { WowAddonCatalog.categories(context) }.getOrDefault(emptyList()) }
|
value = withContext(Dispatchers.IO) { runCatching { WowAddonCatalog.categories(context) }.getOrDefault(emptyList()) }
|
||||||
}
|
}
|
||||||
val presentKey = curse to target.addOns
|
val presentKey = curse to target.addOns
|
||||||
val scanKey = link?.generation to WowAddons.imports
|
val snapshot by produceState(presentKey to emptyMap<String, String?>(), target.addOns, WowAddons.imports, curse, curseInstalls, results.items.isEmpty()) {
|
||||||
val snapshot by produceState(presentKey to Present(), target.addOns, scanKey, curse, curseInstalls, curse == null && results.items.isEmpty()) {
|
|
||||||
val into = target
|
val into = target
|
||||||
val key = curse to into.addOns
|
val key = curse to into.addOns
|
||||||
if (curse != null && link != null && value.first != key) value = key to withContext(Dispatchers.IO) { Present(curse = CurseLink.lastReported(into)) }
|
|
||||||
value = key to withContext(Dispatchers.IO) {
|
value = key to withContext(Dispatchers.IO) {
|
||||||
if (curse != null && link != null) Present(curse = link.marks(context, into, scanKey))
|
if (curse != null && link != null) runCatching { link.call(context, into) { CurseForgeApp.installed(context, it.inspector, it.guid) }.associateWith { null } }.getOrDefault(emptyMap())
|
||||||
else Present(disk = WowAddons.details(into).associateBy { it.name.lowercase() })
|
else WowAddons.details(into).mapNotNull { item -> item.wowiId?.let { it to item.version } }.toMap()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
val present = snapshot.second.takeIf { snapshot.first == presentKey } ?: Present()
|
val present = snapshot.second.takeIf { snapshot.first == presentKey } ?: emptyMap()
|
||||||
fun status(addon: WowAddonCatalog.Addon): AddonStatus {
|
fun status(addon: WowAddonCatalog.Addon): AddonStatus {
|
||||||
if (curse != null) return if (addon.id !in present.curse) AddonStatus.INSTALL else if (present.curse[addon.id] == CURSE_UPDATE) AddonStatus.UPDATE else AddonStatus.INSTALLED
|
if (addon.id !in present) return AddonStatus.INSTALL
|
||||||
|
val have = present[addon.id]
|
||||||
val latest = installed[installKey(addon, target)]?.takeIf { it.first == addon.summary }?.second ?: addon.summary
|
val latest = installed[installKey(addon, target)]?.takeIf { it.first == addon.summary }?.second ?: addon.summary
|
||||||
return diskStatus(addon.folders, present.disk, latest, addon.id)
|
return if (have == null || latest.isBlank() || WowAddonCatalog.sameVersion(have, latest)) AddonStatus.INSTALLED else AddonStatus.UPDATE
|
||||||
}
|
}
|
||||||
fun load(page: Int) {
|
fun load(page: Int) {
|
||||||
if (results.loading) return
|
if (results.loading) return
|
||||||
@@ -317,23 +256,16 @@ internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAdd
|
|||||||
val via = link?.takeIf { curse != null }
|
val via = link?.takeIf { curse != null }
|
||||||
if (via != null) {
|
if (via != null) {
|
||||||
val into = target
|
val into = target
|
||||||
val updating = status(addon) == AddonStatus.UPDATE
|
|
||||||
installing[key] = 0
|
installing[key] = 0
|
||||||
scope.launch {
|
scope.launch {
|
||||||
val done = withContext(Dispatchers.IO) {
|
val done = withContext(Dispatchers.IO) { runCatching { via.call(context, into) { CurseForgeApp.install(context, it.inspector, it.guid, addon.id) } } }
|
||||||
runCatching {
|
|
||||||
via.call(context, into) {
|
|
||||||
if (updating) CurseForgeApp.update(context, it.inspector, it.guid, addon.id)
|
|
||||||
else CurseForgeApp.install(context, it.inspector, it.guid, addon.id)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
installing.remove(key)
|
installing.remove(key)
|
||||||
val ok = done.getOrNull() == true
|
val ok = done.getOrNull() == true
|
||||||
WowAddons.changed()
|
if (ok) {
|
||||||
curseInstalls++
|
WowAddons.changed()
|
||||||
|
curseInstalls++
|
||||||
|
}
|
||||||
val message = when {
|
val message = when {
|
||||||
ok && updating -> context.getString(R.string.user_apps_updated, addon.name)
|
|
||||||
ok -> context.resources.getQuantityString(R.plurals.main_addons_imported, 1, 1, into.flavor)
|
ok -> context.resources.getQuantityString(R.plurals.main_addons_imported, 1, 1, into.flavor)
|
||||||
else -> (done.exceptionOrNull() as? CurseState)?.notice?.let(context::getString)
|
else -> (done.exceptionOrNull() as? CurseState)?.notice?.let(context::getString)
|
||||||
?: context.getString(R.string.stores_dl_failed_reason, done.exceptionOrNull()?.message ?: addon.name)
|
?: context.getString(R.string.stores_dl_failed_reason, done.exceptionOrNull()?.message ?: addon.name)
|
||||||
@@ -355,32 +287,6 @@ internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAdd
|
|||||||
Toast.makeText(context, message.first, Toast.LENGTH_LONG).show()
|
Toast.makeText(context, message.first, Toast.LENGTH_LONG).show()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
fun uninstall(addon: WowAddonCatalog.Addon) {
|
|
||||||
val key = installKey(addon, target)
|
|
||||||
if (key in installing) return
|
|
||||||
if (SessionState.running) {
|
|
||||||
Toast.makeText(context, R.string.main_addons_close_session, Toast.LENGTH_LONG).show()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
val into = target
|
|
||||||
val via = link?.takeIf { curse != null }
|
|
||||||
installing[key] = UNINSTALLING
|
|
||||||
scope.launch {
|
|
||||||
val done = withContext(Dispatchers.IO) {
|
|
||||||
runCatching {
|
|
||||||
val folders = if (via != null) curseFolders(into, addon.id, via.call(context, into) { linked ->
|
|
||||||
CurseForgeApp.projects(context, linked.inspector, linked.guid).firstOrNull { it.id == addon.id }?.folders.orEmpty()
|
|
||||||
}) else addon.folders
|
|
||||||
deleteAddons(context, into, folders, link)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
installing.remove(key)
|
|
||||||
installed.remove(key)
|
|
||||||
WowAddons.changed()
|
|
||||||
curseInstalls++
|
|
||||||
if (done.isFailure) Toast.makeText(context, R.string.fm_delete_failed, Toast.LENGTH_LONG).show()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
val sourceName = stringResource(if (curse != null) R.string.addons_source_curse else R.string.addons_source_wowi)
|
val sourceName = stringResource(if (curse != null) R.string.addons_source_curse else R.string.addons_source_wowi)
|
||||||
val grid = rememberLazyGridState()
|
val grid = rememberLazyGridState()
|
||||||
LaunchedEffect(results, grid) {
|
LaunchedEffect(results, grid) {
|
||||||
@@ -462,7 +368,7 @@ internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAdd
|
|||||||
) {
|
) {
|
||||||
items(results.items, key = { it.id }) { addon ->
|
items(results.items, key = { it.id }) { addon ->
|
||||||
val key = installKey(addon, target)
|
val key = installKey(addon, target)
|
||||||
AddonRow(addon, status(addon), installing[key], if (addon.id == results.items.firstOrNull()?.id) Modifier.focusRequester(firstAction) else Modifier, { uninstall(addon) }) { install(addon) }
|
AddonRow(addon, status(addon), installing[key], if (addon.id == results.items.firstOrNull()?.id) Modifier.focusRequester(firstAction) else Modifier) { install(addon) }
|
||||||
}
|
}
|
||||||
item(span = { GridItemSpan(maxLineSpan) }) {
|
item(span = { GridItemSpan(maxLineSpan) }) {
|
||||||
Column(Modifier.fillMaxWidth().padding(vertical = 8.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
Column(Modifier.fillMaxWidth().padding(vertical = 8.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
@@ -485,22 +391,7 @@ internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAdd
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
internal fun AddonRow(addon: WowAddonCatalog.Addon, status: AddonStatus, progress: Int?, action: Modifier, onUninstall: () -> Unit, onInstall: () -> Unit) {
|
private fun AddonRow(addon: WowAddonCatalog.Addon, status: AddonStatus, progress: Int?, action: Modifier, onInstall: () -> Unit) {
|
||||||
var asking by remember(addon.id) { mutableStateOf(false) }
|
|
||||||
val first = remember(addon.id) { FocusRequester() }
|
|
||||||
var refocus by remember(addon.id) { mutableStateOf(false) }
|
|
||||||
val inputMode = LocalInputModeManager.current
|
|
||||||
LaunchedEffect(status, progress) {
|
|
||||||
if (!refocus) return@LaunchedEffect
|
|
||||||
withFrameNanos { }
|
|
||||||
runCatching { first.requestFocus() }
|
|
||||||
if (progress == null) refocus = false
|
|
||||||
}
|
|
||||||
fun act(block: () -> Unit) {
|
|
||||||
refocus = inputMode.inputMode == InputMode.Keyboard
|
|
||||||
block()
|
|
||||||
}
|
|
||||||
val lead = action.focusRequester(first)
|
|
||||||
val colors = MaterialTheme.colorScheme
|
val colors = MaterialTheme.colorScheme
|
||||||
val pal = LocalPalette.current
|
val pal = LocalPalette.current
|
||||||
Row(
|
Row(
|
||||||
@@ -518,24 +409,13 @@ internal fun AddonRow(addon: WowAddonCatalog.Addon, status: AddonStatus, progres
|
|||||||
fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis,
|
fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
val uninstall = stringResource(R.string.common_uninstall)
|
val size = action
|
||||||
when {
|
when {
|
||||||
progress == UNINSTALLING -> SecondaryButton(stringResource(R.string.stores_uninstalling), compact = true, modifier = lead) {}
|
progress != null -> SecondaryButton(stringResource(R.string.store_installing), compact = true, modifier = size, progress = progress / 100f, onClick = onInstall)
|
||||||
progress != null -> SecondaryButton(stringResource(R.string.store_installing), compact = true, modifier = lead, progress = progress / 100f, onClick = onInstall)
|
status == AddonStatus.INSTALLED -> SecondaryButton(stringResource(R.string.stores_installed_chip), enabled = false, compact = true, modifier = size) {}
|
||||||
status == AddonStatus.INSTALL -> PrimaryButton(stringResource(R.string.store_install), compact = true, modifier = lead) { act(onInstall) }
|
else -> PrimaryButton(stringResource(if (status == AddonStatus.UPDATE) R.string.common_update else R.string.store_install), compact = true, modifier = size, onClick = onInstall)
|
||||||
else -> {
|
|
||||||
if (status == AddonStatus.UPDATE) PrimaryButton(stringResource(R.string.common_update), compact = true, modifier = lead) { act(onInstall) }
|
|
||||||
SecondaryButton(uninstall, compact = true, modifier = if (status == AddonStatus.UPDATE) Modifier else lead) { asking = true }
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (asking) ConfirmDialog(
|
|
||||||
title = stringResource(R.string.stores_uninstall_title, addon.name),
|
|
||||||
text = stringResource(R.string.games_delete_addon_body),
|
|
||||||
confirm = stringResource(R.string.common_uninstall),
|
|
||||||
onConfirm = { asking = false; act(onUninstall) },
|
|
||||||
onDismiss = { asking = false },
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun Modifier.scrollThumb(state: LazyGridState, color: Color): Modifier = drawWithContent {
|
private fun Modifier.scrollThumb(state: LazyGridState, color: Color): Modifier = drawWithContent {
|
||||||
@@ -584,25 +464,4 @@ internal fun installAddon(context: Context, addon: WowAddonCatalog.Addon, target
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
internal fun diskStatus(folders: List<String>, onDisk: Map<String, WowAddons.Installed>, latest: String, id: String): AddonStatus {
|
|
||||||
if (!WowAddons.present(folders) { it.lowercase() in onDisk }) return AddonStatus.INSTALL
|
|
||||||
val have = onDisk.getValue(folders.first().lowercase())
|
|
||||||
return if (WowAddonCatalog.offersUpdate(have.version, latest, sameSource = have.wowiId == id)) AddonStatus.UPDATE else AddonStatus.INSTALLED
|
|
||||||
}
|
|
||||||
|
|
||||||
internal fun curseFolders(target: WowAddons.Target, id: String, listed: List<String>): List<String> =
|
|
||||||
listed.ifEmpty { WowAddons.details(target).filter { it.curseId == id }.map { it.name } }
|
|
||||||
|
|
||||||
internal fun deleteAddons(context: Context, target: WowAddons.Target, folders: List<String>, link: CurseLink?) {
|
|
||||||
val found = folders.mapNotNull { WowAddons.folder(target.addOns, it) }
|
|
||||||
if (found.isEmpty()) throw IOException("No addon folder to delete")
|
|
||||||
found.forEach { deleteAddon(context, target, it.name, link) }
|
|
||||||
}
|
|
||||||
|
|
||||||
internal fun deleteAddon(context: Context, target: WowAddons.Target, folder: String, link: CurseLink? = CurseLink.live()) {
|
|
||||||
val managed = link?.let { runCatching { it.uninstall(context, target, folder) }.getOrDefault(false) } == true
|
|
||||||
val left = WowAddons.folder(target.addOns, folder)
|
|
||||||
if (managed || left == null) WowAddons.changed() else WowAddons.delete(target, left.name)
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun installKey(addon: WowAddonCatalog.Addon, target: WowAddons.Target) = addon.id + "|" + target.addOns.path
|
private fun installKey(addon: WowAddonCatalog.Addon, target: WowAddons.Target) = addon.id + "|" + target.addOns.path
|
||||||
@@ -526,11 +526,11 @@ fun ComponentsPage(
|
|||||||
val availableTitle: @Composable (String) -> String = { l ->
|
val availableTitle: @Composable (String) -> String = { l ->
|
||||||
when (l) {
|
when (l) {
|
||||||
PROTON_TAB -> stringResource(R.string.comp_available_count, protons.rows.count(ProtonRow::available))
|
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 followed: (String) -> Boolean = { l -> view?.proton?.let { ComponentUpdates.autoFollows(it, l) } == true }
|
||||||
val moded: (String) -> Boolean = { followed && it in compModes && it !in compAutoHeld && !ComponentsManager.runtimeManaged(it, gpu.systemPowerVr) }
|
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 automatic: (String) -> Boolean = { moded(it) && compModes[it] == ComponentUpdates.AUTO }
|
||||||
val installedRows: @Composable ColumnScope.(String, Boolean) -> Unit = { l, right ->
|
val installedRows: @Composable ColumnScope.(String, Boolean) -> Unit = { l, right ->
|
||||||
when (l) {
|
when (l) {
|
||||||
@@ -614,7 +614,7 @@ fun ComponentsPage(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
else -> {
|
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))
|
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) {
|
for ((stable, nightly) in available) {
|
||||||
val d = if (nightly != null && nightlyPicked[stable.file] == true) nightly else stable
|
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) },
|
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,
|
"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)
|
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()
|
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?>> {
|
private fun availableRows(l: String, catalog: List<CatalogItem>, snapshot: Snapshot?, toolDir: String?): List<Pair<CatalogItem, CatalogItem?>> {
|
||||||
val available = availableFor(l, catalog, snapshot)
|
val available = availableFor(l, catalog, snapshot, toolDir)
|
||||||
val pairs = ComponentsManager.nightlyPairs(available)
|
val pairs = ComponentsManager.nightlyPairs(available)
|
||||||
val paired = pairs.values.toSet()
|
val paired = pairs.values.toSet()
|
||||||
return available.filter { it !in paired }.map { it to pairs[it] }
|
return available.filter { it !in paired }.map { it to pairs[it] }
|
||||||
@@ -1201,7 +1201,7 @@ private fun GameComponentOverrides(
|
|||||||
}
|
}
|
||||||
GamePackageRow(
|
GamePackageRow(
|
||||||
comp = "fex",
|
comp = "fex",
|
||||||
packages = packages,
|
packages = ComponentsManager.forTool("fex", protonChoice?.dir ?: generalProton?.dir?.name, packages, componentChoices["fex"]) { it.file },
|
||||||
selectedFile = componentChoices["fex"],
|
selectedFile = componentChoices["fex"],
|
||||||
open = componentMenu == "fex",
|
open = componentMenu == "fex",
|
||||||
busy = busy,
|
busy = busy,
|
||||||
|
|||||||
@@ -33,9 +33,7 @@ import androidx.compose.ui.graphics.drawscope.translate
|
|||||||
import androidx.compose.ui.graphics.lerp
|
import androidx.compose.ui.graphics.lerp
|
||||||
import androidx.compose.ui.hapticfeedback.HapticFeedbackType
|
import androidx.compose.ui.hapticfeedback.HapticFeedbackType
|
||||||
import androidx.compose.ui.input.pointer.pointerInput
|
import androidx.compose.ui.input.pointer.pointerInput
|
||||||
import androidx.compose.ui.layout.onGloballyPositioned
|
|
||||||
import androidx.compose.ui.layout.onSizeChanged
|
import androidx.compose.ui.layout.onSizeChanged
|
||||||
import androidx.compose.ui.layout.positionInRoot
|
|
||||||
import androidx.compose.ui.platform.LocalDensity
|
import androidx.compose.ui.platform.LocalDensity
|
||||||
import androidx.compose.ui.platform.LocalHapticFeedback
|
import androidx.compose.ui.platform.LocalHapticFeedback
|
||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
@@ -49,30 +47,21 @@ import kotlin.math.sin
|
|||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
internal fun EmptyLibrary(avoid: Rect?, wall: (@Composable () -> Unit)? = null, fade: @Composable () -> Unit) {
|
internal fun EmptyLibrary(avoid: Rect?, wall: (@Composable () -> Unit)? = null, fade: @Composable () -> Unit) {
|
||||||
var origin by remember { mutableStateOf(Offset.Zero) }
|
val clock = rememberMarkClock(avoid)
|
||||||
val clock = rememberMarkClock(avoid?.translate(-origin.x, -origin.y))
|
Box(Modifier.fillMaxSize().onSizeChanged { clock.page = Size(it.width.toFloat(), it.height.toFloat()) }) {
|
||||||
Box(
|
|
||||||
Modifier.fillMaxSize()
|
|
||||||
.onGloballyPositioned { origin = it.positionInRoot() }
|
|
||||||
.onSizeChanged { clock.page = Size(it.width.toFloat(), it.height.toFloat()) },
|
|
||||||
) {
|
|
||||||
if (wall != null) wall() else EmptyWall(clock)
|
if (wall != null) wall() else EmptyWall(clock)
|
||||||
fade()
|
fade()
|
||||||
Mark(clock)
|
Mark(clock)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private const val TRACE_MS = 1250f
|
||||||
|
private const val FILL_FROM = 450f
|
||||||
private const val POP_FROM = 900f
|
private const val POP_FROM = 900f
|
||||||
private const val IMPACT = 2200f
|
private const val IMPACT = 2200f
|
||||||
private const val RIPPLE_MS = 1250f
|
private const val RIPPLE_MS = 1250f
|
||||||
private const val HIT_MS = 900f
|
private const val HIT_MS = 900f
|
||||||
private const val END = 3600f
|
private const val END = 3600f
|
||||||
private const val REVEAL_MS = 2300f
|
|
||||||
private const val TRACE_DRAW_MS = 900f
|
|
||||||
private const val TRACE_FADE_MS = 500f
|
|
||||||
private const val REVEAL_FILL_FROM = 600f
|
|
||||||
private const val REVEAL_FILL_MS = 450f
|
|
||||||
private const val REVEAL_FADE_FROM = 1700f
|
|
||||||
private const val POKE = 880f
|
private const val POKE = 880f
|
||||||
private const val DRIFT_MS = 75_000f
|
private const val DRIFT_MS = 75_000f
|
||||||
|
|
||||||
@@ -93,7 +82,8 @@ private fun rememberMarkClock(avoid: Rect?): MarkClock {
|
|||||||
val haptics = LocalHapticFeedback.current
|
val haptics = LocalHapticFeedback.current
|
||||||
val keepOff by rememberUpdatedState(avoid)
|
val keepOff by rememberUpdatedState(avoid)
|
||||||
val speed = with(LocalDensity.current) { 64.dp.toPx() }
|
val speed = with(LocalDensity.current) { 64.dp.toPx() }
|
||||||
val clearance = with(LocalDensity.current) { 4.dp.toPx() }
|
val inset = with(LocalDensity.current) { 10.dp.toPx() }
|
||||||
|
val clearance = with(LocalDensity.current) { 16.dp.toPx() }
|
||||||
LaunchedEffect(clock) {
|
LaunchedEffect(clock) {
|
||||||
var last = -1L
|
var last = -1L
|
||||||
var vx = speed * 0.8f
|
var vx = speed * 0.8f
|
||||||
@@ -119,28 +109,16 @@ private fun rememberMarkClock(avoid: Rect?): MarkClock {
|
|||||||
|
|
||||||
var x = clock.at.x + vx * dt / 1000f
|
var x = clock.at.x + vx * dt / 1000f
|
||||||
var y = clock.at.y + vy * dt / 1000f
|
var y = clock.at.y + vy * dt / 1000f
|
||||||
val hw = f.ball
|
val hw = f.halfWidth
|
||||||
val hh = f.ball
|
val hh = f.halfHeight
|
||||||
if (x - hw < 0f) { x = hw; vx = abs(vx) }
|
if (x - hw < inset) { x = inset + hw; vx = abs(vx) }
|
||||||
if (x + hw > clock.page.width) { x = clock.page.width - hw; vx = -abs(vx) }
|
if (x + hw > clock.page.width - inset) { x = clock.page.width - inset - hw; vx = -abs(vx) }
|
||||||
if (y - hh < 0f) { y = hh; vy = abs(vy) }
|
if (y - hh < inset) { y = inset + hh; vy = abs(vy) }
|
||||||
if (y + hh > clock.page.height) { y = clock.page.height - hh; vy = -abs(vy) }
|
if (y + hh > clock.page.height - inset) { y = clock.page.height - inset - hh; vy = -abs(vy) }
|
||||||
keepOff?.inflate(clearance)?.let { r ->
|
keepOff?.inflate(clearance)?.let { r ->
|
||||||
val nearX = x.coerceIn(r.left, r.right)
|
if (x + hw > r.left && x - hw < r.right && y + hh > r.top && y - hh < r.bottom) {
|
||||||
val nearY = y.coerceIn(r.top, r.bottom)
|
val outX = if (x < r.center.x) r.left - (x + hw) else r.right - (x - hw)
|
||||||
val gapX = x - nearX
|
val outY = if (y < r.center.y) r.top - (y + hh) else r.bottom - (y - hh)
|
||||||
val gapY = y - nearY
|
|
||||||
val gap = hypot(gapX, gapY)
|
|
||||||
if (gap in 0.0001f..f.ball) {
|
|
||||||
val nx = gapX / gap
|
|
||||||
val ny = gapY / gap
|
|
||||||
x = nearX + nx * f.ball
|
|
||||||
y = nearY + ny * f.ball
|
|
||||||
val into = vx * nx + vy * ny
|
|
||||||
if (into < 0f) { vx -= 2f * into * nx; vy -= 2f * into * ny }
|
|
||||||
} else if (gap <= 0.0001f) {
|
|
||||||
val outX = if (x < r.center.x) r.left - f.ball - x else r.right + f.ball - x
|
|
||||||
val outY = if (y < r.center.y) r.top - f.ball - y else r.bottom + f.ball - y
|
|
||||||
if (abs(outX) < abs(outY)) { x += outX; vx = if (outX < 0) -abs(vx) else abs(vx) }
|
if (abs(outX) < abs(outY)) { x += outX; vx = if (outX < 0) -abs(vx) else abs(vx) }
|
||||||
else { y += outY; vy = if (outY < 0) -abs(vy) else abs(vy) }
|
else { y += outY; vy = if (outY < 0) -abs(vy) else abs(vy) }
|
||||||
}
|
}
|
||||||
@@ -316,33 +294,30 @@ private fun Mark(clock: MarkClock) {
|
|||||||
} else 0f
|
} else 0f
|
||||||
|
|
||||||
translate(0f, shake) {
|
translate(0f, shake) {
|
||||||
val since = t - IMPACT
|
val fill = Out.transform(clamp01((intro - FILL_FROM) / 450f))
|
||||||
if (since in 0f..REVEAL_MS) {
|
if (fill > 0f) {
|
||||||
val fade = 1f - clamp01((since - REVEAL_FADE_FROM) / (REVEAL_MS - REVEAL_FADE_FROM))
|
val lift = 8f * k * (1f - fill)
|
||||||
val fill = Out.transform(clamp01((since - REVEAL_FILL_FROM) / REVEAL_FILL_MS)) * fade
|
val edge = 5f * f.s
|
||||||
if (fill > 0f) {
|
LogoShape.left(left, 0f) { x, y -> f.px(x, y) + Offset(0f, lift + edge) }
|
||||||
val lift = 8f * k * (1f - fill / fade)
|
LogoShape.right(right) { x, y -> f.px(x, y) + Offset(0f, lift + edge) }
|
||||||
val edge = 5f * f.s
|
drawPath(left, slabEdge.copy(alpha = fill))
|
||||||
LogoShape.left(left, 0f) { x, y -> f.px(x, y) + Offset(0f, lift + edge) }
|
drawPath(right, slabEdge.copy(alpha = fill))
|
||||||
LogoShape.right(right) { x, y -> f.px(x, y) + Offset(0f, lift + edge) }
|
LogoShape.left(left, 0f) { x, y -> f.px(x, y) + Offset(0f, lift) }
|
||||||
drawPath(left, slabEdge.copy(alpha = fill))
|
LogoShape.right(right) { x, y -> f.px(x, y) + Offset(0f, lift) }
|
||||||
drawPath(right, slabEdge.copy(alpha = fill))
|
drawPath(left, ink.copy(alpha = fill))
|
||||||
LogoShape.left(left, 0f) { x, y -> f.px(x, y) + Offset(0f, lift) }
|
drawPath(right, ink.copy(alpha = fill))
|
||||||
LogoShape.right(right) { x, y -> f.px(x, y) + Offset(0f, lift) }
|
}
|
||||||
drawPath(left, ink.copy(alpha = fill))
|
|
||||||
drawPath(right, ink.copy(alpha = fill))
|
if (intro < TRACE_MS) {
|
||||||
}
|
val drawn = TraceEase.transform(clamp01(intro / 775f))
|
||||||
val drawn = TraceEase.transform(clamp01(since / TRACE_DRAW_MS))
|
val alpha = if (intro < 775f) 1f else 1f - (intro - 775f) / 475f
|
||||||
val alpha = (if (since < TRACE_DRAW_MS) 1f else 1f - (since - TRACE_DRAW_MS) / TRACE_FADE_MS).coerceIn(0f, 1f) * fade
|
LogoShape.left(left, 0f, f::px)
|
||||||
if (alpha > 0f) {
|
LogoShape.right(right, f::px)
|
||||||
LogoShape.left(left, 0f, f::px)
|
for (half in listOf(left, right)) {
|
||||||
LogoShape.right(right, f::px)
|
measure.setPath(half, false)
|
||||||
for (half in listOf(left, right)) {
|
piece.reset()
|
||||||
measure.setPath(half, false)
|
measure.getSegment(0f, measure.length * drawn, piece, true)
|
||||||
piece.reset()
|
drawPath(piece, pal.signal.copy(alpha = alpha), style = Stroke(2f * f.s))
|
||||||
measure.getSegment(0f, measure.length * drawn, piece, true)
|
|
||||||
drawPath(piece, pal.signal.copy(alpha = alpha), style = Stroke(3f * f.s))
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -295,7 +295,7 @@ internal fun GameDetail(
|
|||||||
GameTab.ACHIEVEMENTS -> achievementState?.let { st -> AchievementsTab(StoreAchievements.forSource(store?.id)?.label.orEmpty(), st) }
|
GameTab.ACHIEVEMENTS -> achievementState?.let { st -> AchievementsTab(StoreAchievements.forSource(store?.id)?.label.orEmpty(), st) }
|
||||||
GameTab.LAUNCH -> if (game != null) LaunchTab(game, s, a, hopRail)
|
GameTab.LAUNCH -> if (game != null) LaunchTab(game, s, a, hopRail)
|
||||||
GameTab.SAVES -> if (game != null && prefix != null) SavesTab(game, prefix, a)
|
GameTab.SAVES -> if (game != null && prefix != null) SavesTab(game, prefix, a)
|
||||||
GameTab.ADDONS -> if (game != null) AddonsTab(game, addonTargets, s.sessionRunning, a)
|
GameTab.ADDONS -> if (game != null) AddonsTab(game, addonTargets, a)
|
||||||
GameTab.INSTALL -> InstallTab(game, installed, item, store)
|
GameTab.INSTALL -> InstallTab(game, installed, item, store)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1047,11 +1047,9 @@ private fun SavesTab(g: Library.SteamGame, prefix: File, a: FrontEndActions) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
private fun AddonsTab(g: Library.SteamGame, targets: List<WowAddons.Target>, sessionRunning: Boolean, a: FrontEndActions) {
|
private fun AddonsTab(g: Library.SteamGame, targets: List<WowAddons.Target>, a: FrontEndActions) {
|
||||||
var browsing by remember(g.gameId) { mutableStateOf<WowAddons.Target?>(null) }
|
var browsing by remember(g.gameId) { mutableStateOf<WowAddons.Target?>(null) }
|
||||||
val curseForge = CurseForgeApp.find(UserAppsState.items)
|
browsing?.let { AddonBrowserDialog(targets, it, CurseForgeApp.find(UserAppsState.items)) { browsing = null } }
|
||||||
val link = rememberCurseLink(curseForge, sessionRunning)
|
|
||||||
browsing?.let { AddonBrowserDialog(targets, it, curseForge, link) { browsing = null } }
|
|
||||||
Column(Modifier.fillMaxWidth().tabPanel(), verticalArrangement = Arrangement.spacedBy(2.dp)) {
|
Column(Modifier.fillMaxWidth().tabPanel(), verticalArrangement = Arrangement.spacedBy(2.dp)) {
|
||||||
CurseForgeEntry(a)
|
CurseForgeEntry(a)
|
||||||
targets.forEach { target ->
|
targets.forEach { target ->
|
||||||
@@ -1062,12 +1060,6 @@ private fun AddonsTab(g: Library.SteamGame, targets: List<WowAddons.Target>, ses
|
|||||||
val updates by produceState(emptyMap<String, WowAddonCatalog.Addon>(), names) {
|
val updates by produceState(emptyMap<String, WowAddonCatalog.Addon>(), names) {
|
||||||
value = withContext(Dispatchers.IO) { WowAddonCatalog.updates(context, names, target) }
|
value = withContext(Dispatchers.IO) { WowAddonCatalog.updates(context, names, target) }
|
||||||
}
|
}
|
||||||
val scanKey = link?.generation to WowAddons.imports
|
|
||||||
val managed by produceState(emptyMap<String, CurseForgeApp.Project>(), link, target.addOns, scanKey) {
|
|
||||||
value = if (link == null) emptyMap() else withContext(Dispatchers.IO) {
|
|
||||||
runCatching { CurseForgeApp.byFolder(link.installed(context, target, scanKey)) }.getOrDefault(emptyMap())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (targets.size > 1) SectionLabel(target.flavor)
|
if (targets.size > 1) SectionLabel(target.flavor)
|
||||||
MenuItem(stringResource(R.string.addons_download), checked = false) { browsing = target }
|
MenuItem(stringResource(R.string.addons_download), checked = false) { browsing = target }
|
||||||
MenuItem(
|
MenuItem(
|
||||||
@@ -1078,7 +1070,7 @@ private fun AddonsTab(g: Library.SteamGame, targets: List<WowAddons.Target>, ses
|
|||||||
target.addOns.mkdirs()
|
target.addOns.mkdirs()
|
||||||
a.onBrowseFiles(target.addOns)
|
a.onBrowseFiles(target.addOns)
|
||||||
}
|
}
|
||||||
names.forEach { item -> key(target.addOns, item.name) { AddonRow(item, updates[item.name], target, a, link?.let { l -> managed[item.name.lowercase()]?.let { it to l } }) } }
|
names.forEach { item -> key(target.addOns, item.name) { AddonRow(item, updates[item.name], target, a) } }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1132,10 +1124,8 @@ private fun CurseForgeEntry(a: FrontEndActions) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
internal fun AddonRow(item: WowAddons.Installed, wowiUpdate: WowAddonCatalog.Addon?, target: WowAddons.Target, a: FrontEndActions, curse: Pair<CurseForgeApp.Project, CurseLink>? = null) {
|
private fun AddonRow(item: WowAddons.Installed, update: WowAddonCatalog.Addon?, target: WowAddons.Target, a: FrontEndActions) {
|
||||||
val name = item.name
|
val name = item.name
|
||||||
val update = wowiUpdate.takeIf { curse == null }
|
|
||||||
val outdated = update != null || curse?.first?.update == true
|
|
||||||
var asking by remember(target.addOns, name) { mutableStateOf(false) }
|
var asking by remember(target.addOns, name) { mutableStateOf(false) }
|
||||||
var progress by remember(target.addOns, name) { mutableStateOf<Int?>(null) }
|
var progress by remember(target.addOns, name) { mutableStateOf<Int?>(null) }
|
||||||
val context = LocalContext.current
|
val context = LocalContext.current
|
||||||
@@ -1145,33 +1135,26 @@ internal fun AddonRow(item: WowAddons.Installed, wowiUpdate: WowAddonCatalog.Add
|
|||||||
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().padding(start = 16.dp, top = 2.dp, bottom = 2.dp)) {
|
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().padding(start = 16.dp, top = 2.dp, bottom = 2.dp)) {
|
||||||
Column(Modifier.weight(1f)) {
|
Column(Modifier.weight(1f)) {
|
||||||
Text(name, fontSize = 14.sp, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
Text(name, fontSize = 14.sp, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||||
val detail = listOfNotNull(item.version, if (outdated) stringResource(R.string.upd_available) else null).joinToString(" · ")
|
val detail = listOfNotNull(item.version, update?.let { stringResource(R.string.upd_available) }).joinToString(" · ")
|
||||||
if (detail.isNotEmpty()) Text(
|
if (detail.isNotEmpty()) Text(
|
||||||
progress?.let { stringResource(R.string.ctrl_percent, it) } ?: detail, fontSize = 12.sp,
|
progress?.let { stringResource(R.string.ctrl_percent, it) } ?: detail, fontSize = 12.sp,
|
||||||
color = if (outdated) LocalPalette.current.signal else colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis,
|
color = if (update != null) LocalPalette.current.signal else colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
if (outdated && !SessionState.running) IconAction(Icons.Outlined.Download, stringResource(R.string.common_update), "addon:update:${target.flavor}:$name", enabled = progress == null) {
|
if (update != null && !SessionState.running) IconAction(Icons.Outlined.Download, stringResource(R.string.common_update), "addon:update:${target.flavor}:$name", enabled = progress == null) {
|
||||||
progress = 0
|
progress = 0
|
||||||
scope.launch {
|
scope.launch {
|
||||||
val message = withContext(Dispatchers.IO) {
|
val message = withContext(Dispatchers.IO) { installAddon(context, update, target) { pct -> scope.launch { progress = pct } } }
|
||||||
if (curse != null) {
|
|
||||||
val (project, link) = curse
|
|
||||||
val done = runCatching { link.call(context, target) { CurseForgeApp.update(context, it.inspector, it.guid, project.id) } }.getOrDefault(false)
|
|
||||||
WowAddons.changed()
|
|
||||||
if (done) context.getString(R.string.user_apps_updated, name) else context.getString(R.string.stores_dl_failed_reason, name)
|
|
||||||
} else update?.let { installAddon(context, it, target) { pct -> scope.launch { progress = pct } }.first }
|
|
||||||
}
|
|
||||||
progress = null
|
progress = null
|
||||||
if (message != null) android.widget.Toast.makeText(context, message, android.widget.Toast.LENGTH_LONG).show()
|
android.widget.Toast.makeText(context, message.first, android.widget.Toast.LENGTH_LONG).show()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (!SessionState.running) IconAction(Icons.Outlined.Delete, if (curse != null) stringResource(R.string.common_uninstall) else delete, "addon:delete:${target.flavor}:$name", danger = true) { asking = true }
|
if (!SessionState.running) IconAction(Icons.Outlined.Delete, delete, "addon:delete:${target.flavor}:$name", danger = true) { asking = true }
|
||||||
}
|
}
|
||||||
if (asking) ConfirmDialog(
|
if (asking) ConfirmDialog(
|
||||||
title = if (curse != null) stringResource(R.string.stores_uninstall_title, name) else stringResource(R.string.games_delete_addon_title, name),
|
title = stringResource(R.string.games_delete_addon_title, name),
|
||||||
text = stringResource(R.string.games_delete_addon_body),
|
text = stringResource(R.string.games_delete_addon_body),
|
||||||
confirm = if (curse != null) stringResource(R.string.common_uninstall) else delete,
|
confirm = delete,
|
||||||
onConfirm = { a.onAddonDelete(target, name) },
|
onConfirm = { a.onAddonDelete(target, name) },
|
||||||
onDismiss = { asking = false },
|
onDismiss = { asking = false },
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -189,7 +189,6 @@ internal fun LiftHero(
|
|||||||
onOpenChange: (Boolean) -> Unit = {},
|
onOpenChange: (Boolean) -> Unit = {},
|
||||||
start: Dp = 44.dp,
|
start: Dp = 44.dp,
|
||||||
bottom: Dp = 44.dp,
|
bottom: Dp = 44.dp,
|
||||||
onTextBounds: (Rect) -> Unit = {},
|
|
||||||
drop: DropSheetState? = null,
|
drop: DropSheetState? = null,
|
||||||
overlay: @Composable BoxWithConstraintsScope.(lifted: () -> Float) -> Unit = {},
|
overlay: @Composable BoxWithConstraintsScope.(lifted: () -> Float) -> Unit = {},
|
||||||
) {
|
) {
|
||||||
@@ -574,7 +573,7 @@ internal fun LiftHero(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Column(Modifier.align(Alignment.BottomStart).padding(start = start, bottom = bottom, end = 20.dp).onGloballyPositioned { onTextBounds(it.boundsInRoot()) }) {
|
Column(Modifier.align(Alignment.BottomStart).padding(start = start, bottom = bottom, end = 20.dp)) {
|
||||||
Box(Modifier.graphicsLayer { alpha = 1f - wallSink() }) { words() }
|
Box(Modifier.graphicsLayer { alpha = 1f - wallSink() }) { words() }
|
||||||
Spacer(Modifier.height(18.dp))
|
Spacer(Modifier.height(18.dp))
|
||||||
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) {
|
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||||
|
|||||||
@@ -1608,12 +1608,15 @@ private fun ComponentsDrawerPage(host: MenuHost, a: DrawerActions, track: (Strin
|
|||||||
chipModifier = track("cmp-proton"),
|
chipModifier = track("cmp-proton"),
|
||||||
onPick = { id -> a.onGameProton(gameProfile.appId, id) },
|
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) {
|
for (comp in ComponentsManager.COMPONENTS) {
|
||||||
val value = gameProfile.components.getValue(comp)
|
val value = gameProfile.components.getValue(comp)
|
||||||
val managedDxvk = ComponentsManager.runtimeManaged(comp, a.systemPowerVr)
|
val managedDxvk = ComponentsManager.runtimeManaged(comp, a.systemPowerVr)
|
||||||
val options: List<Pair<String?, String>> =
|
val options: List<Pair<String?, String>> =
|
||||||
listOf(null to stringResource(R.string.comp_game_use_general)) +
|
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(
|
DrawerStackedChoice(
|
||||||
host = host,
|
host = host,
|
||||||
key = "game-cmp-$comp",
|
key = "game-cmp-$comp",
|
||||||
@@ -1696,7 +1699,7 @@ private fun ComponentsDrawerPage(host: MenuHost, a: DrawerActions, track: (Strin
|
|||||||
val managedDxvk = ComponentsManager.runtimeManaged(comp, a.systemPowerVr)
|
val managedDxvk = ComponentsManager.runtimeManaged(comp, a.systemPowerVr)
|
||||||
val originals = view.originals.filter { it.comp == comp }
|
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)) } +
|
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
|
if (options.isEmpty() && !managedDxvk) continue
|
||||||
val current = st.activeFile ?: "orig:$build"
|
val current = st.activeFile ?: "orig:$build"
|
||||||
val shown = options.firstOrNull { it.first == current }?.second
|
val shown = options.firstOrNull { it.first == current }?.second
|
||||||
|
|||||||
@@ -140,7 +140,6 @@ internal fun SteamHome(s: FrontEndState, a: FrontEndActions, modifier: Modifier)
|
|||||||
onOpen = a.onSteamSettings, onPrimary = a.onPlay,
|
onOpen = a.onSteamSettings, onPrimary = a.onPlay,
|
||||||
modifier = modifier.clipToBounds(),
|
modifier = modifier.clipToBounds(),
|
||||||
start = if (narrow) 20.dp else 44.dp, bottom = 44.dp,
|
start = if (narrow) 20.dp else 44.dp, bottom = 44.dp,
|
||||||
onTextBounds = { words = it },
|
|
||||||
background = {
|
background = {
|
||||||
when {
|
when {
|
||||||
games.isEmpty() -> EmptyLibrary(
|
games.isEmpty() -> EmptyLibrary(
|
||||||
@@ -161,12 +160,13 @@ internal fun SteamHome(s: FrontEndState, a: FrontEndActions, modifier: Modifier)
|
|||||||
IntegrationSuggestion(s.integration, { a.onSteamIntegration(null) }, a.onDismissIntegration)
|
IntegrationSuggestion(s.integration, { a.onSteamIntegration(null) }, a.onDismissIntegration)
|
||||||
}
|
}
|
||||||
if (narrow) Column(
|
if (narrow) Column(
|
||||||
verticalArrangement = Arrangement.spacedBy(12.dp),
|
verticalArrangement = Arrangement.spacedBy(12.dp), modifier = Modifier.onPlaced { words = it.boundsInParent() },
|
||||||
) {
|
) {
|
||||||
Wordmark(30.dp)
|
Wordmark(30.dp)
|
||||||
runtimeStatus()
|
runtimeStatus()
|
||||||
} else Row(
|
} else Row(
|
||||||
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp),
|
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp),
|
||||||
|
modifier = Modifier.onPlaced { words = it.boundsInParent() },
|
||||||
) {
|
) {
|
||||||
Wordmark(if (narrow) 30.dp else 40.dp)
|
Wordmark(if (narrow) 30.dp else 40.dp)
|
||||||
runtimeStatus()
|
runtimeStatus()
|
||||||
|
|||||||
@@ -10,6 +10,8 @@ import com.droiddeck.launcher.session.SessionPrefs
|
|||||||
import com.droiddeck.launcher.session.SessionState
|
import com.droiddeck.launcher.session.SessionState
|
||||||
|
|
||||||
object CompositorHost {
|
object CompositorHost {
|
||||||
|
private const val TAG = "DroidDeck"
|
||||||
|
|
||||||
@Volatile
|
@Volatile
|
||||||
private var started = false
|
private var started = false
|
||||||
|
|
||||||
@@ -55,6 +57,52 @@ object CompositorHost {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
class Output internal constructor(
|
||||||
|
internal val runtimeDir: java.io.File,
|
||||||
|
internal val turnip: com.droiddeck.launcher.gpu.TurnipDriver,
|
||||||
|
internal val driverId: String?,
|
||||||
|
)
|
||||||
|
|
||||||
|
fun prepare(context: android.content.Context): Output {
|
||||||
|
val runtimeDir = java.io.File(context.filesDir, ".wayland-rt").apply { mkdirs() }
|
||||||
|
com.droiddeck.launcher.core.FileUtils.copyAsset(context, "wayland/keymap.xkb", java.io.File(runtimeDir, "keymap.xkb"))
|
||||||
|
com.droiddeck.launcher.input.VrControllers.publish(context)
|
||||||
|
val turnip = com.droiddeck.launcher.gpu.TurnipDriver(context)
|
||||||
|
com.droiddeck.launcher.gpu.DriverSetupLog.write(context, "surface.driver-setup")
|
||||||
|
if (!started) {
|
||||||
|
displayChoice = SessionPrefs.androidDriver(context)
|
||||||
|
com.droiddeck.launcher.gpu.AutoDriverTrial.displayStarting(context, SessionPrefs.androidDriver(context))
|
||||||
|
}
|
||||||
|
return Output(runtimeDir, turnip, if (started) null else turnip.install())
|
||||||
|
}
|
||||||
|
|
||||||
|
fun logToSession(context: android.content.Context) {
|
||||||
|
val waylandLog = java.io.File(com.droiddeck.launcher.session.SessionPaths.beginOrCurrent(context), "wayland.log")
|
||||||
|
WaylandCompositor.setSessionLogFile(waylandLog)
|
||||||
|
try {
|
||||||
|
android.system.Os.setenv("DD_WAYLAND_LOG", waylandLog.path, true)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
android.util.Log.w(TAG, "could not point the compositor's log at $waylandLog", e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun applyHdr(context: android.content.Context, mode: String) {
|
||||||
|
val on = SessionState.hdrCapable && SessionPrefs.hdr(context, mode)
|
||||||
|
SessionState.hdr = on
|
||||||
|
WaylandCompositor.nativeSetHdrOutput(on)
|
||||||
|
WaylandCompositor.nativeSetZeroCopy(on || SessionPrefs.zeroCopy(context, mode))
|
||||||
|
android.util.Log.i(TAG, "hdr: " + (if (on) "on" else "off") + " for this $mode session")
|
||||||
|
}
|
||||||
|
|
||||||
|
fun start(context: android.content.Context, output: Output, surface: Surface, size: Pair<Int, Int>, refreshHz: Float, fpsLimit: Int): Boolean {
|
||||||
|
com.droiddeck.launcher.gpu.DriverSetupLog.write(context, "compositor.start driver=${output.driverId}")
|
||||||
|
return startOrAttach(
|
||||||
|
context, surface, output.runtimeDir.path,
|
||||||
|
output.driverId?.let { output.turnip.driverPath(it) }, output.driverId?.let { output.turnip.libraryName(it) },
|
||||||
|
context.applicationInfo.nativeLibraryDir, size.first, size.second, refreshHz, fpsLimit,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
@Synchronized
|
@Synchronized
|
||||||
fun startOrAttach(
|
fun startOrAttach(
|
||||||
context: android.content.Context,
|
context: android.content.Context,
|
||||||
|
|||||||
@@ -5,7 +5,6 @@ import android.bluetooth.BluetoothGatt
|
|||||||
import android.bluetooth.BluetoothGattCallback
|
import android.bluetooth.BluetoothGattCallback
|
||||||
import android.bluetooth.BluetoothGattCharacteristic
|
import android.bluetooth.BluetoothGattCharacteristic
|
||||||
import android.bluetooth.BluetoothGattDescriptor
|
import android.bluetooth.BluetoothGattDescriptor
|
||||||
import android.bluetooth.BluetoothGattService
|
|
||||||
import android.os.Handler
|
import android.os.Handler
|
||||||
import org.junit.After
|
import org.junit.After
|
||||||
import org.junit.Assert.*
|
import org.junit.Assert.*
|
||||||
@@ -19,13 +18,11 @@ import org.robolectric.annotation.Config
|
|||||||
import org.robolectric.annotation.Implementation
|
import org.robolectric.annotation.Implementation
|
||||||
import org.robolectric.annotation.Implements
|
import org.robolectric.annotation.Implements
|
||||||
import org.robolectric.util.ReflectionHelpers
|
import org.robolectric.util.ReflectionHelpers
|
||||||
import org.robolectric.shadow.api.Shadow
|
|
||||||
import org.robolectric.shadows.ShadowBluetoothGatt
|
import org.robolectric.shadows.ShadowBluetoothGatt
|
||||||
import java.time.Duration
|
|
||||||
import java.util.UUID
|
import java.util.UUID
|
||||||
|
|
||||||
@RunWith(RobolectricTestRunner::class)
|
@RunWith(RobolectricTestRunner::class)
|
||||||
@Config(sdk = [34], manifest = Config.NONE, shadows = [SteamControllerBleTest.Writer::class, SteamControllerBleTest.BusyGatt::class])
|
@Config(sdk = [34], manifest = Config.NONE, shadows = [SteamControllerBleTest.Writer::class])
|
||||||
class SteamControllerBleTest {
|
class SteamControllerBleTest {
|
||||||
private val keys = ArrayList<Pair<Int, Boolean>>()
|
private val keys = ArrayList<Pair<Int, Boolean>>()
|
||||||
private val router = InputRouter(object : InputOutput {
|
private val router = InputRouter(object : InputOutput {
|
||||||
@@ -156,144 +153,15 @@ class SteamControllerBleTest {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test fun unansweredSubscriptionDropsTheLink() {
|
|
||||||
val link = ValveLink()
|
|
||||||
link.start()
|
|
||||||
assertEquals(1, link.shadow.descriptorWrites)
|
|
||||||
shadowOf(handler.looper).idleFor(Duration.ofMillis(2_500))
|
|
||||||
assertEquals(1, link.shadow.descriptorWrites)
|
|
||||||
assertEquals(2, link.shadow.refused)
|
|
||||||
assertSame(link.gatt, ReflectionHelpers.getField<Any?>(controller, "gatt"))
|
|
||||||
shadowOf(handler.looper).idleFor(Duration.ofMillis(1_000))
|
|
||||||
assertNull(ReflectionHelpers.getField<Any?>(controller, "gatt"))
|
|
||||||
assertFalse(SteamControllerBle.connected)
|
|
||||||
assertEquals(0, link.shadow.lizardWrites)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test fun failedSubscriptionIsWrittenAgain() {
|
|
||||||
val link = ValveLink()
|
|
||||||
link.start()
|
|
||||||
link.answer(BluetoothGatt.GATT_FAILURE)
|
|
||||||
assertFalse(SteamControllerBle.connected)
|
|
||||||
shadowOf(handler.looper).idleFor(Duration.ofMillis(1_500))
|
|
||||||
assertEquals(2, link.shadow.descriptorWrites)
|
|
||||||
link.answer()
|
|
||||||
assertTrue(SteamControllerBle.connected)
|
|
||||||
assertEquals(1, link.shadow.lizardWrites)
|
|
||||||
link.answer()
|
|
||||||
shadowOf(handler.looper).idleFor(Duration.ofMillis(2_000))
|
|
||||||
assertEquals(2, link.shadow.descriptorWrites)
|
|
||||||
assertSame(link.gatt, ReflectionHelpers.getField<Any?>(controller, "gatt"))
|
|
||||||
assertTrue(SteamControllerBle.connected)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test fun inputBeforeTheSubscriptionReplyTurnsLizardModeOffOnceTheReplyArrives() {
|
|
||||||
val link = ValveLink()
|
|
||||||
link.start()
|
|
||||||
link.input()
|
|
||||||
assertTrue(SteamControllerBle.connected)
|
|
||||||
assertTrue(Writer.connections.last())
|
|
||||||
shadowOf(handler.looper).idleFor(Duration.ofMillis(500))
|
|
||||||
assertEquals(0, link.shadow.lizardWrites)
|
|
||||||
link.answer()
|
|
||||||
shadowOf(handler.looper).idleFor(Duration.ofMillis(20))
|
|
||||||
assertEquals(1, link.shadow.lizardWrites)
|
|
||||||
link.answer()
|
|
||||||
shadowOf(handler.looper).idleFor(Duration.ofMillis(3_000))
|
|
||||||
assertEquals(1, link.shadow.descriptorWrites)
|
|
||||||
assertSame(link.gatt, ReflectionHelpers.getField<Any?>(controller, "gatt"))
|
|
||||||
assertTrue(SteamControllerBle.connected)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test fun inputWithoutALizardModeReplyDropsTheLink() {
|
|
||||||
val link = ValveLink()
|
|
||||||
link.start()
|
|
||||||
link.input()
|
|
||||||
assertTrue(SteamControllerBle.connected)
|
|
||||||
shadowOf(handler.looper).idleFor(Duration.ofMillis(2_500))
|
|
||||||
assertEquals(1, link.shadow.descriptorWrites)
|
|
||||||
assertEquals(0, link.shadow.lizardWrites)
|
|
||||||
assertSame(link.gatt, ReflectionHelpers.getField<Any?>(controller, "gatt"))
|
|
||||||
shadowOf(handler.looper).idleFor(Duration.ofMillis(1_000))
|
|
||||||
assertNull(ReflectionHelpers.getField<Any?>(controller, "gatt"))
|
|
||||||
assertFalse(SteamControllerBle.connected)
|
|
||||||
assertFalse(Writer.connections.last())
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test fun failedLizardModeWriteDropsTheLink() {
|
|
||||||
val link = ValveLink()
|
|
||||||
link.start()
|
|
||||||
link.answer()
|
|
||||||
assertEquals(1, link.shadow.lizardWrites)
|
|
||||||
link.answer(BluetoothGatt.GATT_FAILURE)
|
|
||||||
link.input()
|
|
||||||
shadowOf(handler.looper).idleFor(Duration.ofMillis(2_500))
|
|
||||||
assertSame(link.gatt, ReflectionHelpers.getField<Any?>(controller, "gatt"))
|
|
||||||
shadowOf(handler.looper).idleFor(Duration.ofMillis(1_000))
|
|
||||||
assertNull(ReflectionHelpers.getField<Any?>(controller, "gatt"))
|
|
||||||
assertFalse(SteamControllerBle.connected)
|
|
||||||
assertFalse(Writer.connections.last())
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test fun answeredSubscriptionStartsOneLizardModeRefresh() {
|
|
||||||
val link = ValveLink()
|
|
||||||
link.start()
|
|
||||||
link.answer()
|
|
||||||
assertTrue(SteamControllerBle.connected)
|
|
||||||
assertEquals(1, link.shadow.lizardWrites)
|
|
||||||
link.answer()
|
|
||||||
link.input()
|
|
||||||
assertEquals(1, link.shadow.lizardWrites)
|
|
||||||
shadowOf(handler.looper).idleFor(Duration.ofMillis(3_500))
|
|
||||||
assertEquals(1, link.shadow.descriptorWrites)
|
|
||||||
assertEquals(2, link.shadow.lizardWrites)
|
|
||||||
}
|
|
||||||
|
|
||||||
private inner class ValveLink {
|
|
||||||
val gatt: BluetoothGatt = ShadowBluetoothGatt.newInstance(
|
|
||||||
BluetoothAdapter.getDefaultAdapter().getRemoteDevice("00:11:22:33:44:66"))
|
|
||||||
val shadow = Shadow.extract<BusyGatt>(gatt)
|
|
||||||
private val characteristic = BluetoothGattCharacteristic(INPUT, BluetoothGattCharacteristic.PROPERTY_NOTIFY, 0).apply {
|
|
||||||
addDescriptor(BluetoothGattDescriptor(CCCD, 0))
|
|
||||||
}
|
|
||||||
private val callback = ReflectionHelpers.getField<BluetoothGattCallback>(controller, "callback")
|
|
||||||
|
|
||||||
init {
|
|
||||||
val service = BluetoothGattService(SERVICE, BluetoothGattService.SERVICE_TYPE_PRIMARY)
|
|
||||||
service.addCharacteristic(characteristic)
|
|
||||||
service.addCharacteristic(BluetoothGattCharacteristic(REPORT,
|
|
||||||
BluetoothGattCharacteristic.PROPERTY_WRITE or BluetoothGattCharacteristic.PROPERTY_READ, 0))
|
|
||||||
shadow.addDiscoverableService(service)
|
|
||||||
shadow.setGattCallback(object : BluetoothGattCallback() {})
|
|
||||||
gatt.discoverServices()
|
|
||||||
}
|
|
||||||
|
|
||||||
fun start() {
|
|
||||||
ReflectionHelpers.setField(controller, "gatt", gatt)
|
|
||||||
callback.onMtuChanged(gatt, 517, BluetoothGatt.GATT_SUCCESS)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun input() = callback.onCharacteristicChanged(gatt, characteristic, ByteArray(45))
|
|
||||||
|
|
||||||
fun answer(status: Int = BluetoothGatt.GATT_SUCCESS) {
|
|
||||||
val op = shadow.pending
|
|
||||||
shadow.pending = null
|
|
||||||
when (op) {
|
|
||||||
is BluetoothGattDescriptor -> callback.onDescriptorWrite(gatt, op, status)
|
|
||||||
is BluetoothGattCharacteristic -> callback.onCharacteristicWrite(gatt, op, status)
|
|
||||||
else -> fail("no write is waiting for a reply")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun subscribe(target: SteamControllerBle) {
|
private fun subscribe(target: SteamControllerBle) {
|
||||||
val device = BluetoothAdapter.getDefaultAdapter().getRemoteDevice("00:11:22:33:44:55")
|
val device = BluetoothAdapter.getDefaultAdapter().getRemoteDevice("00:11:22:33:44:55")
|
||||||
val gatt = ShadowBluetoothGatt.newInstance(device)
|
val gatt = ShadowBluetoothGatt.newInstance(device)
|
||||||
val characteristic = BluetoothGattCharacteristic(INPUT, BluetoothGattCharacteristic.PROPERTY_NOTIFY, 0)
|
val input = UUID.fromString("100F6C7A-1735-4313-B402-38567131E5F3")
|
||||||
val descriptor = BluetoothGattDescriptor(CCCD, 0)
|
val characteristic = BluetoothGattCharacteristic(input, BluetoothGattCharacteristic.PROPERTY_NOTIFY, 0)
|
||||||
|
val descriptor = BluetoothGattDescriptor(UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"), 0)
|
||||||
characteristic.addDescriptor(descriptor)
|
characteristic.addDescriptor(descriptor)
|
||||||
ReflectionHelpers.setField(target, "gatt", gatt)
|
ReflectionHelpers.setField(target, "gatt", gatt)
|
||||||
ReflectionHelpers.setField(target, "input", INPUT)
|
ReflectionHelpers.setField(target, "input", input)
|
||||||
ReflectionHelpers.setField(target, "reportId", 0x45)
|
ReflectionHelpers.setField(target, "reportId", 0x45)
|
||||||
ReflectionHelpers.getField<BluetoothGattCallback>(target, "callback")
|
ReflectionHelpers.getField<BluetoothGattCallback>(target, "callback")
|
||||||
.onDescriptorWrite(gatt, descriptor, BluetoothGatt.GATT_SUCCESS)
|
.onDescriptorWrite(gatt, descriptor, BluetoothGatt.GATT_SUCCESS)
|
||||||
@@ -302,46 +170,6 @@ class SteamControllerBleTest {
|
|||||||
private fun state(bytes: ByteArray, target: SteamControllerBle = controller) = ReflectionHelpers.callInstanceMethod<Unit>(target, "onState",
|
private fun state(bytes: ByteArray, target: SteamControllerBle = controller) = ReflectionHelpers.callInstanceMethod<Unit>(target, "onState",
|
||||||
ReflectionHelpers.ClassParameter.from(ByteArray::class.java, bytes))
|
ReflectionHelpers.ClassParameter.from(ByteArray::class.java, bytes))
|
||||||
|
|
||||||
private companion object {
|
|
||||||
val SERVICE: UUID = UUID.fromString("100F6C32-1735-4313-B402-38567131E5F3")
|
|
||||||
val INPUT: UUID = UUID.fromString("100F6C7A-1735-4313-B402-38567131E5F3")
|
|
||||||
val REPORT: UUID = UUID.fromString("100F6C34-1735-4313-B402-38567131E5F3")
|
|
||||||
val CCCD: UUID = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb")
|
|
||||||
}
|
|
||||||
|
|
||||||
@Implements(BluetoothGatt::class)
|
|
||||||
class BusyGatt : ShadowBluetoothGatt() {
|
|
||||||
var pending: Any? = null
|
|
||||||
var descriptorWrites = 0
|
|
||||||
var lizardWrites = 0
|
|
||||||
var refused = 0
|
|
||||||
|
|
||||||
@Implementation
|
|
||||||
override fun writeDescriptor(descriptor: BluetoothGattDescriptor): Boolean {
|
|
||||||
if (!accept(descriptor)) return false
|
|
||||||
descriptorWrites++
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
@Implementation
|
|
||||||
override fun writeCharacteristic(characteristic: BluetoothGattCharacteristic): Boolean {
|
|
||||||
if (!accept(characteristic)) return false
|
|
||||||
@Suppress("DEPRECATION")
|
|
||||||
val value = characteristic.value
|
|
||||||
if (characteristic.uuid == REPORT && value[0] == 0x87.toByte() && value[2] == 9.toByte()) lizardWrites++
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun accept(op: Any): Boolean {
|
|
||||||
if (pending != null) {
|
|
||||||
refused++
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
pending = op
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Implements(FakeInputWriter::class)
|
@Implements(FakeInputWriter::class)
|
||||||
class Writer {
|
class Writer {
|
||||||
companion object {
|
companion object {
|
||||||
|
|||||||
@@ -8,7 +8,6 @@ import org.junit.Assert.assertFalse
|
|||||||
import org.junit.Assert.assertNull
|
import org.junit.Assert.assertNull
|
||||||
import org.junit.Assert.assertThrows
|
import org.junit.Assert.assertThrows
|
||||||
import org.junit.Assert.assertTrue
|
import org.junit.Assert.assertTrue
|
||||||
import org.junit.After
|
|
||||||
import org.junit.Rule
|
import org.junit.Rule
|
||||||
import org.junit.Test
|
import org.junit.Test
|
||||||
import org.junit.rules.TemporaryFolder
|
import org.junit.rules.TemporaryFolder
|
||||||
@@ -22,47 +21,6 @@ import java.io.File
|
|||||||
class CurseForgeAppTest {
|
class CurseForgeAppTest {
|
||||||
@get:Rule val temp = TemporaryFolder()
|
@get:Rule val temp = TemporaryFolder()
|
||||||
|
|
||||||
private val original = CurseForgeApp.guest
|
|
||||||
private val url = "ws://127.0.0.1:43117/0f8fad5b-d9cb-469f-a165-70867728950e"
|
|
||||||
private val app = UserApps.App("appimage:c", UserApps.Kind.APPIMAGE, "CurseForge", null, null, AppImageManager.LAUNCHER, listOf("/root/apps/curseforge"), feed = CurseForgeApp.FEED)
|
|
||||||
|
|
||||||
@After
|
|
||||||
fun restoreGuest() {
|
|
||||||
val context = org.robolectric.RuntimeEnvironment.getApplication()
|
|
||||||
launches.forEach { CurseForgeApp.stop(context, app, null, it) }
|
|
||||||
holder.get()?.set(true)
|
|
||||||
CurseForgeApp.guest = original
|
|
||||||
}
|
|
||||||
|
|
||||||
private val launches = mutableListOf<java.util.concurrent.atomic.AtomicBoolean>()
|
|
||||||
|
|
||||||
private fun launch(): java.util.concurrent.atomic.AtomicBoolean = java.util.concurrent.atomic.AtomicBoolean(false).also { launches += it }
|
|
||||||
|
|
||||||
private val holder = java.util.concurrent.atomic.AtomicReference<java.util.concurrent.atomic.AtomicBoolean?>()
|
|
||||||
private val released = java.util.concurrent.CountDownLatch(1)
|
|
||||||
|
|
||||||
private fun fakeGuest(startExit: Int, ready: Boolean = true): MutableList<List<String>> {
|
|
||||||
val calls = java.util.Collections.synchronizedList(mutableListOf<List<String>>())
|
|
||||||
CurseForgeApp.guest = { _, argv, cancelled, onLine ->
|
|
||||||
calls += argv
|
|
||||||
when {
|
|
||||||
argv[0] == CurseForgeApp.HELPER && argv[1] == "start" -> {
|
|
||||||
if (startExit == 0) {
|
|
||||||
holder.set(cancelled)
|
|
||||||
onLine(url)
|
|
||||||
while (cancelled?.get() != true) Thread.sleep(10)
|
|
||||||
released.countDown()
|
|
||||||
} else onLine("busy")
|
|
||||||
startExit
|
|
||||||
}
|
|
||||||
argv[0] == CurseForgeApp.HELPER -> 0
|
|
||||||
ready -> { onLine(JSONObject().put("ok", true).put("value", """{"value":true}""").toString()); 0 }
|
|
||||||
else -> { onLine(JSONObject().put("ok", false).put("error", JSONObject().put("code", "DEVTOOLS_UNREACHABLE").put("message", "no")).toString()); 0 }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return calls
|
|
||||||
}
|
|
||||||
|
|
||||||
private val search = """{"success":true,"injectedCount":0,
|
private val search = """{"success":true,"injectedCount":0,
|
||||||
"pagination":{"index":0,"pageSize":20,"resultCount":20,"totalCount":150},
|
"pagination":{"index":0,"pageSize":20,"resultCount":20,"totalCount":150},
|
||||||
"mods":[
|
"mods":[
|
||||||
@@ -166,19 +124,12 @@ class CurseForgeAppTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun installedProjectsAndExitCodes() {
|
fun installedIdsAndExitCodes() {
|
||||||
val projects = CurseForgeApp.parseProjects(JSONArray("""[
|
assertEquals(setOf("486246", "2"), CurseForgeApp.projectIds(JSONArray("""["486246","2",null]""")))
|
||||||
{"id":"486246","installedModId":"a_486246","status":3,"locked":false,"folders":["RXPGuides","RXPGuides_Extra"]},
|
assertEquals(emptySet<String>(), CurseForgeApp.projectIds(JSONObject()))
|
||||||
{"id":"2","installedModId":"b_2","status":2,"locked":true,"folders":[]},
|
|
||||||
{"id":null}]"""))
|
|
||||||
assertEquals(listOf("486246", "2"), projects.map { it.id })
|
|
||||||
assertEquals("486246", CurseForgeApp.owner(projects, "RXPGuides_Extra")?.id)
|
|
||||||
assertNull(CurseForgeApp.owner(projects, "TomTom"))
|
|
||||||
assertFalse(projects[1].update)
|
|
||||||
assertTrue(CurseForgeApp.parseProjects(JSONObject()).isEmpty())
|
|
||||||
assertEquals(CurseForgeApp.Start.READY, CurseForgeApp.startState(0))
|
assertEquals(CurseForgeApp.Start.READY, CurseForgeApp.startState(0))
|
||||||
assertEquals(CurseForgeApp.Start.BUSY, CurseForgeApp.startState(3))
|
assertEquals(CurseForgeApp.Start.BUSY, CurseForgeApp.startState(3))
|
||||||
assertEquals(CurseForgeApp.Start.FAILED, CurseForgeApp.startState(4))
|
assertEquals(CurseForgeApp.Start.NO_DISPLAY, CurseForgeApp.startState(4))
|
||||||
assertEquals(CurseForgeApp.Start.FAILED, CurseForgeApp.startState(5))
|
assertEquals(CurseForgeApp.Start.FAILED, CurseForgeApp.startState(5))
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -207,364 +158,4 @@ class CurseForgeAppTest {
|
|||||||
assertEquals(File(root, target.flavor), WowAddons.flavorDir(target))
|
assertEquals(File(root, target.flavor), WowAddons.flavorDir(target))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
|
||||||
fun theAppStartsInTheGuestWithoutASessionAndIsAskedThroughItsInspector() {
|
|
||||||
val calls = fakeGuest(0)
|
|
||||||
val started = CurseForgeApp.start(org.robolectric.RuntimeEnvironment.getApplication(), app, launch())
|
|
||||||
assertEquals(CurseForgeApp.Start.READY, started.state)
|
|
||||||
assertEquals(url, started.inspector)
|
|
||||||
assertEquals(listOf(CurseForgeApp.HELPER, "start", "/root/apps/curseforge"), calls.first())
|
|
||||||
val probe = calls[1]
|
|
||||||
assertEquals(listOf(CurseForgeApp.AGENT, "--cdp-inspector", url), probe.take(3))
|
|
||||||
assertEquals("10.0", probe[3])
|
|
||||||
assertTrue(probe[4].contains("InstalledProjectsAppService"))
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun theLaunchLivesUntilItIsStopped() {
|
|
||||||
fakeGuest(0)
|
|
||||||
val context = org.robolectric.RuntimeEnvironment.getApplication()
|
|
||||||
val hold = launch()
|
|
||||||
assertEquals(CurseForgeApp.Start.READY, CurseForgeApp.start(context, app, hold).state)
|
|
||||||
assertEquals(false, holder.get()?.get())
|
|
||||||
assertEquals(1L, released.count)
|
|
||||||
CurseForgeApp.stop(context, app, url, hold)
|
|
||||||
assertTrue(released.await(5, java.util.concurrent.TimeUnit.SECONDS))
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun anAppThatIsAlreadyOpenIsNeitherUsedNorStopped() {
|
|
||||||
val calls = fakeGuest(3)
|
|
||||||
assertEquals(CurseForgeApp.Start.BUSY, CurseForgeApp.start(org.robolectric.RuntimeEnvironment.getApplication(), app, launch()).state)
|
|
||||||
assertEquals(listOf(listOf(CurseForgeApp.HELPER, "start", "/root/apps/curseforge")), calls)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun stoppingAsksTheAppToQuitThenStopsItsHeadlessLaunchOnce() {
|
|
||||||
val calls = fakeGuest(0)
|
|
||||||
val context = org.robolectric.RuntimeEnvironment.getApplication()
|
|
||||||
val hold = launch()
|
|
||||||
CurseForgeApp.start(context, app, hold)
|
|
||||||
calls.clear()
|
|
||||||
CurseForgeApp.stop(context, app, url, hold)
|
|
||||||
assertEquals(CurseForgeApp.AGENT, calls[0][0])
|
|
||||||
assertTrue(calls[0][4].contains("shutdown"))
|
|
||||||
assertEquals(listOf(CurseForgeApp.HELPER, "stop", "/root/apps/curseforge"), calls[1])
|
|
||||||
assertTrue(hold.get())
|
|
||||||
calls.clear()
|
|
||||||
CurseForgeApp.stop(context, app, url, hold)
|
|
||||||
assertTrue(calls.isEmpty())
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun aLateStopLeavesTheNewerLaunchRunning() {
|
|
||||||
val calls = fakeGuest(0)
|
|
||||||
val context = org.robolectric.RuntimeEnvironment.getApplication()
|
|
||||||
val old = launch()
|
|
||||||
val newer = launch()
|
|
||||||
CurseForgeApp.start(context, app, old)
|
|
||||||
CurseForgeApp.start(context, app, newer)
|
|
||||||
assertTrue(old.get())
|
|
||||||
calls.clear()
|
|
||||||
CurseForgeApp.stop(context, app, url, old)
|
|
||||||
assertTrue(calls.isEmpty())
|
|
||||||
assertEquals(false, newer.get())
|
|
||||||
CurseForgeApp.stop(context, app, null, newer)
|
|
||||||
assertEquals(listOf(listOf(CurseForgeApp.HELPER, "stop", "/root/apps/curseforge")), calls)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun aStoppedLaunchNeverStarts() {
|
|
||||||
val calls = fakeGuest(0)
|
|
||||||
val hold = launch().apply { set(true) }
|
|
||||||
assertEquals(CurseForgeApp.Start.FAILED, CurseForgeApp.start(org.robolectric.RuntimeEnvironment.getApplication(), app, hold).state)
|
|
||||||
assertTrue(calls.isEmpty())
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun anAppWithoutADirectoryIsNeverLaunched() {
|
|
||||||
val calls = fakeGuest(0)
|
|
||||||
val bare = UserApps.App("appimage:d", UserApps.Kind.APPIMAGE, "CurseForge", null, null, AppImageManager.LAUNCHER, emptyList(), feed = CurseForgeApp.FEED)
|
|
||||||
val hold = launch()
|
|
||||||
assertEquals(CurseForgeApp.Start.FAILED, CurseForgeApp.start(org.robolectric.RuntimeEnvironment.getApplication(), bare, hold).state)
|
|
||||||
CurseForgeApp.stop(org.robolectric.RuntimeEnvironment.getApplication(), bare, url, hold)
|
|
||||||
assertTrue(calls.isEmpty())
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun theInspectorUrlIsRedactedFromCommandLogs() {
|
|
||||||
val line = CurseForgeApp.evalArgv(url, "x", 1_000).joinToString(" ")
|
|
||||||
assertTrue(line.contains(url))
|
|
||||||
assertTrue(!GuestCommand.redacted(line, CurseForgeApp.INSPECTOR).contains("127.0.0.1"))
|
|
||||||
assertTrue(!GuestCommand.redacted(url, CurseForgeApp.INSPECTOR).contains(url))
|
|
||||||
}
|
|
||||||
|
|
||||||
private class Curse(val addOns: File, val flavor: String = "") {
|
|
||||||
val projects = java.util.concurrent.CopyOnWriteArrayList<JSONObject>()
|
|
||||||
val methods = java.util.Collections.synchronizedList(mutableListOf<String>())
|
|
||||||
@Volatile var unreachableAfterDelete = false
|
|
||||||
@Volatile var unreachable = false
|
|
||||||
|
|
||||||
fun add(id: String, folder: String, status: Int) = add(id, listOf(folder), status)
|
|
||||||
|
|
||||||
fun add(id: String, folders: List<String>, status: Int, onDisk: List<String> = folders) {
|
|
||||||
onDisk.forEach { File(addOns, it).mkdirs() }
|
|
||||||
projects += JSONObject().put("id", id).put("installedModId", "m_$id").put("status", status).put("locked", false).put("folders", JSONArray(folders))
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun folders(p: JSONObject) = (0 until p.getJSONArray("folders").length()).map { p.getJSONArray("folders").getString(it) }
|
|
||||||
|
|
||||||
fun answer(expression: String): Any? {
|
|
||||||
val method = Regex("s\\[\\\\\"(\\w+)\\\\\"\\]").find(expression)?.groupValues?.get(1) ?: return true
|
|
||||||
methods += method
|
|
||||||
return when (method) {
|
|
||||||
"scanGameInstance" -> {
|
|
||||||
projects.removeAll { p -> !File(addOns, p.getJSONArray("folders").getString(0)).isDirectory }
|
|
||||||
true
|
|
||||||
}
|
|
||||||
"getProjects" -> JSONArray(projects.map { JSONObject(it.toString()) })
|
|
||||||
"updateMod" -> {
|
|
||||||
projects.forEach { it.put("status", 1) }
|
|
||||||
true
|
|
||||||
}
|
|
||||||
"detectGameFromPath" -> JSONObject().put("gameInstanceGuid", "g")
|
|
||||||
"getGameInstances" -> JSONArray().put(JSONObject().put("guid", "g").put("installPath", flavor))
|
|
||||||
"deleteMods" -> {
|
|
||||||
projects.removeAll { p ->
|
|
||||||
(p.getString("installedModId") in expression).also { gone ->
|
|
||||||
if (gone) folders(p).forEach { name -> WowAddons.folder(addOns, name)?.deleteRecursively() }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (unreachableAfterDelete) unreachable = true
|
|
||||||
JSONArray()
|
|
||||||
}
|
|
||||||
else -> true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun fakeCurse(addOns: File = temp.newFolder("AddOns"), flavor: String = "", calls: MutableList<List<String>> = mutableListOf()): Curse {
|
|
||||||
val curse = Curse(addOns, flavor)
|
|
||||||
CurseForgeApp.guest = { _, argv, cancelled, onLine ->
|
|
||||||
calls += argv
|
|
||||||
when {
|
|
||||||
argv[0] == CurseForgeApp.HELPER && argv[1] == "start" -> {
|
|
||||||
onLine(url)
|
|
||||||
while (cancelled?.get() != true) Thread.sleep(10)
|
|
||||||
0
|
|
||||||
}
|
|
||||||
argv[0] == CurseForgeApp.HELPER -> 0
|
|
||||||
curse.unreachable -> {
|
|
||||||
onLine(JSONObject().put("ok", false).put("error", JSONObject().put("code", "DEVTOOLS_UNREACHABLE").put("message", "gone")).toString())
|
|
||||||
0
|
|
||||||
}
|
|
||||||
else -> {
|
|
||||||
val value = JSONObject().put("value", curse.answer(argv[4]) ?: JSONObject.NULL)
|
|
||||||
onLine(JSONObject().put("ok", true).put("value", value.toString()).toString())
|
|
||||||
0
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return curse
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun wow(): WowAddons.Target {
|
|
||||||
val context = org.robolectric.RuntimeEnvironment.getApplication()
|
|
||||||
val games = temp.newFolder("Games")
|
|
||||||
val addOns = File(games, "World of Warcraft/_retail_/Interface/AddOns").apply { mkdirs() }
|
|
||||||
com.droiddeck.launcher.session.SessionPrefs.setGameFolderBinds(context, listOf(games.absolutePath to "/root/Games"))
|
|
||||||
return WowAddons.Target("_retail_", addOns)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun anEntryCurseForgeStillListsShowsAsNotInstalledOnceItsFolderIsGone() {
|
|
||||||
val curse = fakeCurse()
|
|
||||||
val context = org.robolectric.RuntimeEnvironment.getApplication()
|
|
||||||
curse.add("298842", "Leatrix_Maps", 1)
|
|
||||||
curse.add("18808", "TomTom", 1)
|
|
||||||
assertTrue(File(curse.addOns, "Leatrix_Maps").deleteRecursively())
|
|
||||||
val listed = CurseForgeApp.projects(context, url, "g")
|
|
||||||
assertEquals(listOf("298842", "18808"), listed.map { it.id })
|
|
||||||
assertEquals(listOf("18808"), CurseForgeApp.onDisk(listed, curse.addOns).map { it.id })
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun aProjectWithAnyFolderMissingOrNoFoldersIsNotInstalled() {
|
|
||||||
val addOns = temp.newFolder("Split")
|
|
||||||
File(addOns, "DBM-Core").mkdirs()
|
|
||||||
val split = CurseForgeApp.Project("3358", "m_3358", listOf("DBM-Core", "DBM-StatusBarTimers"), false)
|
|
||||||
val bare = CurseForgeApp.Project("1", "m_1", emptyList(), false)
|
|
||||||
assertTrue(CurseForgeApp.onDisk(listOf(split, bare), addOns).isEmpty())
|
|
||||||
File(addOns, "DBM-StatusBarTimers").mkdirs()
|
|
||||||
assertEquals(listOf("3358"), CurseForgeApp.onDisk(listOf(split, bare), addOns).map { it.id })
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun aDeleteWhileCurseForgeIsLinkedGoesThroughItsUninstall() {
|
|
||||||
val context = org.robolectric.RuntimeEnvironment.getApplication()
|
|
||||||
val target = wow()
|
|
||||||
val curse = fakeCurse(target.addOns, "/root/Games/World of Warcraft/_retail_")
|
|
||||||
curse.add("298842", "Leatrix_Maps", 1)
|
|
||||||
curse.add("18808", "TomTom", 1)
|
|
||||||
val link = com.droiddeck.launcher.ui.CurseLink(app)
|
|
||||||
try {
|
|
||||||
link.call(context, target) { CurseForgeApp.projects(context, it.inspector, it.guid) }
|
|
||||||
assertTrue(com.droiddeck.launcher.ui.CurseLink.live() === link)
|
|
||||||
com.droiddeck.launcher.ui.deleteAddon(context, target, "Leatrix_Maps")
|
|
||||||
assertTrue("deleteMods" in curse.methods)
|
|
||||||
assertFalse(File(target.addOns, "Leatrix_Maps").exists())
|
|
||||||
assertEquals(listOf("18808"), CurseForgeApp.projects(context, url, "g").map { it.id })
|
|
||||||
} finally {
|
|
||||||
link.close(context)
|
|
||||||
}
|
|
||||||
assertNull(com.droiddeck.launcher.ui.CurseLink.live())
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun aDeleteWithoutALiveLinkRemovesTheFolderAtOnceWithoutStartingCurseForge() {
|
|
||||||
val context = org.robolectric.RuntimeEnvironment.getApplication()
|
|
||||||
val target = wow()
|
|
||||||
val calls = java.util.Collections.synchronizedList(mutableListOf<List<String>>())
|
|
||||||
val curse = fakeCurse(target.addOns, "/root/Games/World of Warcraft/_retail_", calls)
|
|
||||||
curse.add("298842", "Leatrix_Maps", 1)
|
|
||||||
assertNull(com.droiddeck.launcher.ui.CurseLink.live())
|
|
||||||
com.droiddeck.launcher.ui.deleteAddon(context, target, "Leatrix_Maps")
|
|
||||||
assertFalse(File(target.addOns, "Leatrix_Maps").exists())
|
|
||||||
assertTrue(calls.isEmpty())
|
|
||||||
assertTrue(CurseForgeApp.projects(context, url, "g", rescan = true).none { it.id == "298842" })
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun aLinkThatNeverStartedIsNotUsedToDelete() {
|
|
||||||
val context = org.robolectric.RuntimeEnvironment.getApplication()
|
|
||||||
val target = wow()
|
|
||||||
val calls = java.util.Collections.synchronizedList(mutableListOf<List<String>>())
|
|
||||||
val curse = fakeCurse(target.addOns, "/root/Games/World of Warcraft/_retail_", calls)
|
|
||||||
curse.add("298842", "Leatrix_Maps", 1)
|
|
||||||
com.droiddeck.launcher.ui.deleteAddon(context, target, "Leatrix_Maps", com.droiddeck.launcher.ui.CurseLink(app))
|
|
||||||
assertFalse(File(target.addOns, "Leatrix_Maps").exists())
|
|
||||||
assertTrue(calls.isEmpty())
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun anAddonWhoseFolderWasDeletedShowsAsNotInstalledAfterTheRescan() {
|
|
||||||
val curse = fakeCurse()
|
|
||||||
val context = org.robolectric.RuntimeEnvironment.getApplication()
|
|
||||||
curse.add("298842", "Leatrix_Maps", 1)
|
|
||||||
assertEquals(listOf("298842"), CurseForgeApp.projects(context, url, "g", rescan = true).map { it.id })
|
|
||||||
assertTrue(File(curse.addOns, "Leatrix_Maps").deleteRecursively())
|
|
||||||
assertTrue(CurseForgeApp.projects(context, url, "g").isNotEmpty())
|
|
||||||
assertTrue(CurseForgeApp.projects(context, url, "g", rescan = true).isEmpty())
|
|
||||||
assertTrue("scanGameInstance" in curse.methods)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun aNewerFileShowsAsAnUpdateUntilCurseForgeUpdatesIt() {
|
|
||||||
val curse = fakeCurse()
|
|
||||||
val context = org.robolectric.RuntimeEnvironment.getApplication()
|
|
||||||
curse.add("298842", "Leatrix_Maps", 2)
|
|
||||||
curse.add("18808", "TomTom", 1)
|
|
||||||
val before = CurseForgeApp.projects(context, url, "g", rescan = true).associate { it.id to it.update }
|
|
||||||
assertEquals(mapOf("298842" to true, "18808" to false), before)
|
|
||||||
assertTrue(CurseForgeApp.update(context, url, "g", "298842"))
|
|
||||||
assertTrue("updateMod" in curse.methods)
|
|
||||||
assertTrue(CurseForgeApp.projects(context, url, "g").none { it.update })
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun uninstallingThroughCurseForgeClearsItsListAndTheFolder() {
|
|
||||||
val curse = fakeCurse()
|
|
||||||
val context = org.robolectric.RuntimeEnvironment.getApplication()
|
|
||||||
curse.add("298842", "Leatrix_Maps", 1)
|
|
||||||
curse.add("18808", "TomTom", 1)
|
|
||||||
val project = CurseForgeApp.owner(CurseForgeApp.projects(context, url, "g"), "Leatrix_Maps")!!
|
|
||||||
assertTrue(CurseForgeApp.uninstall(context, url, "g", project))
|
|
||||||
assertEquals(listOf("18808"), CurseForgeApp.projects(context, url, "g").map { it.id })
|
|
||||||
assertFalse(File(curse.addOns, "Leatrix_Maps").exists())
|
|
||||||
assertTrue(File(curse.addOns, "TomTom").isDirectory)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun anUninstallThatRemovedTheFolderBeforeCurseForgeWentAwayCountsAsDeleted() {
|
|
||||||
val context = org.robolectric.RuntimeEnvironment.getApplication()
|
|
||||||
val target = wow()
|
|
||||||
val curse = fakeCurse(target.addOns, "/root/Games/World of Warcraft/_retail_")
|
|
||||||
curse.add("298842", "Leatrix_Maps", 1)
|
|
||||||
curse.unreachableAfterDelete = true
|
|
||||||
val link = com.droiddeck.launcher.ui.CurseLink(app)
|
|
||||||
try {
|
|
||||||
link.call(context, target) { CurseForgeApp.projects(context, it.inspector, it.guid) }
|
|
||||||
val before = WowAddons.imports
|
|
||||||
com.droiddeck.launcher.ui.deleteAddon(context, target, "Leatrix_Maps")
|
|
||||||
assertTrue("deleteMods" in curse.methods)
|
|
||||||
assertFalse(File(target.addOns, "Leatrix_Maps").exists())
|
|
||||||
assertTrue(WowAddons.imports > before)
|
|
||||||
} finally {
|
|
||||||
kotlinx.coroutines.runBlocking { link.close(context).join() }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun aLocalDeleteInAProjectWithAMissingFolderKeepsItsOtherFolders() {
|
|
||||||
val context = org.robolectric.RuntimeEnvironment.getApplication()
|
|
||||||
val target = wow()
|
|
||||||
val curse = fakeCurse(target.addOns, "/root/Games/World of Warcraft/_retail_")
|
|
||||||
curse.add("3358", listOf("DBM-Core", "DBM-GUI", "DBM-StatusBarTimers"), 1, onDisk = listOf("DBM-Core", "DBM-GUI"))
|
|
||||||
curse.add("298842", "Leatrix_Maps", 1)
|
|
||||||
val link = com.droiddeck.launcher.ui.CurseLink(app)
|
|
||||||
try {
|
|
||||||
link.call(context, target) { CurseForgeApp.projects(context, it.inspector, it.guid) }
|
|
||||||
com.droiddeck.launcher.ui.deleteAddon(context, target, "DBM-Core")
|
|
||||||
assertFalse("deleteMods" in curse.methods)
|
|
||||||
assertFalse(File(target.addOns, "DBM-Core").exists())
|
|
||||||
assertTrue(File(target.addOns, "DBM-GUI").isDirectory)
|
|
||||||
com.droiddeck.launcher.ui.deleteAddon(context, target, "Leatrix_Maps")
|
|
||||||
assertTrue("deleteMods" in curse.methods)
|
|
||||||
assertFalse(File(target.addOns, "Leatrix_Maps").exists())
|
|
||||||
} finally {
|
|
||||||
kotlinx.coroutines.runBlocking { link.close(context).join() }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun foldersMatchCurseForgesNamesWhateverTheirCase() {
|
|
||||||
val context = org.robolectric.RuntimeEnvironment.getApplication()
|
|
||||||
val target = wow()
|
|
||||||
val curse = fakeCurse(target.addOns, "/root/Games/World of Warcraft/_retail_")
|
|
||||||
curse.add("12345", listOf("Questie"), 1, onDisk = listOf("questie"))
|
|
||||||
val listed = CurseForgeApp.projects(context, url, "g")
|
|
||||||
assertEquals(listOf("12345"), CurseForgeApp.onDisk(listed, target.addOns).map { it.id })
|
|
||||||
assertEquals("12345", CurseForgeApp.byFolder(listed)["questie"]?.id)
|
|
||||||
assertEquals("questie", WowAddons.folder(target.addOns, "Questie")?.name)
|
|
||||||
val link = com.droiddeck.launcher.ui.CurseLink(app)
|
|
||||||
try {
|
|
||||||
link.call(context, target) { CurseForgeApp.projects(context, it.inspector, it.guid) }
|
|
||||||
com.droiddeck.launcher.ui.deleteAddon(context, target, "Questie")
|
|
||||||
assertTrue("deleteMods" in curse.methods)
|
|
||||||
assertNull(WowAddons.folder(target.addOns, "Questie"))
|
|
||||||
} finally {
|
|
||||||
kotlinx.coroutines.runBlocking { link.close(context).join() }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun aLocalDeleteFindsTheFolderWhateverItsCaseAndAnAbsentFolderIsAlreadyDeleted() {
|
|
||||||
val context = org.robolectric.RuntimeEnvironment.getApplication()
|
|
||||||
val target = wow()
|
|
||||||
File(target.addOns, "questie").mkdirs()
|
|
||||||
File(target.addOns, "TomTom").mkdirs()
|
|
||||||
com.droiddeck.launcher.ui.deleteAddon(context, target, "Questie", null)
|
|
||||||
assertNull(WowAddons.folder(target.addOns, "Questie"))
|
|
||||||
assertTrue(File(target.addOns, "TomTom").isDirectory)
|
|
||||||
val before = WowAddons.imports
|
|
||||||
com.droiddeck.launcher.ui.deleteAddon(context, target, "Gone", null)
|
|
||||||
assertTrue(WowAddons.imports > before)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun theAgentAnswerIsTheLastJsonLine() {
|
|
||||||
assertEquals("a", CurseForgeApp.lastJson(listOf("noise", """{"v":"a"}""", "== done"))?.getString("v"))
|
|
||||||
assertNull(CurseForgeApp.lastJson(listOf("noise")))
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -15,7 +15,7 @@ class WowAddonCatalogTest {
|
|||||||
private val context get() = RuntimeEnvironment.getApplication()
|
private val context get() = RuntimeEnvironment.getApplication()
|
||||||
|
|
||||||
private val files = """[
|
private val files = """[
|
||||||
{"UID":"1","UICATID":"19","UIVersion":"1.0","UIDate":300,"UIName":"Bartender","UIAuthorName":"Nevcairiel","UIDownloadTotal":"500","UICompatibility":[{"version":"12.0.0","name":"Midnight"}],"UIIMG_Thumbs":["https://cdn.example/a.jpg"],"UIDir":["Bartender4"," Bartender4_Options "]},
|
{"UID":"1","UICATID":"19","UIVersion":"1.0","UIDate":300,"UIName":"Bartender","UIAuthorName":"Nevcairiel","UIDownloadTotal":"500","UICompatibility":[{"version":"12.0.0","name":"Midnight"}],"UIIMG_Thumbs":["https://cdn.example/a.jpg"]},
|
||||||
{"UID":"2","UICATID":"20","UIVersion":"2.0","UIDate":100,"UIName":"Zygor","UIAuthorName":"Kappa","UIDownloadTotal":"900","UICompatibility":[{"version":"1.15.7","name":"Classic"},{"version":"4.4.2","name":"Cataclysm Classic"}],"UIIMG_Thumbs":null},
|
{"UID":"2","UICATID":"20","UIVersion":"2.0","UIDate":100,"UIName":"Zygor","UIAuthorName":"Kappa","UIDownloadTotal":"900","UICompatibility":[{"version":"1.15.7","name":"Classic"},{"version":"4.4.2","name":"Cataclysm Classic"}],"UIIMG_Thumbs":null},
|
||||||
{"UID":"3","UICATID":"21","UIVersion":"3.0","UIDate":200,"UIName":"Alpha","UIAuthorName":"bartuser","UIDownloadTotal":"10","UIDownloadMonthly":"9","UICompatibility":null},
|
{"UID":"3","UICATID":"21","UIVersion":"3.0","UIDate":200,"UIName":"Alpha","UIAuthorName":"bartuser","UIDownloadTotal":"10","UIDownloadMonthly":"9","UICompatibility":null},
|
||||||
{"UID":"4","UICATID":"19","UIVersion":"4.0","UIDate":400,"UIName":"TBCOnly","UIAuthorName":"x","UIDownloadTotal":"20","UIDownloadMonthly":"5","UICompatibility":[{"version":"2.5.4","name":"The Burning Crusade Classic"}]}
|
{"UID":"4","UICATID":"19","UIVersion":"4.0","UIDate":400,"UIName":"TBCOnly","UIAuthorName":"x","UIDownloadTotal":"20","UIDownloadMonthly":"5","UICompatibility":[{"version":"2.5.4","name":"The Burning Crusade Classic"}]}
|
||||||
@@ -44,12 +44,6 @@ class WowAddonCatalogTest {
|
|||||||
assertEquals("19", e[0].category)
|
assertEquals("19", e[0].category)
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test fun fileListEntriesCarryTheirAddonFolders() {
|
|
||||||
val e = WowAddonCatalog.parseWowiFiles(files)
|
|
||||||
assertEquals(listOf("Bartender4", "Bartender4_Options"), e[0].addon.folders)
|
|
||||||
assertEquals(emptyList<String>(), e[1].addon.folders)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test fun versionsMapToFlavors() {
|
@Test fun versionsMapToFlavors() {
|
||||||
assertEquals("_retail_", WowAddonCatalog.flavorOf("12.1.0"))
|
assertEquals("_retail_", WowAddonCatalog.flavorOf("12.1.0"))
|
||||||
assertEquals("_retail_", WowAddonCatalog.flavorOf("11.0.5"))
|
assertEquals("_retail_", WowAddonCatalog.flavorOf("11.0.5"))
|
||||||
@@ -204,32 +198,6 @@ us|1|aa|bb|cc||tpr/wow|h|s|t||1|12.1.0.65000|kk|wowf
|
|||||||
assertFalse(WowAddonCatalog.sameVersion("1.2.3", "1.2.4"))
|
assertFalse(WowAddonCatalog.sameVersion("1.2.3", "1.2.4"))
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test fun versionsCompareNumericSegmentsFirst() {
|
|
||||||
assertEquals(true, WowAddonCatalog.newer("v4.11.38-7-ge56e9d8", "4.11.39"))
|
|
||||||
assertEquals(true, WowAddonCatalog.newer("1.9", "1.10"))
|
|
||||||
assertEquals(true, WowAddonCatalog.newer("2", "2.0.1"))
|
|
||||||
assertEquals(false, WowAddonCatalog.newer("11.2.0", "6.2.5"))
|
|
||||||
assertEquals(false, WowAddonCatalog.newer("2.0", "2"))
|
|
||||||
assertNull(WowAddonCatalog.newer("11.4.10-beta1", "11.4.10"))
|
|
||||||
assertNull(WowAddonCatalog.newer("release", "1.0"))
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test fun anUpdateIsOfferedOnlyForANewerVersionOrTheSameSourcesCurrentFile() {
|
|
||||||
assertTrue(WowAddonCatalog.offersUpdate("1.9", "1.10", sameSource = false))
|
|
||||||
assertFalse(WowAddonCatalog.offersUpdate("11.2.0", "6.2.5", sameSource = true))
|
|
||||||
assertFalse(WowAddonCatalog.offersUpdate("v1.2", "1.2", sameSource = true))
|
|
||||||
assertTrue(WowAddonCatalog.offersUpdate("11.4.10-beta1", "11.4.10", sameSource = true))
|
|
||||||
assertFalse(WowAddonCatalog.offersUpdate("11.4.10-beta1", "11.4.10", sameSource = false))
|
|
||||||
assertFalse(WowAddonCatalog.offersUpdate(null, "1.0", sameSource = true))
|
|
||||||
assertFalse(WowAddonCatalog.offersUpdate("1.0", "", sameSource = true))
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test fun findUpdatesNeverOffersADowngrade() {
|
|
||||||
val installed = listOf(WowAddons.Installed("Ahead", "3.0", "10"), WowAddons.Installed("Tagged", "r55-alpha", "20"))
|
|
||||||
val updates = WowAddonCatalog.findUpdates(listOf(entry("10", "2.9"), entry("20", "r56")), installed)
|
|
||||||
assertEquals(setOf("Tagged"), updates.keys)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test fun md5Check() {
|
@Test fun md5Check() {
|
||||||
val f = File(context.cacheDir, "wowaddon-md5-test.zip")
|
val f = File(context.cacheDir, "wowaddon-md5-test.zip")
|
||||||
f.writeText("hello")
|
f.writeText("hello")
|
||||||
|
|||||||
@@ -220,74 +220,24 @@ class WowAddonsTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test fun tocFieldsReadVersionAndSourceIds() {
|
@Test fun tocFieldsReadVersionAndSourceIds() {
|
||||||
val fields = WowAddons.tocFields("\uFEFF## Interface: 110002\n## Title: Foo\n## Version: 1.4.2\n## X-WoWI-ID: 1234\n## Version: 9\n## X-Curse-Project-ID: @curse-id@\nFoo.lua\n".lineSequence(), setOf("Version", "X-WoWI-ID", "X-Curse-Project-ID"))
|
val fields = WowAddons.tocFields("\uFEFF## Interface: 110002\n## Title: Foo\n## Version: 1.4.2\n## X-WoWI-ID: 1234\n## Version: 9\n## X-Curse-Project-ID: @curse-id@\nFoo.lua\n")
|
||||||
assertEquals("1.4.2", fields["Version"])
|
assertEquals("1.4.2", fields["Version"])
|
||||||
assertEquals("1234", fields["X-WoWI-ID"])
|
assertEquals("1234", fields["X-WoWI-ID"])
|
||||||
assertEquals(null, fields["X-Curse-Project-ID"])
|
assertEquals(null, fields["X-Curse-Project-ID"])
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test fun tocFieldsKeepOnlyTheRequestedKeysAndStopOnceFound() {
|
|
||||||
var read = 0
|
|
||||||
val lines = sequence {
|
|
||||||
yield("## Version: 2.0")
|
|
||||||
yield("## X-WoWI-ID: 5")
|
|
||||||
yield("## X-Curse-Project-ID: 9")
|
|
||||||
repeat(100_000) { read++; yield("## X-Data-$it: payload") }
|
|
||||||
}
|
|
||||||
val fields = WowAddons.tocFields(lines)
|
|
||||||
assertEquals(mapOf("Version" to "2.0", "X-WoWI-ID" to "5", "X-Curse-Project-ID" to "9"), fields)
|
|
||||||
assertEquals(0, read)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test fun detailsSkipDataRowsInLargeTocs() {
|
|
||||||
val target = target()
|
|
||||||
val db = File(target.addOns, "BigDB").apply { mkdirs() }
|
|
||||||
File(db, "BigDB_Mists.toc").bufferedWriter().use { w ->
|
|
||||||
w.write("## Title: BigDB\nsrc\\main.lua\n")
|
|
||||||
repeat(50_000) { w.write("## X-Data-$it: ${"x".repeat(200)}\n") }
|
|
||||||
w.write("## Version: 3.1\n")
|
|
||||||
}
|
|
||||||
val details = WowAddons.details(target).single()
|
|
||||||
assertEquals("3.1", details.version)
|
|
||||||
assertEquals(null, details.wowiId)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test fun detailsUseTheTocAndTheRecordedSource() {
|
@Test fun detailsUseTheTocAndTheRecordedSource() {
|
||||||
val target = target()
|
val target = target()
|
||||||
val foo = File(target.addOns, "Foo").apply { mkdirs() }
|
val foo = File(target.addOns, "Foo").apply { mkdirs() }
|
||||||
File(foo, "Foo_Mainline.toc").writeText("## Version: 1.0\n## X-WoWI-ID: 77\n## X-Curse-Project-ID: 334372\n")
|
File(foo, "Foo_Mainline.toc").writeText("## Version: 1.0\n## X-WoWI-ID: 77\n")
|
||||||
File(target.addOns, "Bar").mkdirs()
|
File(target.addOns, "Bar").mkdirs()
|
||||||
val details = WowAddons.details(target).associateBy { it.name }
|
val details = WowAddons.details(target).associateBy { it.name }
|
||||||
assertEquals(setOf("Bar", "Foo"), details.keys)
|
assertEquals(setOf("Bar", "Foo"), details.keys)
|
||||||
assertEquals("1.0", details.getValue("Foo").version)
|
assertEquals("1.0", details.getValue("Foo").version)
|
||||||
assertEquals("77", details.getValue("Foo").wowiId)
|
assertEquals("77", details.getValue("Foo").wowiId)
|
||||||
assertEquals("334372", details.getValue("Foo").curseId)
|
|
||||||
assertEquals(null, details.getValue("Bar").curseId)
|
|
||||||
assertEquals(null, details.getValue("Bar").version)
|
assertEquals(null, details.getValue("Bar").version)
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test fun detailsFillFieldsTheMainTocLacksFromTheFlavourTocs() {
|
|
||||||
val target = target()
|
|
||||||
val questie = File(target.addOns, "Questie").apply { mkdirs() }
|
|
||||||
File(questie, "Questie.toc").writeText("## Interface: 00000\n## Title: Questie\n")
|
|
||||||
File(questie, "Questie_Vanilla.toc").writeText("## Version: 12.6.4\n## X-Curse-Project-ID: 334372\n")
|
|
||||||
File(questie, "Questie_Wrath.toc").writeText("## Version: 12.6.4\n")
|
|
||||||
val questieDetails = WowAddons.details(target).single()
|
|
||||||
assertEquals("12.6.4", questieDetails.version)
|
|
||||||
assertEquals("334372", questieDetails.curseId)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test fun detailsKeepTheMainTocWhenItHasTheFields() {
|
|
||||||
val target = target()
|
|
||||||
val foo = File(target.addOns, "Foo").apply { mkdirs() }
|
|
||||||
File(foo, "Foo.toc").writeText("## Version: 2.0\n## X-Curse-Project-ID: 5\n")
|
|
||||||
File(foo, "Foo_Classic.toc").writeText("## Version: 1.0\n## X-Curse-Project-ID: 6\n## X-WoWI-ID: 7\n")
|
|
||||||
val fooDetails = WowAddons.details(target).single()
|
|
||||||
assertEquals("2.0", fooDetails.version)
|
|
||||||
assertEquals("5", fooDetails.curseId)
|
|
||||||
assertEquals("7", fooDetails.wowiId)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test fun importRecordsTheSourceAndPlainImportsClearIt() {
|
@Test fun importRecordsTheSourceAndPlainImportsClearIt() {
|
||||||
val target = target()
|
val target = target()
|
||||||
WowAddons.import(zip("Foo/Foo.toc" to "## Version: 1.0\n"), target, WowAddons.Origin("55", "2.0"))
|
WowAddons.import(zip("Foo/Foo.toc" to "## Version: 1.0\n"), target, WowAddons.Origin("55", "2.0"))
|
||||||
|
|||||||
@@ -0,0 +1,139 @@
|
|||||||
|
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 aTwinAGameChoiceStillNeedsCannotBeDeletedAsUnused() {
|
||||||
|
val state = JSONObject().put("profiles", JSONObject().put("42", JSONObject().put("fex", "FEXCore-2611.1-linux.wcp")))
|
||||||
|
assertEquals(bionicTool, ComponentsManager.twinUser(state, listOf(proton(ownTool), proton(bionicTool)), "FEXCore-2611.1-bionic.wcp")?.dir?.name)
|
||||||
|
assertEquals(null, ComponentsManager.twinUser(state, listOf(proton(ownTool)), "FEXCore-2611.1-bionic.wcp"))
|
||||||
|
assertEquals(null, ComponentsManager.twinUser(state, listOf(proton(ownTool), proton(bionicTool)), "FEXCore-2610-bionic.wcp"))
|
||||||
|
assertEquals(null, ComponentsManager.twinUser(JSONObject(), listOf(proton(bionicTool)), "FEXCore-2611.1-bionic.wcp"))
|
||||||
|
}
|
||||||
|
|
||||||
|
@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.json.JSONObject
|
||||||
import org.junit.Assert.assertEquals
|
import org.junit.Assert.assertEquals
|
||||||
import org.junit.Assert.assertFalse
|
import org.junit.Assert.assertFalse
|
||||||
|
import org.junit.Assert.assertThrows
|
||||||
import org.junit.Assert.assertTrue
|
import org.junit.Assert.assertTrue
|
||||||
import org.junit.Before
|
import org.junit.Before
|
||||||
import org.junit.Test
|
import org.junit.Test
|
||||||
@@ -23,6 +24,7 @@ class ComponentsRepublishTest {
|
|||||||
private val fex = "FEXCore-2610-d2rfix28-linux.wcp"
|
private val fex = "FEXCore-2610-d2rfix28-linux.wcp"
|
||||||
private val scope = "2596113170"
|
private val scope = "2596113170"
|
||||||
private val dll = "files/lib/wine/aarch64-windows/libwow64fex.dll"
|
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
|
private lateinit var context: Context
|
||||||
|
|
||||||
@Before fun setUp() {
|
@Before fun setUp() {
|
||||||
@@ -48,6 +50,61 @@ class ComponentsRepublishTest {
|
|||||||
assertEquals(fex, ComponentsManager.gameComponents(context, scope)["fex"])
|
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() {
|
@Test fun nothingIsRewrittenWhileTheToolsAreUnchanged() {
|
||||||
proton("DroidDeck-Proton 11-11.8", "DroidDeck-Proton-11-11.8")
|
proton("DroidDeck-Proton 11-11.8", "DroidDeck-Proton-11-11.8")
|
||||||
packageFile()
|
packageFile()
|
||||||
@@ -117,18 +174,21 @@ class ComponentsRepublishTest {
|
|||||||
|
|
||||||
private fun launchState() = File(LinuxRuntime.rootDir(context), "root/.local/share/droiddeck-components/desired.tsv")
|
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) {
|
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, "files/lib/wine").mkdirs()
|
||||||
File(dir, "proton").writeText("#!/bin/sh\n")
|
File(dir, "proton").writeText("#!/bin/sh\n")
|
||||||
File(dir, "version").writeText("1 $version\n")
|
File(dir, "version").writeText("1 $version\n")
|
||||||
File(dir, dll).apply { parentFile!!.mkdirs(); writeText("bundled FEX $version") }
|
File(dir, dll).apply { parentFile!!.mkdirs(); writeText("bundled FEX $version") }
|
||||||
|
File(dir, so).apply { parentFile!!.mkdirs(); writeText("bundled unix FEX $version") }
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun packageFile() {
|
private fun packageFile(name: String = fex, type: String = "FEXCore-Linux", text: String = "d2rfix28 wow64") {
|
||||||
val out = File(context.filesDir, "components/packages/$fex").apply { parentFile!!.mkdirs() }
|
val out = File(context.filesDir, "components/packages/$name").apply { parentFile!!.mkdirs() }
|
||||||
val profile = JSONObject().put("type", "FEXCore-Linux").put("versionName", "2610-d2rfix28").toString().toByteArray()
|
val profile = JSONObject().put("type", type).put("versionName", name.removeSuffix(".wcp")).toString().toByteArray()
|
||||||
val body = "d2rfix28 wow64".toByteArray()
|
val body = text.toByteArray()
|
||||||
TarArchiveOutputStream(ZstdOutputStream(out.outputStream())).use { tar ->
|
TarArchiveOutputStream(ZstdOutputStream(out.outputStream())).use { tar ->
|
||||||
tar.putArchiveEntry(TarArchiveEntry("profile.json").apply { size = profile.size.toLong() })
|
tar.putArchiveEntry(TarArchiveEntry("profile.json").apply { size = profile.size.toLong() })
|
||||||
tar.write(profile)
|
tar.write(profile)
|
||||||
|
|||||||
@@ -98,6 +98,22 @@ class EnhancedSessionLogShareTest {
|
|||||||
SessionLogShare.clear(app)
|
SessionLogShare.clear(app)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test fun aBionicGameLogIsSharedWithTheGamesUnderItsName() {
|
||||||
|
val session = tmp.newFolder("2026-11-22-09-steam")
|
||||||
|
session.resolve("session.log").writeText("startup ok\n")
|
||||||
|
val launch = session.resolve("games/2026-11-22-201105-bionic-341940").apply { mkdirs() }
|
||||||
|
launch.resolve("droiddeck-bionic.log").writeText("20:11:05 waitforexitandrun Hatred.exe\n")
|
||||||
|
|
||||||
|
val games = EnhancedSessionLogShare.create(app, session).single { it.name.endsWith("-games.zip") }
|
||||||
|
|
||||||
|
ZipFile(games).use { archive ->
|
||||||
|
val entry = archive.getEntry("${session.name}/games/2026-11-22-201105-bionic-341940/droiddeck-bionic.log")
|
||||||
|
assertTrue(entry != null)
|
||||||
|
assertEquals("20:11:05 waitforexitandrun Hatred.exe\n", archive.getInputStream(entry).bufferedReader().readText())
|
||||||
|
}
|
||||||
|
SessionLogShare.clear(app)
|
||||||
|
}
|
||||||
|
|
||||||
@Test fun oversizedFilesKeepBoundedBeginningAndTailAndDeclareTruncation() {
|
@Test fun oversizedFilesKeepBoundedBeginningAndTailAndDeclareTruncation() {
|
||||||
val session = tmp.newFolder("2026-11-04-02-game")
|
val session = tmp.newFolder("2026-11-04-02-game")
|
||||||
session.resolve("steam-7.log").writeText("begin\n" + "middle\n".repeat(100) + "tail\n")
|
session.resolve("steam-7.log").writeText("begin\n" + "middle\n".repeat(100) + "tail\n")
|
||||||
|
|||||||
@@ -68,6 +68,19 @@ class ExperimentalProtonsTest {
|
|||||||
assertEquals(listOf("pre"), ProtonExtras.assets(tool, releases, true).map { it.tag })
|
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
|
@Test
|
||||||
fun markerRoundTripKeepsReleaseTag() {
|
fun markerRoundTripKeepsReleaseTag() {
|
||||||
val dir = File(com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(activity), "root/.local/share/Steam/compatibilitytools.d/Experimental-pre").apply { mkdirs() }
|
val dir = File(com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(activity), "root/.local/share/Steam/compatibilitytools.d/Experimental-pre").apply { mkdirs() }
|
||||||
|
|||||||
@@ -127,4 +127,90 @@ class ProtonDefaultTest {
|
|||||||
assertTrue(games.containsKey("43"))
|
assertTrue(games.containsKey("43"))
|
||||||
assertNull(games["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
|
@Test
|
||||||
fun theThreeSourcesInOrder() {
|
fun theSourcesInOrder() {
|
||||||
assertEquals(listOf("ge", "cachyos", "droiddeck"), ProtonExtras.tools.map { it.id })
|
assertEquals(listOf("ge", "cachyos", "droiddeck", "bionic"), ProtonExtras.tools.map { it.id })
|
||||||
val droiddeck = tool("droiddeck")
|
val droiddeck = tool("droiddeck")
|
||||||
assertEquals("DroidDeck-Proton", droiddeck.name)
|
assertEquals("DroidDeck-Proton", droiddeck.name)
|
||||||
assertEquals("DroidDeck-Proton", droiddeck.prefix)
|
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"))
|
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
|
@Test
|
||||||
fun theTarballAndItsSha512FileArePicked() {
|
fun theTarballAndItsSha512FileArePicked() {
|
||||||
val picked = ProtonExtras.pickAsset(tool("droiddeck"), JSONArray().put(droiddeckRelease("11-7.5")))!!
|
val picked = ProtonExtras.pickAsset(tool("droiddeck"), JSONArray().put(droiddeckRelease("11-7.5")))!!
|
||||||
@@ -206,6 +229,22 @@ class ProtonExtrasTest {
|
|||||||
assertNull(ProtonExtras.update(context, tool("droiddeck")))
|
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
|
@Test
|
||||||
fun removingDeletesOneBuildOrEveryOlderOne() {
|
fun removingDeletesOneBuildOrEveryOlderOne() {
|
||||||
val context = RuntimeEnvironment.getApplication()
|
val context = RuntimeEnvironment.getApplication()
|
||||||
|
|||||||
@@ -168,8 +168,8 @@ class StoreGameSidecarTest {
|
|||||||
"if \"%DD_EPIC_PARENT%\"==\"1\" set \"DD_P=1\"",
|
"if \"%DD_EPIC_PARENT%\"==\"1\" set \"DD_P=1\"",
|
||||||
"if \"%DD_EPIC_PARENT%\"==\"0\" set \"DD_P=\"",
|
"if \"%DD_EPIC_PARENT%\"==\"0\" set \"DD_P=\"",
|
||||||
"if defined DD_P set \"SteamAppId=\"",
|
"if defined DD_P set \"SteamAppId=\"",
|
||||||
"if defined DD_P if not exist \"Z:\\usr\\local\\lib\\droiddeck-epic\\EpicGamesLauncher.exe\" set \"DD_P=\"",
|
"if defined DD_P if not exist \"%DD_R%\\usr\\local\\lib\\droiddeck-epic\\EpicGamesLauncher.exe\" set \"DD_P=\"",
|
||||||
"if defined DD_P set DD_P=\"Z:\\usr\\local\\lib\\droiddeck-epic\\EpicGamesLauncher.exe\"",
|
"if defined DD_P set DD_P=\"%DD_R%\\usr\\local\\lib\\droiddeck-epic\\EpicGamesLauncher.exe\"",
|
||||||
)
|
)
|
||||||
|
|
||||||
@Test fun epicTitlesThatCheckTheirParentStartUnderTheStandIn() {
|
@Test fun epicTitlesThatCheckTheirParentStartUnderTheStandIn() {
|
||||||
|
|||||||
@@ -105,11 +105,28 @@ class UbisoftTest {
|
|||||||
val text = StoreLaunch.launcherText(StoreGameSidecar(Store.UBISOFT, "space-sc", "Splinter Cell", "system/SplinterCell.exe"))
|
val text = StoreLaunch.launcherText(StoreGameSidecar(Store.UBISOFT, "space-sc", "Splinter Cell", "system/SplinterCell.exe"))
|
||||||
val lines = text.trimEnd().split("\r\n")
|
val lines = text.trimEnd().split("\r\n")
|
||||||
assertTrue(lines.contains("if not exist \"%~dp0.droiddeck-ubisoft.json\" goto direct"))
|
assertTrue(lines.contains("if not exist \"%~dp0.droiddeck-ubisoft.json\" goto direct"))
|
||||||
assertTrue(lines.contains("\"Z:\\usr\\local\\lib\\droiddeck-ubisoft\\droiddeck-upc.exe\" \"%~dp0.droiddeck-ubisoft.json\""))
|
val service = lines.indexOf("\"%DD_R%\\usr\\local\\lib\\droiddeck-ubisoft\\droiddeck-upc.exe\" \"%~dp0.droiddeck-ubisoft.json\"")
|
||||||
|
assertTrue(service in 0 until lines.indexOf(":direct"))
|
||||||
|
assertTrue(lines.indexOf("set \"DD_R=Z:\"") in 0 until lines.indexOf("if defined DROIDDECK_GUEST_ROOT set \"DD_R=%DROIDDECK_GUEST_ROOT%\""))
|
||||||
|
assertTrue(lines.indexOf("if defined DROIDDECK_GUEST_ROOT set \"DD_R=%DROIDDECK_GUEST_ROOT%\"") < service)
|
||||||
assertEquals("\"%~dp0system\\SplinterCell.exe\"", lines.last())
|
assertEquals("\"%~dp0system\\SplinterCell.exe\"", lines.last())
|
||||||
assertTrue(lines.indexOf(":direct") < lines.lastIndex)
|
assertTrue(lines.indexOf(":direct") < lines.lastIndex)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test fun anInstalledGamesOlderLauncherIsRewritten() {
|
||||||
|
val folder = java.nio.file.Files.createTempDirectory("ubisoft-adopt").toFile()
|
||||||
|
try {
|
||||||
|
File(folder, "system").mkdirs()
|
||||||
|
File(folder, "system/SplinterCell.exe").writeText("exe")
|
||||||
|
val sidecar = StoreGameSidecar(Store.UBISOFT, "space-sc", "Splinter Cell", "system/SplinterCell.exe", launcher = StoreLaunch.LAUNCHER)
|
||||||
|
File(folder, StoreLaunch.LAUNCHER).writeText("@echo off\r\nif not exist \"Z:\\usr\\local\\lib\\droiddeck-ubisoft\\droiddeck-upc.exe\" goto direct\r\n")
|
||||||
|
StoreLaunch.adopt(folder, sidecar)
|
||||||
|
assertEquals(StoreLaunch.launcherText(sidecar), File(folder, StoreLaunch.LAUNCHER).readText())
|
||||||
|
} finally {
|
||||||
|
folder.deleteRecursively()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@Test fun activationPayloadsSurviveTheHexHop() {
|
@Test fun activationPayloadsSurviveTheHexHop() {
|
||||||
val bytes = byteArrayOf(0, 1, 0x7f, -1, -128, 42)
|
val bytes = byteArrayOf(0, 1, 0x7f, -1, -128, 42)
|
||||||
assertEquals("00017fff802a", UbisoftActivation.hex(bytes))
|
assertEquals("00017fff802a", UbisoftActivation.hex(bytes))
|
||||||
|
|||||||
@@ -1,94 +0,0 @@
|
|||||||
package com.droiddeck.launcher.ui
|
|
||||||
|
|
||||||
import androidx.compose.runtime.mutableStateOf
|
|
||||||
import androidx.compose.ui.Modifier
|
|
||||||
import androidx.compose.ui.test.assertCountEquals
|
|
||||||
import androidx.compose.ui.test.onAllNodesWithText
|
|
||||||
import androidx.compose.ui.test.onNodeWithText
|
|
||||||
import androidx.compose.ui.test.performClick
|
|
||||||
import com.droiddeck.launcher.R
|
|
||||||
import com.droiddeck.launcher.runtime.WowAddonCatalog
|
|
||||||
import com.droiddeck.launcher.runtime.WowAddons
|
|
||||||
import org.junit.Assert.assertEquals
|
|
||||||
import org.junit.Rule
|
|
||||||
import org.junit.Test
|
|
||||||
import org.junit.runner.RunWith
|
|
||||||
import org.robolectric.RobolectricTestRunner
|
|
||||||
import org.robolectric.RuntimeEnvironment
|
|
||||||
import org.robolectric.annotation.Config
|
|
||||||
|
|
||||||
@RunWith(RobolectricTestRunner::class)
|
|
||||||
@Config(sdk = [28], qualifiers = "w960dp-h540dp-land", application = android.app.Application::class)
|
|
||||||
class AddonRowTest {
|
|
||||||
@get:Rule val compose = createRobolectricComposeRule()
|
|
||||||
|
|
||||||
private val addon = WowAddonCatalog.Addon("298842", "Leatrix Maps", "Leatrix", "", 0, 0, null)
|
|
||||||
private fun text(id: Int) = RuntimeEnvironment.getApplication().getString(id)
|
|
||||||
|
|
||||||
private fun show(status: AddonStatus, uninstalls: MutableList<String> = mutableListOf(), installs: MutableList<String> = mutableListOf()) {
|
|
||||||
val state = mutableStateOf(status)
|
|
||||||
compose.setContent {
|
|
||||||
DroidDeckTheme {
|
|
||||||
AddonRow(addon, state.value, null, Modifier, { uninstalls += addon.id }) { installs += addon.id }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test fun aMissingAddonOffersOnlyInstall() {
|
|
||||||
val installs = mutableListOf<String>()
|
|
||||||
show(AddonStatus.INSTALL, installs = installs)
|
|
||||||
compose.onAllNodesWithText(text(R.string.common_uninstall)).assertCountEquals(0)
|
|
||||||
compose.onAllNodesWithText(text(R.string.common_update)).assertCountEquals(0)
|
|
||||||
compose.onNodeWithText(text(R.string.store_install)).performClick()
|
|
||||||
assertEquals(listOf("298842"), installs)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test fun aCurrentAddonOffersOnlyUninstallAfterAConfirm() {
|
|
||||||
val uninstalls = mutableListOf<String>()
|
|
||||||
show(AddonStatus.INSTALLED, uninstalls)
|
|
||||||
compose.onAllNodesWithText(text(R.string.store_install)).assertCountEquals(0)
|
|
||||||
compose.onAllNodesWithText(text(R.string.common_update)).assertCountEquals(0)
|
|
||||||
compose.onAllNodesWithText(text(R.string.stores_installed_chip)).assertCountEquals(0)
|
|
||||||
compose.onNodeWithText(text(R.string.common_uninstall)).performClick()
|
|
||||||
assertEquals(emptyList<String>(), uninstalls)
|
|
||||||
compose.onAllNodesWithText(text(R.string.common_uninstall))[1].performClick()
|
|
||||||
assertEquals(listOf("298842"), uninstalls)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test fun anOutdatedAddonOffersUpdateAndUninstall() {
|
|
||||||
val installs = mutableListOf<String>()
|
|
||||||
show(AddonStatus.UPDATE, installs = installs)
|
|
||||||
compose.onAllNodesWithText(text(R.string.common_uninstall)).assertCountEquals(1)
|
|
||||||
compose.onNodeWithText(text(R.string.common_update)).performClick()
|
|
||||||
assertEquals(listOf("298842"), installs)
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun disk(vararg addons: WowAddons.Installed) = addons.associateBy { it.name.lowercase() }
|
|
||||||
|
|
||||||
@Test fun anotherSourcesAddonOnDiskIsUpdatableOnlyToANewerVersion() {
|
|
||||||
val onDisk = disk(WowAddons.Installed("Questie", "11.2.0", null), WowAddons.Installed("QuestieDB", null, null))
|
|
||||||
assertEquals(AddonStatus.INSTALLED, diskStatus(listOf("Questie"), onDisk, "6.2.5", "1"))
|
|
||||||
assertEquals(AddonStatus.UPDATE, diskStatus(listOf("Questie"), onDisk, "11.3.0", "1"))
|
|
||||||
assertEquals(AddonStatus.INSTALLED, diskStatus(listOf("Questie"), onDisk, "v11.2.0", "1"))
|
|
||||||
assertEquals(AddonStatus.INSTALLED, diskStatus(listOf("QuestieDB"), onDisk, "1.0", "1"))
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test fun anIncomparableVersionIsAnUpdateOnlyFromTheSameSource() {
|
|
||||||
val onDisk = disk(WowAddons.Installed("TomTom", "v4.0.1-release", "12"))
|
|
||||||
assertEquals(AddonStatus.UPDATE, diskStatus(listOf("TomTom"), onDisk, "v4.0.1-beta", "12"))
|
|
||||||
assertEquals(AddonStatus.INSTALLED, diskStatus(listOf("TomTom"), onDisk, "v4.0.1-beta", "99"))
|
|
||||||
assertEquals(AddonStatus.INSTALLED, diskStatus(listOf("TomTom"), onDisk, "4.0.0", "12"))
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test fun foldersOnDiskMatchWhateverTheirCase() {
|
|
||||||
val onDisk = disk(WowAddons.Installed("questie", "11.2.0", null))
|
|
||||||
assertEquals(AddonStatus.INSTALLED, diskStatus(listOf("Questie"), onDisk, "11.2.0", "1"))
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test fun anAddonCountsAsInstalledOnlyWhenEveryFolderIsOnDisk() {
|
|
||||||
val onDisk = disk(WowAddons.Installed("Bartender4", "4.19.2", null))
|
|
||||||
assertEquals(AddonStatus.INSTALL, diskStatus(listOf("Bartender4", "Bartender4_Options"), onDisk, "4.19.2", "1"))
|
|
||||||
assertEquals(AddonStatus.INSTALL, diskStatus(emptyList(), onDisk, "4.19.2", "1"))
|
|
||||||
assertEquals(AddonStatus.INSTALL, diskStatus(listOf("TomTom"), onDisk, "4.4.1", "1"))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,68 +0,0 @@
|
|||||||
package com.droiddeck.launcher.ui
|
|
||||||
|
|
||||||
import com.droiddeck.launcher.runtime.CurseForgeApp
|
|
||||||
import com.droiddeck.launcher.runtime.WowAddons
|
|
||||||
import org.junit.Assert.assertEquals
|
|
||||||
import org.junit.Rule
|
|
||||||
import org.junit.Test
|
|
||||||
import org.junit.rules.TemporaryFolder
|
|
||||||
|
|
||||||
class CurseLinkReportTest {
|
|
||||||
@get:Rule val temp = TemporaryFolder()
|
|
||||||
|
|
||||||
private fun target(vararg folders: String): WowAddons.Target {
|
|
||||||
val addOns = temp.newFolder("AddOns")
|
|
||||||
folders.forEach { java.io.File(addOns, it).mkdirs() }
|
|
||||||
return WowAddons.Target("_retail_", addOns)
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun project(id: String, vararg folders: String, update: Boolean = false) = CurseForgeApp.Project(id, "m$id", folders.toList(), update)
|
|
||||||
|
|
||||||
@Test fun beforeAnyReportNothingIsKnown() {
|
|
||||||
assertEquals(emptyMap<String, String?>(), CurseLink.lastReported(target("Questie")))
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test fun beforeCurseForgeReportsAddonsWhoseFoldersAreAllOnDiskShowAsInstalled() {
|
|
||||||
val target = target("questie", "QuestieDB", "Auctionator")
|
|
||||||
CurseLink.report(target, listOf(
|
|
||||||
project("334372", "Questie", "QuestieDB", update = true),
|
|
||||||
project("1", "Auctionator"),
|
|
||||||
project("2", "Details", "Details_Streamer"),
|
|
||||||
project("3", "Auctionator", "Auctionator_Extra"),
|
|
||||||
))
|
|
||||||
assertEquals(mapOf<String, String?>("334372" to null, "1" to null), CurseLink.lastReported(target))
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test fun anAddonRemovedFromDiskSinceTheLastReportIsNotInstalled() {
|
|
||||||
val target = target("Questie")
|
|
||||||
CurseLink.report(target, listOf(project("334372", "Questie")))
|
|
||||||
java.io.File(target.addOns, "Questie").delete()
|
|
||||||
assertEquals(emptyMap<String, String?>(), CurseLink.lastReported(target))
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun toc(target: WowAddons.Target, folder: String, curseId: String) {
|
|
||||||
val dir = java.io.File(target.addOns, folder).apply { mkdirs() }
|
|
||||||
java.io.File(dir, "$folder.toc").writeText("## Interface: 110207\n## Title: $folder\n## X-Curse-Project-ID: $curseId\n$folder.lua\n")
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test fun beforeAnyReportAnAddonWhoseTocNamesTheProjectShowsAsInstalled() {
|
|
||||||
val target = target()
|
|
||||||
toc(target, "Questie", "334372")
|
|
||||||
toc(target, "Auctionator", "@project-id@")
|
|
||||||
assertEquals(mapOf<String, String?>("334372" to null), CurseLink.lastReported(target))
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test fun aPlaceholderProjectIdIsIgnored() {
|
|
||||||
val target = target()
|
|
||||||
toc(target, "Auctionator", "@project-id@")
|
|
||||||
assertEquals(emptyMap<String, String?>(), CurseLink.lastReported(target))
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test fun curseForgesReportOverridesTheTocProjectId() {
|
|
||||||
val target = target()
|
|
||||||
toc(target, "Questie", "334372")
|
|
||||||
toc(target, "Auctionator", "1")
|
|
||||||
CurseLink.report(target, listOf(project("1", "Auctionator", update = true)))
|
|
||||||
assertEquals(mapOf<String, String?>("1" to null), CurseLink.lastReported(target))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,253 +0,0 @@
|
|||||||
package com.droiddeck.launcher.ui
|
|
||||||
|
|
||||||
import androidx.compose.runtime.LaunchedEffect
|
|
||||||
import androidx.compose.runtime.mutableStateOf
|
|
||||||
import androidx.compose.ui.test.assertCountEquals
|
|
||||||
import androidx.compose.ui.test.onAllNodesWithContentDescription
|
|
||||||
import com.droiddeck.launcher.R
|
|
||||||
import com.droiddeck.launcher.runtime.AppImageManager
|
|
||||||
import com.droiddeck.launcher.runtime.CurseForgeApp
|
|
||||||
import com.droiddeck.launcher.runtime.UserApps
|
|
||||||
import com.droiddeck.launcher.runtime.WowAddonCatalog
|
|
||||||
import com.droiddeck.launcher.runtime.WowAddons
|
|
||||||
import com.droiddeck.launcher.session.SessionPrefs
|
|
||||||
import kotlinx.coroutines.Dispatchers
|
|
||||||
import kotlinx.coroutines.runBlocking
|
|
||||||
import kotlinx.coroutines.withTimeout
|
|
||||||
import kotlinx.coroutines.withContext
|
|
||||||
import org.json.JSONArray
|
|
||||||
import org.json.JSONObject
|
|
||||||
import org.junit.After
|
|
||||||
import org.junit.Assert.assertEquals
|
|
||||||
import org.junit.Assert.assertFalse
|
|
||||||
import org.junit.Assert.assertNull
|
|
||||||
import org.junit.Assert.assertThrows
|
|
||||||
import org.junit.Assert.assertTrue
|
|
||||||
import org.junit.Rule
|
|
||||||
import org.junit.Test
|
|
||||||
import org.junit.rules.TemporaryFolder
|
|
||||||
import org.junit.runner.RunWith
|
|
||||||
import org.robolectric.RobolectricTestRunner
|
|
||||||
import org.robolectric.RuntimeEnvironment
|
|
||||||
import org.robolectric.annotation.Config
|
|
||||||
import java.io.File
|
|
||||||
import java.io.IOException
|
|
||||||
import java.nio.file.Files
|
|
||||||
import java.nio.file.LinkOption
|
|
||||||
import java.util.Collections
|
|
||||||
|
|
||||||
@RunWith(RobolectricTestRunner::class)
|
|
||||||
@Config(sdk = [28], qualifiers = "w960dp-h540dp-land", application = android.app.Application::class)
|
|
||||||
class CurseLinkTabTest {
|
|
||||||
@get:Rule val compose = createRobolectricComposeRule()
|
|
||||||
@get:Rule val temp = TemporaryFolder()
|
|
||||||
|
|
||||||
private val original = CurseForgeApp.guest
|
|
||||||
private val url = "ws://127.0.0.1:43117/0f8fad5b-d9cb-469f-a165-70867728950e"
|
|
||||||
private val app = UserApps.App("appimage:c", UserApps.Kind.APPIMAGE, "CurseForge", null, null, AppImageManager.LAUNCHER, listOf("/root/apps/curseforge"), feed = CurseForgeApp.FEED)
|
|
||||||
private val helper = Collections.synchronizedList(mutableListOf<String>())
|
|
||||||
private val methods = Collections.synchronizedList(mutableListOf<String>())
|
|
||||||
private val context get() = RuntimeEnvironment.getApplication()
|
|
||||||
|
|
||||||
@After
|
|
||||||
fun restore() {
|
|
||||||
CurseForgeApp.guest = original
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun text(id: Int) = context.getString(id)
|
|
||||||
|
|
||||||
private fun wow(): WowAddons.Target {
|
|
||||||
val games = temp.newFolder("Games")
|
|
||||||
val addOns = File(games, "World of Warcraft/_retail_/Interface/AddOns").apply { mkdirs() }
|
|
||||||
File(addOns, "Leatrix_Maps").mkdirs()
|
|
||||||
SessionPrefs.setGameFolderBinds(context, listOf(games.absolutePath to "/root/Games"))
|
|
||||||
CurseForgeApp.guest = { _, argv, cancelled, onLine ->
|
|
||||||
if (argv[0] == CurseForgeApp.HELPER) {
|
|
||||||
helper += argv[1]
|
|
||||||
if (argv[1] == "start") {
|
|
||||||
onLine(url)
|
|
||||||
while (cancelled?.get() != true) Thread.sleep(10)
|
|
||||||
}
|
|
||||||
0
|
|
||||||
} else {
|
|
||||||
val method = Regex("s\\[\\\\\"(\\w+)\\\\\"\\]").find(argv[4])?.groupValues?.get(1)
|
|
||||||
method?.let { methods += it }
|
|
||||||
val answer: Any = when (method) {
|
|
||||||
"detectGameFromPath" -> JSONObject().put("gameInstanceGuid", "g")
|
|
||||||
"getGameInstances" -> JSONArray().put(JSONObject().put("guid", "g").put("installPath", "/root/Games/World of Warcraft/_retail_"))
|
|
||||||
"getProjects" -> JSONArray().put(JSONObject().put("id", "298842").put("installedModId", "m").put("status", 1).put("locked", false).put("folders", JSONArray().put("Leatrix_Maps")))
|
|
||||||
else -> true
|
|
||||||
}
|
|
||||||
onLine(JSONObject().put("ok", true).put("value", JSONObject().put("value", answer).toString()).toString())
|
|
||||||
0
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return WowAddons.Target("_retail_", addOns)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun theTabAndItsDialogShareOneCurseForgeThatStopsWhenTheTabLeaves() {
|
|
||||||
val target = wow()
|
|
||||||
val shown = mutableStateOf(true)
|
|
||||||
val seen = Collections.synchronizedList(mutableListOf<List<String>>())
|
|
||||||
var opened: CurseLink? = null
|
|
||||||
compose.setContent {
|
|
||||||
if (shown.value) {
|
|
||||||
val link = rememberCurseLink(app, sessionRunning = false)
|
|
||||||
opened = link
|
|
||||||
LaunchedEffect(link) { withContext(Dispatchers.IO) { link?.let { seen += it.installed(context, target, 0).map { p -> p.id } } } }
|
|
||||||
LaunchedEffect(link) { withContext(Dispatchers.IO) { link?.let { seen += it.installed(context, target, 0).map { p -> p.id } } } }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
compose.waitUntil(20_000) { seen.size == 2 }
|
|
||||||
assertEquals(listOf(listOf("298842"), listOf("298842")), seen.toList())
|
|
||||||
assertEquals(listOf("start"), helper.toList())
|
|
||||||
assertEquals(1, methods.count { it == "scanGameInstance" })
|
|
||||||
assertTrue(CurseLink.live() != null)
|
|
||||||
compose.runOnIdle { shown.value = false }
|
|
||||||
compose.waitForIdle()
|
|
||||||
compose.waitUntil(20_000) { "stop" in helper }
|
|
||||||
assertNull(CurseLink.live())
|
|
||||||
assertTrue("shutdown" in methods)
|
|
||||||
assertEquals(1, helper.count { it == "start" })
|
|
||||||
runBlocking { withTimeout(20_000) { opened!!.stopped.join() } }
|
|
||||||
compose.waitUntil(5_000) { Thread.getAllStackTraces().keys.none { it.isAlive && it.name.startsWith("curseforge") } }
|
|
||||||
val calls = helper.size + methods.size
|
|
||||||
Thread.sleep(1_500)
|
|
||||||
assertEquals(calls, helper.size + methods.size)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun aNewGenerationRescansButReusesTheRunningCurseForge() {
|
|
||||||
val target = wow()
|
|
||||||
val link = CurseLink(app)
|
|
||||||
try {
|
|
||||||
link.installed(context, target, 0)
|
|
||||||
link.installed(context, target, 0)
|
|
||||||
link.refresh()
|
|
||||||
link.installed(context, target, link.generation)
|
|
||||||
assertEquals(2, methods.count { it == "scanGameInstance" })
|
|
||||||
assertEquals(1, helper.count { it == "start" })
|
|
||||||
} finally {
|
|
||||||
runBlocking { link.close(context).join() }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun aFailedScanKeepsTheLastReportInsteadOfClearingIt() {
|
|
||||||
val target = wow()
|
|
||||||
val link = CurseLink(app)
|
|
||||||
try {
|
|
||||||
val reported = link.marks(context, target, 0)
|
|
||||||
assertTrue(reported.isNotEmpty())
|
|
||||||
runBlocking { link.close(context).join() }
|
|
||||||
assertEquals(reported.mapValues { null }, link.marks(context, target, 1))
|
|
||||||
} finally {
|
|
||||||
runBlocking { link.close(context).join() }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun tocFolder(addOns: File, name: String, curseId: String) =
|
|
||||||
File(addOns, name).apply { mkdirs(); File(this, "$name.toc").writeText("## X-Curse-Project-ID: $curseId\n") }
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun anAddonTheManagerDoesNotListIsFoundByItsTocProjectId() {
|
|
||||||
val target = WowAddons.Target("_retail_", temp.newFolder("AddOns"))
|
|
||||||
tocFolder(target.addOns, "Questie", "334372")
|
|
||||||
tocFolder(target.addOns, "Other", "1")
|
|
||||||
assertEquals(listOf("Questie"), curseFolders(target, "334372", emptyList()))
|
|
||||||
assertEquals(listOf("Listed"), curseFolders(target, "334372", listOf("Listed")))
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun uninstallingByTocProjectIdDeletesOnlyTheMatchedFolders() {
|
|
||||||
val target = WowAddons.Target("_retail_", temp.newFolder("AddOns"))
|
|
||||||
tocFolder(target.addOns, "Questie", "334372")
|
|
||||||
tocFolder(target.addOns, "Other", "1")
|
|
||||||
deleteAddons(context, target, curseFolders(target, "334372", emptyList()), null)
|
|
||||||
assertEquals(listOf("Other"), WowAddons.installed(target))
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun uninstallingALinkedAddonLeavesTheLinkTargetAlone() {
|
|
||||||
val target = WowAddons.Target("_retail_", temp.newFolder("AddOns"))
|
|
||||||
val outside = tocFolder(temp.newFolder("outside"), "Questie", "334372")
|
|
||||||
File(outside, "keep.lua").writeText("keep")
|
|
||||||
Files.createSymbolicLink(File(target.addOns, "Questie").toPath(), outside.toPath())
|
|
||||||
deleteAddons(context, target, curseFolders(target, "334372", emptyList()), null)
|
|
||||||
assertFalse(Files.exists(File(target.addOns, "Questie").toPath(), LinkOption.NOFOLLOW_LINKS))
|
|
||||||
assertEquals("keep", File(outside, "keep.lua").readText())
|
|
||||||
assertTrue(File(outside, "Questie.toc").isFile)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun uninstallingWithNothingToDeleteFails() {
|
|
||||||
val target = WowAddons.Target("_retail_", temp.newFolder("AddOns"))
|
|
||||||
tocFolder(target.addOns, "Other", "1")
|
|
||||||
assertThrows(IOException::class.java) { deleteAddons(context, target, curseFolders(target, "334372", emptyList()), null) }
|
|
||||||
assertEquals(listOf("Other"), WowAddons.installed(target))
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun noCurseForgeStartsWhileASessionRuns() {
|
|
||||||
wow()
|
|
||||||
var link: CurseLink? = CurseLink(app)
|
|
||||||
compose.setContent { link = rememberCurseLink(app, sessionRunning = true) }
|
|
||||||
compose.waitForIdle()
|
|
||||||
assertNull(link)
|
|
||||||
assertTrue(helper.isEmpty())
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun aStaleEntryWhoseFolderIsGoneIsNotManaged() {
|
|
||||||
val target = wow()
|
|
||||||
assertTrue(File(target.addOns, "Leatrix_Maps").deleteRecursively())
|
|
||||||
val link = CurseLink(app)
|
|
||||||
try {
|
|
||||||
assertTrue(link.installed(context, target, 0).isEmpty())
|
|
||||||
} finally {
|
|
||||||
runBlocking { link.close(context).join() }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private val actions = FrontEndActions(
|
|
||||||
onPlay = {}, onPlayDesktopUi = {}, onSteamGame = {}, onDesktop = {}, onEmulator = {},
|
|
||||||
onRom = {}, onResume = {}, onSteamSettings = {}, onDesktopSettings = {},
|
|
||||||
onInstallPackage = {}, onRemovePackage = {}, onRuntime = {}, onFrameGenPick = {},
|
|
||||||
onImportLossless = {}, onProtons = {}, onComponents = {}, onPerformance = {},
|
|
||||||
onRoms = {}, onFiles = {}, onLogs = {}, onOffline = {},
|
|
||||||
onWirelessAdbPair = { _, _, _, _ -> }, onWirelessAdbApply = { _, _, _, _ -> },
|
|
||||||
onSetPhantomProcessLimit = { _, _ -> },
|
|
||||||
)
|
|
||||||
|
|
||||||
private fun row(update: Boolean?, wowi: Boolean) {
|
|
||||||
val target = WowAddons.Target("_retail_", temp.newFolder("AddOns"))
|
|
||||||
val item = WowAddons.Installed("Leatrix_Maps", "1.60.35", null)
|
|
||||||
val newer = WowAddonCatalog.Addon("1", "Leatrix Maps", "Leatrix", "1.60.36", 0, 0, null).takeIf { wowi }
|
|
||||||
val curse = update?.let { CurseForgeApp.Project("298842", "m", listOf("Leatrix_Maps"), it) to CurseLink(app) }
|
|
||||||
compose.setContent { DroidDeckTheme { AddonRow(item, newer, target, actions, curse) } }
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun aManagedRowWithAnUpdateOffersUpdateAndUninstall() {
|
|
||||||
row(update = true, wowi = false)
|
|
||||||
compose.onAllNodesWithContentDescription(text(R.string.common_update)).assertCountEquals(1)
|
|
||||||
compose.onAllNodesWithContentDescription(text(R.string.common_uninstall)).assertCountEquals(1)
|
|
||||||
compose.onAllNodesWithContentDescription(text(R.string.common_delete)).assertCountEquals(0)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun aCurrentManagedRowIgnoresOtherSourcesAndOffersOnlyUninstall() {
|
|
||||||
row(update = false, wowi = true)
|
|
||||||
compose.onAllNodesWithContentDescription(text(R.string.common_update)).assertCountEquals(0)
|
|
||||||
compose.onAllNodesWithContentDescription(text(R.string.common_uninstall)).assertCountEquals(1)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun anUnmanagedRowKeepsTheLocalUpdateAndDelete() {
|
|
||||||
row(update = null, wowi = true)
|
|
||||||
compose.onAllNodesWithContentDescription(text(R.string.common_update)).assertCountEquals(1)
|
|
||||||
compose.onAllNodesWithContentDescription(text(R.string.common_delete)).assertCountEquals(1)
|
|
||||||
compose.onAllNodesWithContentDescription(text(R.string.common_uninstall)).assertCountEquals(0)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,15 +1,11 @@
|
|||||||
package com.droiddeck.launcher.ui
|
package com.droiddeck.launcher.ui
|
||||||
|
|
||||||
import android.content.ComponentName
|
import android.content.ComponentName
|
||||||
import android.os.Handler
|
|
||||||
import android.view.Choreographer
|
|
||||||
import androidx.activity.ComponentActivity
|
import androidx.activity.ComponentActivity
|
||||||
import androidx.compose.ui.platform.AndroidUiDispatcher
|
|
||||||
import androidx.compose.ui.test.junit4.createComposeRule
|
import androidx.compose.ui.test.junit4.createComposeRule
|
||||||
import androidx.compose.runtime.snapshots.Snapshot
|
import androidx.compose.runtime.snapshots.Snapshot
|
||||||
import org.robolectric.RuntimeEnvironment
|
import org.robolectric.RuntimeEnvironment
|
||||||
import org.robolectric.Shadows.shadowOf
|
import org.robolectric.Shadows.shadowOf
|
||||||
import kotlin.coroutines.ContinuationInterceptor
|
|
||||||
|
|
||||||
fun createRobolectricComposeRule() = createComposeRule().also {
|
fun createRobolectricComposeRule() = createComposeRule().also {
|
||||||
RingVeil.reset()
|
RingVeil.reset()
|
||||||
@@ -17,46 +13,5 @@ fun createRobolectricComposeRule() = createComposeRule().also {
|
|||||||
shadowOf(context.packageManager).addActivityIfNotPresent(
|
shadowOf(context.packageManager).addActivityIfNotPresent(
|
||||||
ComponentName(context, ComponentActivity::class.java),
|
ComponentName(context, ComponentActivity::class.java),
|
||||||
)
|
)
|
||||||
resumeDroppedUiDispatch()
|
|
||||||
Snapshot.sendApplyNotifications()
|
Snapshot.sendApplyNotifications()
|
||||||
}
|
}
|
||||||
|
|
||||||
internal class UiDispatch {
|
|
||||||
private val type = AndroidUiDispatcher::class.java
|
|
||||||
private val dispatcher = AndroidUiDispatcher.Main[ContinuationInterceptor] as AndroidUiDispatcher
|
|
||||||
private fun field(name: String) = type.getDeclaredField(name).apply { isAccessible = true }
|
|
||||||
val lock: Any = field("lock").get(dispatcher)!!
|
|
||||||
val handler = field("handler").get(dispatcher) as Handler
|
|
||||||
val choreographer = field("choreographer").get(dispatcher) as Choreographer
|
|
||||||
val callback: Any = field("dispatchCallback").get(dispatcher)!!
|
|
||||||
private val trampolineFlag = field("scheduledTrampolineDispatch")
|
|
||||||
private val frameFlag = field("scheduledFrameDispatch")
|
|
||||||
|
|
||||||
fun trampolineDropped() = trampolineFlag.getBoolean(dispatcher) && !handler.hasMessages(0)
|
|
||||||
|
|
||||||
fun frameDropped() = frameFlag.getBoolean(dispatcher) && !frameQueued()
|
|
||||||
|
|
||||||
private fun frameQueued(): Boolean {
|
|
||||||
val queues = Choreographer::class.java.getDeclaredField("mCallbackQueues").apply { isAccessible = true }.get(choreographer) as Array<*>
|
|
||||||
return queues.any { queue ->
|
|
||||||
var record = queue?.let { q -> q.javaClass.getDeclaredField("mHead").apply { isAccessible = true }.get(q) }
|
|
||||||
var found = false
|
|
||||||
while (record != null && !found) {
|
|
||||||
val recordType = record.javaClass
|
|
||||||
found = recordType.getDeclaredField("action").apply { isAccessible = true }.get(record) === callback
|
|
||||||
record = recordType.getDeclaredField("next").apply { isAccessible = true }.get(record)
|
|
||||||
}
|
|
||||||
found
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
internal fun uiDispatchDropped(): Boolean = UiDispatch().run { synchronized(lock) { trampolineDropped() || frameDropped() } }
|
|
||||||
|
|
||||||
internal fun resumeDroppedUiDispatch() {
|
|
||||||
val ui = UiDispatch()
|
|
||||||
synchronized(ui.lock) {
|
|
||||||
if (ui.trampolineDropped()) ui.handler.post(ui.callback as Runnable)
|
|
||||||
if (ui.frameDropped()) ui.choreographer.postFrameCallback(ui.callback as Choreographer.FrameCallback)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,90 +0,0 @@
|
|||||||
package com.droiddeck.launcher.ui
|
|
||||||
|
|
||||||
import android.os.Looper
|
|
||||||
import android.view.Choreographer
|
|
||||||
import androidx.compose.runtime.MutableIntState
|
|
||||||
import androidx.compose.runtime.mutableIntStateOf
|
|
||||||
import androidx.compose.runtime.withFrameNanos
|
|
||||||
import androidx.compose.ui.platform.AndroidUiDispatcher
|
|
||||||
import kotlinx.coroutines.CoroutineScope
|
|
||||||
import kotlinx.coroutines.launch
|
|
||||||
import org.junit.Assert.assertEquals
|
|
||||||
import org.junit.Assert.assertFalse
|
|
||||||
import org.junit.Assert.assertTrue
|
|
||||||
import org.junit.Test
|
|
||||||
import org.junit.runner.RunWith
|
|
||||||
import org.robolectric.RobolectricTestRunner
|
|
||||||
import org.robolectric.Shadows.shadowOf
|
|
||||||
import org.robolectric.annotation.Config
|
|
||||||
import java.time.Duration
|
|
||||||
|
|
||||||
@RunWith(RobolectricTestRunner::class)
|
|
||||||
@Config(sdk = [34], application = android.app.Application::class)
|
|
||||||
class RobolectricComposeRuleTest {
|
|
||||||
private fun dropPendingUiDispatch() {
|
|
||||||
val ui = UiDispatch()
|
|
||||||
ui.handler.removeCallbacksAndMessages(null)
|
|
||||||
dropPendingFrame()
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun dropPendingFrame() {
|
|
||||||
val ui = UiDispatch()
|
|
||||||
ui.choreographer.removeFrameCallback(ui.callback as Choreographer.FrameCallback)
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun awaitFrameAfterTrampoline(ran: MutableIntState) {
|
|
||||||
CoroutineScope(AndroidUiDispatcher.Main).launch { withFrameNanos { ran.intValue++ } }
|
|
||||||
shadowOf(Looper.getMainLooper()).runOneTask()
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun uiWorkDroppedByAnEarlierTestsLooperResetRunsAgainForTheNextComposeTest() {
|
|
||||||
val ran = mutableIntStateOf(0)
|
|
||||||
CoroutineScope(AndroidUiDispatcher.Main).launch { ran.intValue++ }
|
|
||||||
dropPendingUiDispatch()
|
|
||||||
shadowOf(Looper.getMainLooper()).idle()
|
|
||||||
assertEquals(0, ran.intValue)
|
|
||||||
assertTrue(uiDispatchDropped())
|
|
||||||
createRobolectricComposeRule()
|
|
||||||
shadowOf(Looper.getMainLooper()).idle()
|
|
||||||
assertEquals(1, ran.intValue)
|
|
||||||
assertFalse(uiDispatchDropped())
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun aDispatchStillQueuedIsLeftAlone() {
|
|
||||||
val ran = mutableIntStateOf(0)
|
|
||||||
CoroutineScope(AndroidUiDispatcher.Main).launch { ran.intValue++ }
|
|
||||||
assertFalse(uiDispatchDropped())
|
|
||||||
resumeDroppedUiDispatch()
|
|
||||||
shadowOf(Looper.getMainLooper()).idle()
|
|
||||||
assertEquals(1, ran.intValue)
|
|
||||||
assertFalse(uiDispatchDropped())
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun aFrameDroppedAfterTheTrampolineDrainedRunsAgainForTheNextComposeTest() {
|
|
||||||
val ran = mutableIntStateOf(0)
|
|
||||||
awaitFrameAfterTrampoline(ran)
|
|
||||||
dropPendingFrame()
|
|
||||||
shadowOf(Looper.getMainLooper()).idleFor(Duration.ofSeconds(1))
|
|
||||||
assertEquals(0, ran.intValue)
|
|
||||||
assertTrue(uiDispatchDropped())
|
|
||||||
createRobolectricComposeRule()
|
|
||||||
shadowOf(Looper.getMainLooper()).idleFor(Duration.ofSeconds(1))
|
|
||||||
assertEquals(1, ran.intValue)
|
|
||||||
assertFalse(uiDispatchDropped())
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun aFrameStillQueuedIsLeftAlone() {
|
|
||||||
val ran = mutableIntStateOf(0)
|
|
||||||
awaitFrameAfterTrampoline(ran)
|
|
||||||
assertEquals(0, ran.intValue)
|
|
||||||
assertFalse(uiDispatchDropped())
|
|
||||||
resumeDroppedUiDispatch()
|
|
||||||
shadowOf(Looper.getMainLooper()).idleFor(Duration.ofSeconds(1))
|
|
||||||
assertEquals(1, ran.intValue)
|
|
||||||
assertFalse(uiDispatchDropped())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -219,78 +219,6 @@ alone would then read as an installed client.
|
|||||||
- `0007-cmake-install-code-without-depends`: CMake 4.5 rejects the `DEPENDS` argument FEX passes to
|
- `0007-cmake-install-code-without-depends`: CMake 4.5 rejects the `DEPENDS` argument FEX passes to
|
||||||
`install(CODE ...)` for the guest thunk libraries, so builds with host thunks stopped at configure.
|
`install(CODE ...)` for the guest thunk libraries, so builds with host thunks stopped at configure.
|
||||||
The guest libraries are external projects in the default build, which `install` already follows.
|
The guest libraries are external projects in the default build, which `install` already follows.
|
||||||
- `0008-signal-return-restores-syscall-state`: a guest `rt_sigreturn` is a system call, so FEX's
|
|
||||||
syscall stub marks every static register as spilled (`InSyscallInfo = 0xFFFF`). When the handler
|
|
||||||
left RIP alone, the return resumed the interrupted JIT code without passing the stub's reset, and
|
|
||||||
the mark stayed. Every asynchronous signal after that (until the next system call ended) skipped the
|
|
||||||
register spill and handed the guest handler stale registers from the last system call: only RIP was
|
|
||||||
right. CoreCLR suspends threads for the GC with such signals and reads or redirects the interrupted
|
|
||||||
context, so x86-64 .NET programs failed at random (`AccessViolationException` in whatever code ran
|
|
||||||
next, then SIGABRT). `tools/fex/probes/async-signal-context.c` shows it: under FEX-2611.1 one signal in
|
|
||||||
2000 carried the interrupted registers, natively all of them. The return now restores the value saved
|
|
||||||
when the signal arrived, and only when the signal interrupted JIT code, which is the only case that
|
|
||||||
saves it. Restoring it for a signal that interrupted a system call cleared the mark while that call
|
|
||||||
was still running, so the next signal in the call's return path spilled clobbered registers:
|
|
||||||
`setitimer` at 100 Hz around `time()` crashed in 15 of 15 runs, and with the guard as often as the
|
|
||||||
same build without the patch (about half; a separate crash that FEX-2611.1 also shows).
|
|
||||||
- `0009-signal-handler-escape-frees-host-stack`: FEX keeps each signal's host context on the host
|
|
||||||
stack and frees it only on `rt_sigreturn`. A guest that leaves its handler another way (`siglongjmp`,
|
|
||||||
or CoreCLR resuming a `catch` after a NullReferenceException) left that 2 KB block and one
|
|
||||||
`SignalHandlerRefCounter` count behind. About 3500 such exceptions on one thread overran the 8 MB
|
|
||||||
host stack, which has no guard page, and the CurseForge agent died with "Internal CLR error.
|
|
||||||
(0x80131506)" and "Stack overflow occurred on the same thread again!" at the start of its second
|
|
||||||
addon scan. FEX now chains each thread's signal frames with the guest frame range and alternate
|
|
||||||
stack they used. When a signal arrives in JIT code that runs at the host level of the newest frame
|
|
||||||
and the guest stack pointer shows the guest has left that frame (above its frame, or back off the
|
|
||||||
alternate stack above where the outermost frame on it interrupted), the left frames are dropped and
|
|
||||||
the new context is stored where the newest live frame (or the dispatcher entry) left the host stack.
|
|
||||||
`rt_sigreturn` pops its frame and any newer ones it skips. Signals that arrive inside system calls or
|
|
||||||
thunk callbacks are left alone. `tools/fex/probes/signal-handler-escape.c` leaves handlers on and
|
|
||||||
off the alternate stack, mixes them with handlers that return, and leaves nested handlers: FEX-2611.1
|
|
||||||
with 0001 to 0008 crashed (SIGSEGV) before 2000 iterations of it, and `siglongjmp` out of a SIGSEGV
|
|
||||||
handler died after about 3500; with this patch 350000 escapes and 200000 straight `siglongjmp`s
|
|
||||||
finish, as natively. The approach is the one suggested in FEX-Emu/FEX#2487.
|
|
||||||
- `0010-syscall-exit-resets-host-stack` (`Fixed-upstream: FEX-2612`): a backport of FEX's
|
|
||||||
"JIT: Ensure IR ops that jump out of the JIT reset the stack" (FEX-Emu/FEX#6122). A system call or
|
|
||||||
code-entry removal that ends a block jumps to the dispatcher without dropping the block's spill
|
|
||||||
slots, and the syscall handler's fast path branches straight into the next block, so every such
|
|
||||||
exit leaked up to 32 bytes per spill slot of host stack. AVX and MMX code keeps enough values live to
|
|
||||||
spill, and `tools/fex/probes/syscall-host-stack.c` overran the 8 MB host stack after about 65000
|
|
||||||
system calls; with the patch 2000000 finish, as natively. The CPUID hunk of the upstream commit is
|
|
||||||
left out, since CPUID returns to the JIT in 2611.
|
|
||||||
- `0011-thunk-calls-mark-spilled-state`: a thunk call (every vDSO `clock_gettime`, `gettimeofday`
|
|
||||||
and `time`, and the host library thunks) spills the static registers to the guest frame and calls
|
|
||||||
host code, which clobbers the caller-saved host registers. A signal that arrived in the JIT code
|
|
||||||
after the host call returned and before the registers were refilled took the interrupted state from
|
|
||||||
those clobbered host registers: the guest handler got garbage registers, and the interrupted code
|
|
||||||
resumed with them, or FEX built the signal frame at a garbage stack pointer and crashed. The thunk
|
|
||||||
call now marks every static register as spilled (`InSyscallInfo = 0xFFFF`, as the system call
|
|
||||||
handler does) until the refill ends, and a fully spilled mark takes only RIP from the host PC and
|
|
||||||
leaves the frame's GPRs, vector registers and flags alone (the 16-bit mask could not name the
|
|
||||||
x16/x17 and v16 to v31 registers the host call clobbers). Every guest signal now saves and clears the
|
|
||||||
mark, so guest handlers and nested signals never inherit it, and every return puts back the value it
|
|
||||||
saved; 0008 restored it only for JIT code because the other paths saved none. A handler that changes
|
|
||||||
RIP restarts at the dispatcher with no mark, and thunk callbacks into guest code run with none.
|
|
||||||
`tools/fex/probes/vdso-signal-state.c` calls `clock_gettime` under a 1 kHz `SIGALRM` and checks the
|
|
||||||
values held across each call: FEX-2611 crashed in 3 of 8 runs, with 0001 to 0010 in 7 of 8; with
|
|
||||||
this patch 0 of 28, as natively. This was the "separate crash" noted under 0008.
|
|
||||||
- `0012-signal-return-applies-guest-registers`: a signal return that kept RIP threw away every
|
|
||||||
register change the guest handler made in its `ucontext`; only a changed RIP made FEX reload the
|
|
||||||
guest state from it. CoreCLR suspends threads for garbage collection with a signal and, in fully
|
|
||||||
interruptible code, runs the collection from that handler and writes the moved object references
|
|
||||||
back into the interrupted registers, so under FEX the thread resumed with pointers into the old heap.
|
|
||||||
The CurseForge agent's crashes during parallel addon scans (an `AccessViolationException` in
|
|
||||||
`Curse.Hashing.MurmurHash2.ComputeHash` or `RegexInterpreter`, or "Internal CLR error. (0x80131506)"
|
|
||||||
with a stack overflow) look like this, but they still happen with this patch, so it is not a fix for
|
|
||||||
them. When RIP is
|
|
||||||
unchanged, each guest GPR the handler changed is now written where the resumed code reads it: the
|
|
||||||
guest frame for registers the interrupted code had spilled (all of them inside a system call or
|
|
||||||
thunk call), otherwise the static host register. Unchanged registers are left alone, signals that
|
|
||||||
interrupted code outside the JIT (and not inside a system call or thunk call) keep the old
|
|
||||||
behaviour, and 32-bit frames compare and write only the low 32 bits. `tools/fex/probes/signal-register-update.c`
|
|
||||||
spins until a `SIGALRM` handler sets a register (R12, or ESI in 32-bit `rt` and legacy frames):
|
|
||||||
FEX-2611.1 with 0001 to 0011 never sees it in any of the three frame types, with this patch all
|
|
||||||
three see it on the first signal, as natively.
|
|
||||||
- **Building and publishing.** Droid-Deck/DroidDeck-Components' `build-fex.yml` builds `tools/fex` from
|
- **Building and publishing.** Droid-Deck/DroidDeck-Components' `build-fex.yml` builds `tools/fex` from
|
||||||
this repository at a chosen ref (default `main`) with host thunks, in the same Arch Linux ARM container
|
this repository at a chosen ref (default `main`) with host thunks, in the same Arch Linux ARM container
|
||||||
with a read-only token, then a separate job replaces `fex.tzst` on Components' single `fex` release,
|
with a read-only token, then a separate job replaces `fex.tzst` on Components' single `fex` release,
|
||||||
|
|||||||
@@ -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
+126
@@ -0,0 +1,126 @@
|
|||||||
|
#!/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):
|
||||||
|
run = subprocess.run([readelf, "-d", path], capture_output=True, text=True)
|
||||||
|
if run.returncode != 0: # a damaged ELF must fail the check, not pass with no dependencies
|
||||||
|
raise SystemExit("check-needed: %s -d %s failed (%d): %s" % (readelf, path, run.returncode, run.stderr.strip()))
|
||||||
|
return [l.split("[", 1)[1].split("]", 1)[0] for l in run.stdout.splitlines() if "(NEEDED)" in l]
|
||||||
|
|
||||||
|
|
||||||
|
def names_in(*dirs):
|
||||||
|
names = set()
|
||||||
|
for d in dirs:
|
||||||
|
for root, _, files in os.walk(d):
|
||||||
|
# a link whose target is missing provides nothing
|
||||||
|
names.update(f for f in files if os.path.isfile(os.path.join(root, f)))
|
||||||
|
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,235 @@
|
|||||||
|
// 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 <sys/stat.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;
|
||||||
|
// non-blocking, so a FIFO without a writer cannot hang the start; anything but a regular file goes to libc
|
||||||
|
int fd = open(resolved, O_RDONLY | O_CLOEXEC | O_NONBLOCK);
|
||||||
|
if (fd < 0) return PASS;
|
||||||
|
struct stat st;
|
||||||
|
if (fstat(fd, &st) != 0 || !S_ISREG(st.st_mode)) {
|
||||||
|
close(fd);
|
||||||
|
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);
|
||||||
|
// up to four leading entries, argc - 1 trailing ones and the terminator (argc may be 0)
|
||||||
|
char **out = calloc((size_t)(argc > 0 ? argc - 1 : 0) + 5, 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;
|
||||||
|
}
|
||||||
|
|
||||||
|
// libc's functions: bound when the library loads (single-threaded), so execve() in a post-fork child finds them bound.
|
||||||
|
// A call that comes before that (another library's constructor) binds through an atomic slot: concurrent binders
|
||||||
|
// store the same pointer, and readers never see a torn one.
|
||||||
|
typedef ssize_t (*readlink_fn)(const char *, char *, size_t);
|
||||||
|
typedef char *(*realpath_fn)(const char *, char *);
|
||||||
|
typedef int (*execve_fn)(const char *, char *const[], char *const[]);
|
||||||
|
typedef int (*spawn_fn)(pid_t *, const char *, const posix_spawn_file_actions_t *, const posix_spawnattr_t *,
|
||||||
|
char *const[], char *const[]);
|
||||||
|
static void *slot_readlink, *slot_realpath, *slot_execve, *slot_spawn, *slot_spawnp;
|
||||||
|
|
||||||
|
static void *bound(void **slot, const char *name) {
|
||||||
|
void *p = __atomic_load_n(slot, __ATOMIC_ACQUIRE);
|
||||||
|
if (!p) {
|
||||||
|
p = dlsym(RTLD_NEXT, name);
|
||||||
|
__atomic_store_n(slot, p, __ATOMIC_RELEASE);
|
||||||
|
}
|
||||||
|
return p;
|
||||||
|
}
|
||||||
|
#define real_readlink ((readlink_fn)bound(&slot_readlink, "readlink"))
|
||||||
|
#define real_realpath ((realpath_fn)bound(&slot_realpath, "realpath"))
|
||||||
|
#define real_execve ((execve_fn)bound(&slot_execve, "execve"))
|
||||||
|
#define real_spawn ((spawn_fn)bound(&slot_spawn, "posix_spawn"))
|
||||||
|
#define real_spawnp ((spawn_fn)bound(&slot_spawnp, "posix_spawnp"))
|
||||||
|
|
||||||
|
__attribute__((constructor)) static void bind_libc(void) {
|
||||||
|
(void)real_readlink;
|
||||||
|
(void)real_realpath;
|
||||||
|
(void)real_execve;
|
||||||
|
(void)real_spawn;
|
||||||
|
(void)real_spawnp;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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) return 0;
|
||||||
|
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) {
|
||||||
|
if (!real_realpath) {
|
||||||
|
errno = ENOSYS;
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
char prog[PATH_MAX];
|
||||||
|
if (path && strcmp(path, "/proc/self/exe") == 0 && linker_program(prog, sizeof prog)) return real_realpath(prog, resolved);
|
||||||
|
return real_realpath(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)) {
|
||||||
|
if (real_realpath && real_realpath(prog, full)) {
|
||||||
|
size_t l = strlen(full);
|
||||||
|
if (l > size) l = size;
|
||||||
|
memcpy(buf, full, l);
|
||||||
|
return (ssize_t)l;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!real_readlink) {
|
||||||
|
errno = ENOSYS;
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
return real_readlink(path, buf, size);
|
||||||
|
}
|
||||||
|
|
||||||
|
int execve(const char *path, char *const argv[], char *const envp[]) {
|
||||||
|
execve_fn real = real_execve;
|
||||||
|
if (!real) {
|
||||||
|
errno = ENOSYS;
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
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[]) {
|
||||||
|
spawn_fn real = real_spawn;
|
||||||
|
if (!real) return ENOSYS;
|
||||||
|
char storage[6 * PATH_MAX];
|
||||||
|
const char *file = path;
|
||||||
|
// file actions can change the child's directory before it starts: a relative path is resolved there by libc, so
|
||||||
|
// it is left to libc instead of being resolved here against the parent's directory
|
||||||
|
char **args = (actions && path && path[0] != '/') ? NULL : 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[]) {
|
||||||
|
if (file && strchr(file, '/')) return posix_spawn(pid, file, actions, attr, argv, envp);
|
||||||
|
spawn_fn real = real_spawnp;
|
||||||
|
if (!real) return ENOSYS;
|
||||||
|
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,330 @@
|
|||||||
|
// 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, tconn = -1, cconn = -1;
|
||||||
|
static uint16_t tseq, cseq; // sequence number of the last request sent on each connection
|
||||||
|
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; }
|
||||||
|
|
||||||
|
// Sends one request on the current connection; its sequence number goes to *seq. 0 when sent.
|
||||||
|
static int request(const void *p, size_t n, uint16_t *seq) {
|
||||||
|
if (wr(p, n)) return -1;
|
||||||
|
uint16_t *last = (fd == cconn && cconn != tconn) ? &cseq : &tseq;
|
||||||
|
++*last;
|
||||||
|
if (seq) *seq = *last;
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reads one whole packet into rbuf; a reply (or generic event) longer than rbuf ends the connection. 0 when read.
|
||||||
|
static int packet(void) {
|
||||||
|
if (rd(rbuf, 32)) return -1;
|
||||||
|
uint8_t type = rbuf[0] & 0x7f;
|
||||||
|
if (rbuf[0] == 1 || type == 35) {
|
||||||
|
uint32_t words = *(uint32_t *)(rbuf + 4);
|
||||||
|
if (words > (sizeof rbuf - 32) / 4) return -1;
|
||||||
|
if (words && rd(rbuf + 32, words * 4u)) return -1;
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
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 forget(uint32_t *list, int *n, uint32_t w) {
|
||||||
|
for (int i = 0; i < *n; i++)
|
||||||
|
if (list[i] == w) { list[i] = list[--*n]; return; }
|
||||||
|
}
|
||||||
|
|
||||||
|
static void note_event(const uint8_t *e) {
|
||||||
|
uint8_t type = e[0] & 0x7f;
|
||||||
|
uint32_t win = *(uint32_t *)(e + 8);
|
||||||
|
if (type == 17) { // DestroyNotify: a destroyed window is neither a candidate nor a tagged game window
|
||||||
|
forget(pending, &npending, win);
|
||||||
|
forget(tagged, &ntagged, win);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (type != 16 && type != 19) return; // CreateNotify, MapNotify
|
||||||
|
if (win && !known(tagged, ntagged, win) && !known(pending, npending, win) && npending < 256) pending[npending++] = win;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reads until the answer to request `seq`. Returns 1 reply, 0 error, -1 io. Events are noted; errors of requests
|
||||||
|
// without a reply (a ChangeProperty on a window that is gone) and other stale packets are skipped.
|
||||||
|
static int reply(uint16_t seq) {
|
||||||
|
for (;;) {
|
||||||
|
if (packet()) return -1;
|
||||||
|
if (rbuf[0] > 1) { note_event(rbuf); continue; }
|
||||||
|
if (*(uint16_t *)(rbuf + 2) != seq) continue;
|
||||||
|
return rbuf[0] == 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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);
|
||||||
|
uint16_t seq;
|
||||||
|
if (request(req, 8 + pad4(n), &seq)) return 0;
|
||||||
|
return reply(seq) == 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;
|
||||||
|
uint16_t seq;
|
||||||
|
if (request(req, sizeof req, &seq) || reply(seq) != 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);
|
||||||
|
request(req, 24 + 4 * n, NULL);
|
||||||
|
}
|
||||||
|
|
||||||
|
// First CARDINAL of a root property into *value (0 when unset). 0 when the property could not be read.
|
||||||
|
static int first_card(uint32_t root, uint32_t prop, uint32_t *value) {
|
||||||
|
uint8_t gp[24] = {20, 0, 6, 0};
|
||||||
|
uint16_t seq;
|
||||||
|
*(uint32_t *)(gp + 4) = root;
|
||||||
|
*(uint32_t *)(gp + 8) = prop;
|
||||||
|
*(uint32_t *)(gp + 20) = 64;
|
||||||
|
if (request(gp, sizeof gp, &seq) || reply(seq) != 1) return 0;
|
||||||
|
*value = *(uint32_t *)(rbuf + 16) ? *(uint32_t *)(rbuf + 32) : 0;
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 1 when the window still exists (GetWindowAttributes answers), 0 when it is gone, -1 on an io failure.
|
||||||
|
static int alive(uint32_t win) {
|
||||||
|
uint8_t ga[8] = {3, 0, 2, 0};
|
||||||
|
uint16_t seq;
|
||||||
|
*(uint32_t *)(ga + 4) = win;
|
||||||
|
if (request(ga, sizeof ga, &seq)) return -1;
|
||||||
|
return reply(seq);
|
||||||
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
request(req, sizeof req, NULL);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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;
|
||||||
|
}
|
||||||
|
tconn = tfd;
|
||||||
|
cconn = cfd;
|
||||||
|
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;
|
||||||
|
request(cwa, sizeof cwa, NULL);
|
||||||
|
|
||||||
|
uint8_t qt[8] = {15, 0, 2, 0}; // QueryTree(root): windows that exist already
|
||||||
|
uint16_t qseq;
|
||||||
|
*(uint32_t *)(qt + 4) = root;
|
||||||
|
if (request(qt, sizeof qt, &qseq) == 0 && reply(qseq) == 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, focus_reads = 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;
|
||||||
|
uint16_t gseq;
|
||||||
|
if (request(gp, sizeof gp, &gseq) == 0 && reply(gseq) == 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
|
||||||
|
uint16_t aseq, gseq;
|
||||||
|
*(uint32_t *)(ga + 4) = tagged[i];
|
||||||
|
int map = -1, ovr = -1, w = -1, h = -1;
|
||||||
|
if (request(ga, sizeof ga, &aseq) == 0 && reply(aseq) == 1) { map = rbuf[26]; ovr = rbuf[27]; }
|
||||||
|
uint8_t gg[8] = {14, 0, 2, 0}; // GetGeometry
|
||||||
|
*(uint32_t *)(gg + 4) = tagged[i];
|
||||||
|
if (request(gg, sizeof gg, &gseq) == 0 && reply(gseq) == 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) {
|
||||||
|
// the override is only for a game that still has a window: a tagged window that was destroyed is gone
|
||||||
|
// from `tagged` (DestroyNotify), and one that is left must still answer
|
||||||
|
int live = 0;
|
||||||
|
for (int i = 0; i < ntagged && !live; i++) live = alive(tagged[i]) == 1;
|
||||||
|
uint32_t f = 0;
|
||||||
|
fd = cfd;
|
||||||
|
int read_ok = live && first_card(croot, a_focus, &f);
|
||||||
|
fd = tfd;
|
||||||
|
if (!live) {
|
||||||
|
focus_checked = 1;
|
||||||
|
printf("gstag: no tagged window left 8 s after the tag; focus left as it is\n");
|
||||||
|
} else if (!read_ok) {
|
||||||
|
// a failed read says nothing about who has focus: try again on the next pass, a few times
|
||||||
|
if (++focus_reads >= 3) { focus_checked = 1; printf("gstag: focus could not be read; left as it is\n"); }
|
||||||
|
} else {
|
||||||
|
focus_checked = 1;
|
||||||
|
if (f != appid) {
|
||||||
|
uint32_t ids[2] = {appid, 769};
|
||||||
|
fd = cfd;
|
||||||
|
set_cards(croot, a_ctrl, ids, 2);
|
||||||
|
fd = tfd;
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
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 (packet()) { printf("gstag: connection closed or a packet too long\n"); break; }
|
||||||
|
if (rbuf[0] > 1) note_event(rbuf); // replies and errors here belong to no request waiting
|
||||||
|
}
|
||||||
|
if (npending > 200) {
|
||||||
|
// drop only windows that are gone; live candidates may still get WM_CLASS
|
||||||
|
for (int i = 0; i < npending; ) {
|
||||||
|
int a = alive(pending[i]);
|
||||||
|
if (a < 0) break;
|
||||||
|
if (a == 0) pending[i] = pending[--npending];
|
||||||
|
else i++;
|
||||||
|
}
|
||||||
|
if (npending > 200) { // still too many: keep the newest
|
||||||
|
memmove(pending, pending + (npending - 200), 200 * sizeof *pending);
|
||||||
|
npending = 200;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
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,549 @@
|
|||||||
|
// 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 <sys/syscall.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;
|
||||||
|
// made and sized under a private name, then put in place in one step: no other process can open it while it
|
||||||
|
// is still empty, and an object another process published first is opened instead
|
||||||
|
char tmp[PATH_MAX];
|
||||||
|
int w = snprintf(tmp, sizeof tmp, "%s.%d.%d", path, (int)getpid(), i);
|
||||||
|
if (w <= 0 || (size_t)w >= sizeof tmp) break;
|
||||||
|
fd = open(tmp, O_RDWR | O_CREAT | O_EXCL | O_CLOEXEC, 0600);
|
||||||
|
if (fd < 0) break;
|
||||||
|
if (ftruncate(fd, (off_t)size) != 0) {
|
||||||
|
close(fd);
|
||||||
|
unlink(tmp);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
int placed = (int)syscall(SYS_renameat2, AT_FDCWD, tmp, AT_FDCWD, path, 1 /* RENAME_NOREPLACE */);
|
||||||
|
if (placed != 0 && (errno == ENOSYS || errno == EINVAL)) { // no renameat2: a hard link fails on EEXIST too
|
||||||
|
placed = link(tmp, path);
|
||||||
|
unlink(tmp);
|
||||||
|
}
|
||||||
|
if (placed == 0) {
|
||||||
|
if (created) *created = true;
|
||||||
|
if (notes++ < 64) say("steamshm: %s created (%zu bytes)\n", path, size);
|
||||||
|
return fd;
|
||||||
|
}
|
||||||
|
int err = errno;
|
||||||
|
close(fd);
|
||||||
|
unlink(tmp);
|
||||||
|
errno = err;
|
||||||
|
if (err != 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)) {
|
||||||
|
munmap(t, page);
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
flush((uintptr_t)t, 32);
|
||||||
|
return t;
|
||||||
|
}
|
||||||
|
|
||||||
|
static void drop_trampoline(void *t)
|
||||||
|
{
|
||||||
|
if (t) munmap(t, getauxval(AT_PAGESZ));
|
||||||
|
}
|
||||||
|
|
||||||
|
// The library's code pages are file mappings: patched anonymous copies are prepared first and then moved over the
|
||||||
|
// originals in one step each. Both hooks go in or neither: the pages of both functions (one range when they share a
|
||||||
|
// page) are copied, patched and made executable before anything is replaced, and a copy of the original pages is
|
||||||
|
// kept, so a failed second replacement puts the first range back.
|
||||||
|
struct range {
|
||||||
|
uintptr_t lo;
|
||||||
|
size_t len;
|
||||||
|
uint8_t *patched, *saved;
|
||||||
|
};
|
||||||
|
|
||||||
|
static bool prepare(struct range *r, uintptr_t lo, uintptr_t hi)
|
||||||
|
{
|
||||||
|
r->lo = lo;
|
||||||
|
r->len = hi - lo;
|
||||||
|
r->patched = mmap(NULL, r->len, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
|
||||||
|
r->saved = mmap(NULL, r->len, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
|
||||||
|
if (r->patched == MAP_FAILED || r->saved == MAP_FAILED) {
|
||||||
|
if (r->patched != MAP_FAILED) munmap(r->patched, r->len);
|
||||||
|
if (r->saved != MAP_FAILED) munmap(r->saved, r->len);
|
||||||
|
r->patched = r->saved = NULL;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
memcpy(r->patched, (void *)lo, r->len);
|
||||||
|
memcpy(r->saved, (void *)lo, r->len);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
static void patch(struct range *r, uint32_t *fn, uintptr_t to)
|
||||||
|
{
|
||||||
|
if ((uintptr_t)fn >= r->lo && (uintptr_t)fn + 16 <= r->lo + r->len)
|
||||||
|
jump_code((uint32_t *)(r->patched + ((uintptr_t)fn - r->lo)), to);
|
||||||
|
}
|
||||||
|
|
||||||
|
static bool seal(struct range *r)
|
||||||
|
{
|
||||||
|
return !mprotect(r->patched, r->len, PROT_READ | PROT_EXEC) && !mprotect(r->saved, r->len, PROT_READ | PROT_EXEC);
|
||||||
|
}
|
||||||
|
|
||||||
|
static bool commit(struct range *r)
|
||||||
|
{
|
||||||
|
if (mremap(r->patched, r->len, r->len, MREMAP_MAYMOVE | MREMAP_FIXED, (void *)r->lo) == MAP_FAILED) return false;
|
||||||
|
r->patched = NULL; // now the mapping at lo
|
||||||
|
flush(r->lo, r->len);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
static void restore(struct range *r)
|
||||||
|
{
|
||||||
|
if (r->saved && mremap(r->saved, r->len, r->len, MREMAP_MAYMOVE | MREMAP_FIXED, (void *)r->lo) != MAP_FAILED) {
|
||||||
|
r->saved = NULL;
|
||||||
|
flush(r->lo, r->len);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static void release(struct range *r)
|
||||||
|
{
|
||||||
|
if (r->patched) munmap(r->patched, r->len);
|
||||||
|
if (r->saved) munmap(r->saved, r->len);
|
||||||
|
r->patched = r->saved = NULL;
|
||||||
|
}
|
||||||
|
|
||||||
|
static bool redirect_both(uint32_t *fa, uintptr_t ta, uint32_t *fb, uintptr_t tb)
|
||||||
|
{
|
||||||
|
size_t page = getauxval(AT_PAGESZ);
|
||||||
|
uintptr_t alo = (uintptr_t)fa & ~(page - 1), ahi = ((uintptr_t)fa + 16 + page - 1) & ~(page - 1);
|
||||||
|
uintptr_t blo = (uintptr_t)fb & ~(page - 1), bhi = ((uintptr_t)fb + 16 + page - 1) & ~(page - 1);
|
||||||
|
struct range r[2] = {{0}};
|
||||||
|
int n = 1;
|
||||||
|
if (alo < bhi && blo < ahi) { // overlapping pages: one range holds both patches
|
||||||
|
if (!prepare(&r[0], alo < blo ? alo : blo, ahi > bhi ? ahi : bhi)) return false;
|
||||||
|
} else if (!prepare(&r[0], alo, ahi) || !prepare(&r[1], blo, bhi)) {
|
||||||
|
release(&r[0]);
|
||||||
|
release(&r[1]);
|
||||||
|
return false;
|
||||||
|
} else n = 2;
|
||||||
|
for (int i = 0; i < n; i++) {
|
||||||
|
patch(&r[i], fa, ta);
|
||||||
|
patch(&r[i], fb, tb);
|
||||||
|
}
|
||||||
|
bool ok = true;
|
||||||
|
for (int i = 0; i < n && ok; i++) ok = seal(&r[i]);
|
||||||
|
if (ok && !commit(&r[0])) ok = false;
|
||||||
|
else if (ok && n == 2 && !commit(&r[1])) {
|
||||||
|
restore(&r[0]);
|
||||||
|
ok = false;
|
||||||
|
}
|
||||||
|
for (int i = 0; i < n; i++) release(&r[i]);
|
||||||
|
return ok;
|
||||||
|
}
|
||||||
|
|
||||||
|
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_both(unlink_fn, (uintptr_t)hook_unlink, open_fn, (uintptr_t)hook_open)) {
|
||||||
|
drop_trampoline((void *)orig_open);
|
||||||
|
drop_trampoline((void *)orig_unlink);
|
||||||
|
orig_open = NULL;
|
||||||
|
orig_unlink = NULL;
|
||||||
|
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,443 @@
|
|||||||
|
#!/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)
|
||||||
|
LOGS=${DROIDDECK_BIONIC_LOGS:-}
|
||||||
|
|
||||||
|
mkdir -p "$COMPAT"
|
||||||
|
LOG=$COMPAT/droiddeck-bionic.log
|
||||||
|
[ "$verb" = runinprefix ] || { [ -f "$LOG" ] && mv -f "$LOG" "$LOG.1"; }
|
||||||
|
# A game's log is written into DroidDeck's session folder (../proton names it), which Share logs takes only as a
|
||||||
|
# file with one name; the usual name here points to it, and dangles once that session's folder is removed.
|
||||||
|
[ -L "$LOG" ] && [ ! -e "$LOG" ] && rm -f "$LOG"
|
||||||
|
if [ -n "$LOGS" ] && [ ! -e "$LOG" ] && mkdir -p "$LOGS" 2>/dev/null && : >> "$LOGS/droiddeck-bionic.log" 2>/dev/null; then
|
||||||
|
ln -s "$LOGS/droiddeck-bionic.log" "$LOG" 2>/dev/null
|
||||||
|
fi
|
||||||
|
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) ;;
|
||||||
|
DXVK_LOG_PATH|VKD3D_LOG_FILE|MESA_LOG_FILE) ;;
|
||||||
|
DROIDDECK_GPU_LOAD|DROIDDECK_GPU_LOAD_DIR|DROIDDECK_VRAM_CAP|DROIDDECK_VRAM_CAP_MB|DROIDDECK_DISPLAY_DRIVER) ;;
|
||||||
|
DROIDDECK_GUEST_ROOT) ;;
|
||||||
|
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=${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|\
|
||||||
|
winemenubuilder|wineboot.exe|tabtip.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.
|
||||||
|
# The stamp holds this FEX's ID and what the caches held when this tool last finished with the prefix, so a cache that
|
||||||
|
# another FEX wrote to since (DroidDeck-Proton running the same game) is cleared too.
|
||||||
|
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)
|
||||||
|
fex_cache_sum() { # names, sizes and times of the files in the prefix's FEX code caches
|
||||||
|
for u in "$COMPAT/pfx/drive_c/users"/*; do
|
||||||
|
[ -L "$u" ] && continue
|
||||||
|
c=$u/AppData/Local/fex-emu/DiskCache
|
||||||
|
[ -d "$c" ] && find "$c" -type f -exec stat -c '%n %s %Y' {} + 2>/dev/null
|
||||||
|
done | sort | md5sum | cut -c1-16
|
||||||
|
}
|
||||||
|
save_fex_stamp() { echo "$fexid $(fex_cache_sum)" > "$COMPAT/pfx/.droiddeck-fex-cache" 2>/dev/null; }
|
||||||
|
if [ "$(cat "$COMPAT/pfx/.droiddeck-fex-cache" 2>/dev/null)" != "$fexid $(fex_cache_sum)" ]; 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 (another FEX build wrote to it, or it is unknown)"
|
||||||
|
done
|
||||||
|
save_fex_stamp
|
||||||
|
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" "$@"
|
||||||
|
rc=$?
|
||||||
|
save_fex_stamp
|
||||||
|
exit $rc
|
||||||
|
fi
|
||||||
|
|
||||||
|
name=${EXE##*/}; name=${name##*\\}
|
||||||
|
comm=$(echo "$name" | cut -c1-15)
|
||||||
|
game_pids() { # processes of this prefix with the game's name (two prefixes can run programs with the same name)
|
||||||
|
for p in $(grep -lFx "$comm" /proc/[0-9]*/comm 2>/dev/null); do
|
||||||
|
p=${p%/comm}
|
||||||
|
tr '\0' '\n' < "$p/environ" 2>/dev/null | grep -qxF "WINEPREFIX=$COMPAT/pfx" && echo "${p#/proc/}"
|
||||||
|
done
|
||||||
|
}
|
||||||
|
# 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; save_fex_stamp; 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. A launcher
|
||||||
|
# that started the game and ended leaves the game as another program of this prefix, so the wait goes on while any
|
||||||
|
# program of the prefix runs, apart from Wine's own services (Proton waits for the prefix's programs the same way).
|
||||||
|
while [ -n "$(game_pids)" ] || kill -0 $WP 2>/dev/null || programs_left; do sleep 2; done
|
||||||
|
echo "$(date +%H:%M:%S) game exited"
|
||||||
|
[ -n "$GT" ] && kill $GT 2>/dev/null
|
||||||
|
stop_wine
|
||||||
|
wait $WP
|
||||||
|
rc=$?
|
||||||
|
save_fex_stamp
|
||||||
|
echo "$(date +%H:%M:%S) done (exit $rc)"
|
||||||
|
exit $rc
|
||||||
@@ -0,0 +1,120 @@
|
|||||||
|
#!/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
|
||||||
|
}
|
||||||
|
|
||||||
|
# A guest Z: path (also as NAME=Z:..., e.g. an installer's /DIR=) -> the Z: path of its Android file; anything else unchanged
|
||||||
|
zpath() {
|
||||||
|
local p k
|
||||||
|
case "$1" in
|
||||||
|
[Zz]:[\\/]*) p=${1:2}; p=$(real "${p//\\//}"); printf 'Z:%s\n' "${p//\//\\}" ;;
|
||||||
|
*=[Zz]:[\\/]*) k=${1%%=[Zz]:[\\/]*}; printf '%s=%s\n' "$k" "$(zpath "${1#"$k="}")" ;;
|
||||||
|
*) printf '%s\n' "$1" ;;
|
||||||
|
esac
|
||||||
|
}
|
||||||
|
|
||||||
|
# Where a game launch's log goes in DroidDeck's session folder (Share logs takes that folder): the game's log folder
|
||||||
|
# when Detailed graphics logs made one (droiddeck-game-env), else a folder of its own; nothing for other verbs
|
||||||
|
session_logs() {
|
||||||
|
[ "$verb" = waitforexitandrun ] && [ -n "${DD_DEBUG_DIR:-}" ] || return 0
|
||||||
|
if [ -n "${PROTON_LOG_DIR:-}" ]; then
|
||||||
|
real "$PROTON_LOG_DIR"
|
||||||
|
else
|
||||||
|
local id=${SteamAppId:-0}
|
||||||
|
printf '%s/games/%s-bionic-%s\n' "$(real "${DD_DEBUG_DIR%/}")" "$(date +%Y-%m-%d-%H%M%S)" "${id//[^0-9]/}"
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
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
|
||||||
|
# Another 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
|
||||||
|
[Zz]:[\\/]*) exe=$(zpath "$1") ;;
|
||||||
|
[A-Za-z]:[\\/]*) exe=$1 ;;
|
||||||
|
/*) exe=$(real "$1") ;;
|
||||||
|
*/*) exe=$(real "$PWD/$1") ;;
|
||||||
|
*) exe=$1 ;;
|
||||||
|
esac
|
||||||
|
shift
|
||||||
|
# DroidDeck's store and Xbox helpers name guest files by Z: paths (reg.exe import, cmd.exe /c, msiexec /i, setup
|
||||||
|
# /DIR=); this Wine's Z: is Android's root.
|
||||||
|
args=()
|
||||||
|
for a in "$@"; do args+=("$(zpath "$a")"); done
|
||||||
|
export DROIDDECK_BIONIC_ROOT="$DDNATV_ROOT"
|
||||||
|
# The guest's root as this Wine names it; the store launch files DroidDeck writes (StoreLaunch.kt) start their
|
||||||
|
# helpers from it.
|
||||||
|
r=$(real /); r=${r%/}; DROIDDECK_GUEST_ROOT="Z:${r//\//\\}"; export DROIDDECK_GUEST_ROOT
|
||||||
|
# The Xbox runtime's DLC and mount folders come as ;-separated Z: paths of the guest.
|
||||||
|
zreal() {
|
||||||
|
local out="" part
|
||||||
|
local -a parts
|
||||||
|
IFS=';' read -r -a parts <<< "$1"
|
||||||
|
for part in "${parts[@]}"; do
|
||||||
|
out="${out:+$out;}$(zpath "$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; }
|
||||||
|
# So are the graphics log locations Detailed graphics logs or game debugging set for this launch.
|
||||||
|
for v in DXVK_LOG_PATH VKD3D_LOG_FILE MESA_LOG_FILE; do
|
||||||
|
[ -n "${!v:-}" ] && { printf -v "$v" '%s' "$(real "${!v}")"; export "${v?}"; }
|
||||||
|
done
|
||||||
|
DROIDDECK_BIONIC_LOGS=$(session_logs); export DROIDDECK_BIONIC_LOGS
|
||||||
|
# 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" ${args[@]+"${args[@]}"} ;;
|
||||||
|
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%"
|
||||||
|
}
|
||||||
@@ -1,18 +0,0 @@
|
|||||||
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp
|
|
||||||
index b4c7b24..643185d 100644
|
|
||||||
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp
|
|
||||||
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp
|
|
||||||
@@ -264,12 +264,13 @@ void SignalDelegator::RestoreThreadState(FEXCore::Core::InternalThreadState* Thr
|
|
||||||
auto Frame = Thread->CurrentFrame;
|
|
||||||
|
|
||||||
if (Context->Flags & ArchHelpers::Context::ContextFlags::CONTEXT_FLAG_INJIT) {
|
|
||||||
// XXX: Unsupported since it needs state reconstruction
|
|
||||||
// If we are in the JIT then SRA might need to be restored to values from the context
|
|
||||||
// We can't currently support this since it might result in tearing without real state reconstruction
|
|
||||||
+ Frame->InSyscallInfo = Context->InSyscallInfo;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (Is64BitMode) {
|
|
||||||
RestoreFrame_x64(Thread, Context, Frame, ucontext);
|
|
||||||
} else {
|
|
||||||
if (Type == RestoreType::TYPE_NONREALTIME) {
|
|
||||||
@@ -1,174 +0,0 @@
|
|||||||
diff --git a/Source/Tools/LinuxEmulation/ArchHelpers/MContext.h b/Source/Tools/LinuxEmulation/ArchHelpers/MContext.h
|
|
||||||
index 02bb6bf..2e72492 100644
|
|
||||||
--- a/Source/Tools/LinuxEmulation/ArchHelpers/MContext.h
|
|
||||||
+++ b/Source/Tools/LinuxEmulation/ArchHelpers/MContext.h
|
|
||||||
@@ -49,6 +49,11 @@ struct X86ContextBackup {
|
|
||||||
uint64_t FPStateLocation;
|
|
||||||
uint64_t UContextLocation;
|
|
||||||
uint64_t SigInfoLocation;
|
|
||||||
+ uint64_t PrevGuestFrame;
|
|
||||||
+ uint64_t GuestFrameEnd;
|
|
||||||
+ uint64_t GuestInterruptedSP;
|
|
||||||
+ uint64_t GuestAltBase;
|
|
||||||
+ uint64_t GuestAltEnd;
|
|
||||||
FEXCore::Core::CPUState GuestState;
|
|
||||||
static constexpr int RedZoneSize = 128;
|
|
||||||
};
|
|
||||||
@@ -76,6 +81,11 @@ struct ArmContextBackup {
|
|
||||||
uint64_t FPStateLocation;
|
|
||||||
uint64_t UContextLocation;
|
|
||||||
uint64_t SigInfoLocation;
|
|
||||||
+ uint64_t PrevGuestFrame;
|
|
||||||
+ uint64_t GuestFrameEnd;
|
|
||||||
+ uint64_t GuestInterruptedSP;
|
|
||||||
+ uint64_t GuestAltBase;
|
|
||||||
+ uint64_t GuestAltEnd;
|
|
||||||
FEXCore::Core::CPUState GuestState;
|
|
||||||
|
|
||||||
// Arm64 doesn't have a red zone
|
|
||||||
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp
|
|
||||||
index 643185d..53179c4 100644
|
|
||||||
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp
|
|
||||||
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp
|
|
||||||
@@ -136,6 +136,31 @@ void SignalDelegator::SpillSRA(FEXCore::Core::InternalThreadState* Thread, void*
|
|
||||||
#endif
|
|
||||||
}
|
|
||||||
|
|
||||||
+namespace {
|
|
||||||
+ bool OnGuestAltStack(const ArchHelpers::Context::ContextBackup* Backup, uint64_t SP) {
|
|
||||||
+ return Backup->GuestAltEnd != 0 && SP >= Backup->GuestAltBase && SP <= Backup->GuestAltEnd;
|
|
||||||
+ }
|
|
||||||
+
|
|
||||||
+ bool GuestLeftFrame(const ArchHelpers::Context::ContextBackup* Backup, uint64_t GuestSP, uint32_t Limit) {
|
|
||||||
+ const bool SPOnAlt = OnGuestAltStack(Backup, GuestSP);
|
|
||||||
+ if (SPOnAlt == OnGuestAltStack(Backup, Backup->GuestFrameEnd)) {
|
|
||||||
+ return GuestSP >= Backup->GuestFrameEnd;
|
|
||||||
+ }
|
|
||||||
+ if (SPOnAlt) {
|
|
||||||
+ return false;
|
|
||||||
+ }
|
|
||||||
+ auto Entry = Backup;
|
|
||||||
+ while (OnGuestAltStack(Backup, Entry->GuestInterruptedSP)) {
|
|
||||||
+ if (--Limit == 0 || !Entry->PrevGuestFrame) {
|
|
||||||
+ return false;
|
|
||||||
+ }
|
|
||||||
+ Entry = reinterpret_cast<const ArchHelpers::Context::ContextBackup*>(Entry->PrevGuestFrame);
|
|
||||||
+ }
|
|
||||||
+ return OnGuestAltStack(Backup, Entry->GuestFrameEnd) && Entry->GuestAltBase == Backup->GuestAltBase &&
|
|
||||||
+ Entry->GuestAltEnd == Backup->GuestAltEnd && GuestSP >= Entry->GuestInterruptedSP;
|
|
||||||
+ }
|
|
||||||
+}
|
|
||||||
+
|
|
||||||
ArchHelpers::Context::ContextBackup* SignalDelegator::StoreThreadState(FEXCore::Core::InternalThreadState* Thread, int Signal, void* ucontext) {
|
|
||||||
// We can end up getting a signal at any point in our host state
|
|
||||||
// Jump to a handler that saves all state so we can safely return
|
|
||||||
@@ -249,6 +274,19 @@ void SignalDelegator::RestoreThreadState(FEXCore::Core::InternalThreadState* Thr
|
|
||||||
}
|
|
||||||
|
|
||||||
OldSP = *reinterpret_cast<uint64_t*>(GuestSP);
|
|
||||||
+
|
|
||||||
+ auto& SignalInfo = FEX::HLE::ThreadManager::GetStateObjectFromFEXCoreThread(Thread)->SignalInfo;
|
|
||||||
+ uint64_t Entry = SignalInfo.GuestFrames;
|
|
||||||
+ for (uint32_t Depth = 1; Entry && Depth <= SignalInfo.GuestFrameCount; ++Depth) {
|
|
||||||
+ auto EntryBackup = reinterpret_cast<ArchHelpers::Context::ContextBackup*>(Entry);
|
|
||||||
+ if (Entry == OldSP) {
|
|
||||||
+ SignalInfo.GuestFrames = EntryBackup->PrevGuestFrame;
|
|
||||||
+ SignalInfo.GuestFrameCount -= Depth;
|
|
||||||
+ Thread->CurrentFrame->SignalHandlerRefCounter -= Depth - 1;
|
|
||||||
+ break;
|
|
||||||
+ }
|
|
||||||
+ Entry = EntryBackup->PrevGuestFrame;
|
|
||||||
+ }
|
|
||||||
}
|
|
||||||
|
|
||||||
uintptr_t NewSP = OldSP;
|
|
||||||
@@ -287,6 +325,7 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS
|
|
||||||
auto ContextBackup = StoreThreadState(Thread, Signal, ucontext);
|
|
||||||
|
|
||||||
auto Frame = Thread->CurrentFrame;
|
|
||||||
+ auto& SignalInfo = FEX::HLE::ThreadManager::GetStateObjectFromFEXCoreThread(Thread)->SignalInfo;
|
|
||||||
|
|
||||||
// Ref count our faults
|
|
||||||
// We use this to track if it is safe to clear cache
|
|
||||||
@@ -336,6 +375,8 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS
|
|
||||||
|
|
||||||
uint64_t OldGuestSP = Frame->State.gregs[FEXCore::X86State::REG_RSP];
|
|
||||||
uint64_t NewGuestSP = OldGuestSP;
|
|
||||||
+ uint64_t GuestAltBase = 0;
|
|
||||||
+ uint64_t GuestAltEnd = 0;
|
|
||||||
|
|
||||||
// altstack is only used if the signal handler was setup with SA_ONSTACK
|
|
||||||
if (GuestAction->sa_flags & SA_ONSTACK) {
|
|
||||||
@@ -345,6 +386,8 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS
|
|
||||||
// Then that means we are hitting recursive signals and we need to walk back the stack correctly
|
|
||||||
uint64_t AltStackBase = reinterpret_cast<uint64_t>(GuestStack->ss_sp);
|
|
||||||
uint64_t AltStackEnd = AltStackBase + GuestStack->ss_size;
|
|
||||||
+ GuestAltBase = AltStackBase;
|
|
||||||
+ GuestAltEnd = AltStackEnd;
|
|
||||||
if (OldGuestSP >= AltStackBase && OldGuestSP <= AltStackEnd) {
|
|
||||||
// We are already in the alt stack, the rest of the code will handle adjusting this
|
|
||||||
} else {
|
|
||||||
@@ -353,6 +396,40 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
+#ifdef ARCHITECTURE_arm64
|
|
||||||
+ auto Newest = reinterpret_cast<ArchHelpers::Context::ContextBackup*>(SignalInfo.GuestFrames);
|
|
||||||
+ if (WasInJIT && Newest && ContextBackup->PrevSP == SignalInfo.GuestFrames &&
|
|
||||||
+ Frame->SignalHandlerRefCounter == SignalInfo.GuestFrameCount + 1 && GuestLeftFrame(Newest, OldGuestSP, SignalInfo.GuestFrameCount)) {
|
|
||||||
+ uint32_t LeftFrames = 0;
|
|
||||||
+ while (Newest && LeftFrames < SignalInfo.GuestFrameCount &&
|
|
||||||
+ GuestLeftFrame(Newest, OldGuestSP, SignalInfo.GuestFrameCount - LeftFrames)) {
|
|
||||||
+ Newest = reinterpret_cast<ArchHelpers::Context::ContextBackup*>(Newest->PrevGuestFrame);
|
|
||||||
+ ++LeftFrames;
|
|
||||||
+ }
|
|
||||||
+
|
|
||||||
+ const uint64_t HostTop = Newest ? reinterpret_cast<uint64_t>(Newest) : Frame->ReturningStackLocation;
|
|
||||||
+ const uint64_t MovedBackup = FEXCore::AlignDown(
|
|
||||||
+ HostTop - ArchHelpers::Context::ContextBackup::RedZoneSize - sizeof(ArchHelpers::Context::ContextBackup), 16);
|
|
||||||
+ if (MovedBackup > reinterpret_cast<uint64_t>(ContextBackup)) {
|
|
||||||
+ memmove(reinterpret_cast<void*>(MovedBackup), ContextBackup, sizeof(ArchHelpers::Context::ContextBackup));
|
|
||||||
+ ContextBackup = reinterpret_cast<ArchHelpers::Context::ContextBackup*>(MovedBackup);
|
|
||||||
+ ContextBackup->PrevSP = HostTop;
|
|
||||||
+ ArchHelpers::Context::SetSp(ucontext, MovedBackup);
|
|
||||||
+ SignalInfo.GuestFrames = reinterpret_cast<uint64_t>(Newest);
|
|
||||||
+ SignalInfo.GuestFrameCount -= LeftFrames;
|
|
||||||
+ Frame->SignalHandlerRefCounter -= LeftFrames;
|
|
||||||
+ }
|
|
||||||
+ }
|
|
||||||
+#endif
|
|
||||||
+
|
|
||||||
+ ContextBackup->GuestFrameEnd = NewGuestSP;
|
|
||||||
+ ContextBackup->GuestInterruptedSP = OldGuestSP;
|
|
||||||
+ ContextBackup->GuestAltBase = GuestAltBase;
|
|
||||||
+ ContextBackup->GuestAltEnd = GuestAltEnd;
|
|
||||||
+ ContextBackup->PrevGuestFrame = SignalInfo.GuestFrames;
|
|
||||||
+ SignalInfo.GuestFrames = reinterpret_cast<uint64_t>(ContextBackup);
|
|
||||||
+ ++SignalInfo.GuestFrameCount;
|
|
||||||
+
|
|
||||||
// siginfo_t
|
|
||||||
siginfo_t* HostSigInfo = reinterpret_cast<siginfo_t*>(info);
|
|
||||||
|
|
||||||
@@ -491,6 +568,8 @@ bool SignalDelegator::HandleSignalPause(FEXCore::Core::InternalThreadState* Thre
|
|
||||||
|
|
||||||
// Our ref counting doesn't matter anymore
|
|
||||||
Thread->CurrentFrame->SignalHandlerRefCounter = 0;
|
|
||||||
+ ThreadObject->SignalInfo.GuestFrames = 0;
|
|
||||||
+ ThreadObject->SignalInfo.GuestFrameCount = 0;
|
|
||||||
|
|
||||||
// Set the new PC
|
|
||||||
if (CTX->IsAddressInCodeBuffer(Thread, ArchHelpers::Context::GetPc(ucontext))) {
|
|
||||||
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h
|
|
||||||
index dfcd4b0..e4a86a9 100644
|
|
||||||
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h
|
|
||||||
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h
|
|
||||||
@@ -83,6 +83,9 @@ struct ThreadStateObject : public FEXCore::Allocator::FEXAllocOperators {
|
|
||||||
// Queue of thread local signal frames that have been deferred.
|
|
||||||
// Async signals aren't guaranteed to be delivered in any particular order, but FEX treats them as FILO.
|
|
||||||
fextl::vector<DeferredSignalState> DeferredSignalFrames;
|
|
||||||
+
|
|
||||||
+ uint64_t GuestFrames {};
|
|
||||||
+ uint32_t GuestFrameCount {};
|
|
||||||
} SignalInfo {};
|
|
||||||
|
|
||||||
// Seccomp thread specific data.
|
|
||||||
@@ -1,23 +0,0 @@
|
|||||||
Fixed-upstream: FEX-2612
|
|
||||||
diff --git a/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp b/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp
|
|
||||||
index c2b1d8e287..fcdf261484 100644
|
|
||||||
--- a/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp
|
|
||||||
+++ b/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp
|
|
||||||
@@ -285,6 +285,8 @@ DEF_OP(CondJump) {
|
|
||||||
DEF_OP(Syscall) {
|
|
||||||
SpillStaticRegs(TMP1);
|
|
||||||
|
|
||||||
+ ResetStack();
|
|
||||||
+
|
|
||||||
// Jump to the syscall dispatch handler. We won't return after this.
|
|
||||||
ldr(TMP1, STATE, offsetof(FEXCore::Core::CpuStateFrame, Pointers.ThreadDispatchSyscallHandler));
|
|
||||||
br(TMP1);
|
|
||||||
@@ -376,6 +378,8 @@ DEF_OP(ThreadRemoveCodeEntry) {
|
|
||||||
|
|
||||||
SpillStaticRegs(TMP1);
|
|
||||||
|
|
||||||
+ ResetStack();
|
|
||||||
+
|
|
||||||
// Store the new RIP to go to.
|
|
||||||
str(GetReg(Op->NewRIP).X(), STATE, offsetof(FEXCore::Core::CpuStateFrame, State.rip));
|
|
||||||
|
|
||||||
@@ -1,109 +0,0 @@
|
|||||||
diff --git a/FEXCore/Source/Interface/Core/Core.cpp b/FEXCore/Source/Interface/Core/Core.cpp
|
|
||||||
--- a/FEXCore/Source/Interface/Core/Core.cpp
|
|
||||||
+++ b/FEXCore/Source/Interface/Core/Core.cpp
|
|
||||||
@@ -383,7 +383,11 @@
|
|
||||||
}
|
|
||||||
|
|
||||||
void ContextImpl::HandleCallback(FEXCore::Core::InternalThreadState* Thread, uint64_t RIP) {
|
|
||||||
- static_cast<ContextImpl*>(Thread->CTX)->Dispatcher->ExecuteJITCallback(Thread->CurrentFrame, RIP);
|
|
||||||
+ auto Frame = Thread->CurrentFrame;
|
|
||||||
+ const auto InSyscallInfo = Frame->InSyscallInfo;
|
|
||||||
+ Frame->InSyscallInfo = 0;
|
|
||||||
+ static_cast<ContextImpl*>(Thread->CTX)->Dispatcher->ExecuteJITCallback(Frame, RIP);
|
|
||||||
+ Frame->InSyscallInfo = InSyscallInfo;
|
|
||||||
}
|
|
||||||
|
|
||||||
void ContextImpl::ExecuteThread(FEXCore::Core::InternalThreadState* Thread) {
|
|
||||||
diff --git a/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp b/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp
|
|
||||||
--- a/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp
|
|
||||||
+++ b/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp
|
|
||||||
@@ -305,6 +305,9 @@
|
|
||||||
|
|
||||||
PushDynamicRegs(TMP1);
|
|
||||||
|
|
||||||
+ LoadConstant(ARMEmitter::Size::i64Bit, TMP1, 0xFFFF);
|
|
||||||
+ str(TMP1, STATE, offsetof(FEXCore::Core::CpuStateFrame, InSyscallInfo));
|
|
||||||
+
|
|
||||||
mov(ARMEmitter::Size::i64Bit, ARMEmitter::Reg::r0, GetReg(Op->ArgPtr));
|
|
||||||
|
|
||||||
InsertNamedThunkRelocation(ARMEmitter::Reg::r2, Op->ThunkNameHash);
|
|
||||||
@@ -320,6 +323,8 @@
|
|
||||||
FillStaticRegs({
|
|
||||||
.NZCV = false,
|
|
||||||
});
|
|
||||||
+
|
|
||||||
+ str(ARMEmitter::XReg::zr, STATE, offsetof(FEXCore::Core::CpuStateFrame, InSyscallInfo));
|
|
||||||
}
|
|
||||||
|
|
||||||
DEF_OP(ValidateCode) {
|
|
||||||
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp
|
|
||||||
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp
|
|
||||||
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp
|
|
||||||
@@ -107,6 +107,10 @@
|
|
||||||
#ifdef ARCHITECTURE_arm64
|
|
||||||
Thread->CurrentFrame->State.rip = CTX->RestoreRIPFromHostPC(Thread, ArchHelpers::Context::GetPc(ucontext));
|
|
||||||
|
|
||||||
+ if ((IgnoreMask & 0xFFFF) == 0xFFFF) {
|
|
||||||
+ return;
|
|
||||||
+ }
|
|
||||||
+
|
|
||||||
for (size_t i = 0; i < Config.SRAGPRCount; i++) {
|
|
||||||
const uint8_t SRAIdxMap = Config.SRAGPRMapping[i];
|
|
||||||
if (IgnoreMask & (1U << SRAIdxMap)) {
|
|
||||||
@@ -301,12 +305,10 @@
|
|
||||||
if (Context->UContextLocation) {
|
|
||||||
auto Frame = Thread->CurrentFrame;
|
|
||||||
|
|
||||||
- if (Context->Flags & ArchHelpers::Context::ContextFlags::CONTEXT_FLAG_INJIT) {
|
|
||||||
- // XXX: Unsupported since it needs state reconstruction
|
|
||||||
- // If we are in the JIT then SRA might need to be restored to values from the context
|
|
||||||
- // We can't currently support this since it might result in tearing without real state reconstruction
|
|
||||||
- Frame->InSyscallInfo = Context->InSyscallInfo;
|
|
||||||
- }
|
|
||||||
+ // XXX: Unsupported since it needs state reconstruction
|
|
||||||
+ // If we are in the JIT then SRA might need to be restored to values from the context
|
|
||||||
+ // We can't currently support this since it might result in tearing without real state reconstruction
|
|
||||||
+ Frame->InSyscallInfo = Context->InSyscallInfo;
|
|
||||||
|
|
||||||
if (Is64BitMode) {
|
|
||||||
RestoreFrame_x64(Thread, Context, Frame, ucontext);
|
|
||||||
@@ -361,6 +363,9 @@
|
|
||||||
ContextBackup->InSyscallInfo = Thread->CurrentFrame->InSyscallInfo;
|
|
||||||
Thread->CurrentFrame->InSyscallInfo = 0;
|
|
||||||
} else {
|
|
||||||
+ ContextBackup->InSyscallInfo = Frame->InSyscallInfo;
|
|
||||||
+ Frame->InSyscallInfo = 0;
|
|
||||||
+
|
|
||||||
if (!IsAddressInDispatcher(OldPC)) {
|
|
||||||
// This is likely to cause issues but in some cases it isn't fatal
|
|
||||||
// This can also happen if we have put a signal on hold, then we just reenabled the signal
|
|
||||||
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp
|
|
||||||
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp
|
|
||||||
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp
|
|
||||||
@@ -131,7 +131,7 @@
|
|
||||||
if (Context->OriginalRIP != guest_uctx->uc_mcontext.gregs[FEXCore::x86_64::FEX_REG_RIP] || Context->FaultToTopAndGeneratedException) {
|
|
||||||
|
|
||||||
// Restore previous `InSyscallInfo` structure.
|
|
||||||
- Frame->InSyscallInfo = Context->InSyscallInfo;
|
|
||||||
+ Frame->InSyscallInfo = 0;
|
|
||||||
|
|
||||||
// Hack! Go back to the top of the dispatcher top
|
|
||||||
// This is only safe inside the JIT rather than anything outside of it
|
|
||||||
@@ -211,7 +211,7 @@
|
|
||||||
// If the guest modified the RIP then we need to take special precautions here
|
|
||||||
if (Context->OriginalRIP != guest_uctx->sc.ip || Context->FaultToTopAndGeneratedException) {
|
|
||||||
// Restore previous `InSyscallInfo` structure.
|
|
||||||
- Frame->InSyscallInfo = Context->InSyscallInfo;
|
|
||||||
+ Frame->InSyscallInfo = 0;
|
|
||||||
|
|
||||||
// Hack! Go back to the top of the dispatcher top
|
|
||||||
// This is only safe inside the JIT rather than anything outside of it
|
|
||||||
@@ -290,7 +290,7 @@
|
|
||||||
if (Context->OriginalRIP != guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_EIP] || Context->FaultToTopAndGeneratedException) {
|
|
||||||
|
|
||||||
// Restore previous `InSyscallInfo` structure.
|
|
||||||
- Frame->InSyscallInfo = Context->InSyscallInfo;
|
|
||||||
+ Frame->InSyscallInfo = 0;
|
|
||||||
|
|
||||||
// Hack! Go back to the top of the dispatcher top
|
|
||||||
// This is only safe inside the JIT rather than anything outside of it
|
|
||||||
@@ -1,112 +0,0 @@
|
|||||||
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h
|
|
||||||
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h
|
|
||||||
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h
|
|
||||||
@@ -263,6 +263,8 @@
|
|
||||||
FEXCore::Core::CpuStateFrame* Frame, void* ucontext);
|
|
||||||
void RestoreRTFrame_ia32(FEXCore::Core::InternalThreadState* Thread, ArchHelpers::Context::ContextBackup* Context,
|
|
||||||
FEXCore::Core::CpuStateFrame* Frame, void* ucontext);
|
|
||||||
+ void ResumeWithGuestGPRs(ArchHelpers::Context::ContextBackup* Context, FEXCore::Core::CpuStateFrame* Frame, void* ucontext,
|
|
||||||
+ const uint64_t* GuestGPRs, size_t Count, uint64_t Mask);
|
|
||||||
|
|
||||||
///< Setup the signal frame for x64.
|
|
||||||
uint64_t SetupFrame_x64(FEXCore::Core::InternalThreadState* Thread, ArchHelpers::Context::ContextBackup* ContextBackup,
|
|
||||||
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp
|
|
||||||
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp
|
|
||||||
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp
|
|
||||||
@@ -122,6 +122,32 @@
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
+void SignalDelegator::ResumeWithGuestGPRs(ArchHelpers::Context::ContextBackup* Context, FEXCore::Core::CpuStateFrame* Frame, void* ucontext,
|
|
||||||
+ const uint64_t* GuestGPRs, size_t Count, uint64_t Mask) {
|
|
||||||
+#ifdef ARCHITECTURE_arm64
|
|
||||||
+ const uint32_t Spilled = Context->InSyscallInfo & 0xFFFF;
|
|
||||||
+ const bool AllSpilled = Spilled == 0xFFFF;
|
|
||||||
+ if (!AllSpilled && !(Context->Flags & ArchHelpers::Context::ContextFlags::CONTEXT_FLAG_INJIT)) {
|
|
||||||
+ return;
|
|
||||||
+ }
|
|
||||||
+
|
|
||||||
+ for (size_t i = 0; i < Count && i < Config.SRAGPRCount; i++) {
|
|
||||||
+ const uint8_t HostReg = Config.SRAGPRMapping[i];
|
|
||||||
+ const bool InFrame = AllSpilled || (Spilled & (1U << HostReg));
|
|
||||||
+ const uint64_t Delivered = InFrame ? Frame->State.gregs[i] : ArchHelpers::Context::GetArmReg(ucontext, HostReg);
|
|
||||||
+ if (((Delivered ^ GuestGPRs[i]) & Mask) == 0) {
|
|
||||||
+ continue;
|
|
||||||
+ }
|
|
||||||
+
|
|
||||||
+ if (InFrame) {
|
|
||||||
+ Frame->State.gregs[i] = GuestGPRs[i];
|
|
||||||
+ } else {
|
|
||||||
+ ArchHelpers::Context::SetArmReg(ucontext, HostReg, GuestGPRs[i]);
|
|
||||||
+ }
|
|
||||||
+ }
|
|
||||||
+#endif
|
|
||||||
+}
|
|
||||||
+
|
|
||||||
void SignalDelegator::RestoreFrame_x64(FEXCore::Core::InternalThreadState* Thread, ArchHelpers::Context::ContextBackup* Context,
|
|
||||||
FEXCore::Core::CpuStateFrame* Frame, void* ucontext) {
|
|
||||||
auto* guest_uctx = reinterpret_cast<FEXCore::x86_64::ucontext_t*>(Context->UContextLocation);
|
|
||||||
@@ -202,6 +228,27 @@
|
|
||||||
const auto modulo_i = (i + CurrentOffset) % 8;
|
|
||||||
memcpy(&Frame->State.mm[modulo_i], &fpstate->_st[i], sizeof(Frame->State.mm[0]));
|
|
||||||
}
|
|
||||||
+ } else {
|
|
||||||
+ uint64_t GuestGPRs[FEXCore::Core::CPUState::NUM_GPRS];
|
|
||||||
+#define COPY_REG(x) GuestGPRs[FEXCore::X86State::REG_##x] = guest_uctx->uc_mcontext.gregs[FEXCore::x86_64::FEX_REG_##x];
|
|
||||||
+ COPY_REG(R8);
|
|
||||||
+ COPY_REG(R9);
|
|
||||||
+ COPY_REG(R10);
|
|
||||||
+ COPY_REG(R11);
|
|
||||||
+ COPY_REG(R12);
|
|
||||||
+ COPY_REG(R13);
|
|
||||||
+ COPY_REG(R14);
|
|
||||||
+ COPY_REG(R15);
|
|
||||||
+ COPY_REG(RDI);
|
|
||||||
+ COPY_REG(RSI);
|
|
||||||
+ COPY_REG(RBP);
|
|
||||||
+ COPY_REG(RBX);
|
|
||||||
+ COPY_REG(RDX);
|
|
||||||
+ COPY_REG(RAX);
|
|
||||||
+ COPY_REG(RCX);
|
|
||||||
+ COPY_REG(RSP);
|
|
||||||
+#undef COPY_REG
|
|
||||||
+ ResumeWithGuestGPRs(Context, Frame, ucontext, GuestGPRs, FEXCore::Core::CPUState::NUM_GPRS, ~0ULL);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@@ -280,6 +327,17 @@
|
|
||||||
const auto modulo_i = (i + CurrentOffset) % 8;
|
|
||||||
memcpy(&Frame->State.mm[modulo_i], &fpstate->_st[i], 10);
|
|
||||||
}
|
|
||||||
+ } else {
|
|
||||||
+ uint64_t GuestGPRs[8];
|
|
||||||
+ GuestGPRs[FEXCore::X86State::REG_RAX] = guest_uctx->sc.ax;
|
|
||||||
+ GuestGPRs[FEXCore::X86State::REG_RCX] = guest_uctx->sc.cx;
|
|
||||||
+ GuestGPRs[FEXCore::X86State::REG_RDX] = guest_uctx->sc.dx;
|
|
||||||
+ GuestGPRs[FEXCore::X86State::REG_RBX] = guest_uctx->sc.bx;
|
|
||||||
+ GuestGPRs[FEXCore::X86State::REG_RSP] = guest_uctx->sc.sp;
|
|
||||||
+ GuestGPRs[FEXCore::X86State::REG_RBP] = guest_uctx->sc.bp;
|
|
||||||
+ GuestGPRs[FEXCore::X86State::REG_RSI] = guest_uctx->sc.si;
|
|
||||||
+ GuestGPRs[FEXCore::X86State::REG_RDI] = guest_uctx->sc.di;
|
|
||||||
+ ResumeWithGuestGPRs(Context, Frame, ucontext, GuestGPRs, 8, 0xFFFF'FFFFULL);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@@ -359,6 +417,17 @@
|
|
||||||
const auto modulo_i = (i + CurrentOffset) % 8;
|
|
||||||
memcpy(&Frame->State.mm[modulo_i], &fpstate->_st[i], 10);
|
|
||||||
}
|
|
||||||
+ } else {
|
|
||||||
+ uint64_t GuestGPRs[8];
|
|
||||||
+ GuestGPRs[FEXCore::X86State::REG_RAX] = guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_RAX];
|
|
||||||
+ GuestGPRs[FEXCore::X86State::REG_RCX] = guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_RCX];
|
|
||||||
+ GuestGPRs[FEXCore::X86State::REG_RDX] = guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_RDX];
|
|
||||||
+ GuestGPRs[FEXCore::X86State::REG_RBX] = guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_RBX];
|
|
||||||
+ GuestGPRs[FEXCore::X86State::REG_RSP] = guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_RSP];
|
|
||||||
+ GuestGPRs[FEXCore::X86State::REG_RBP] = guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_RBP];
|
|
||||||
+ GuestGPRs[FEXCore::X86State::REG_RSI] = guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_RSI];
|
|
||||||
+ GuestGPRs[FEXCore::X86State::REG_RDI] = guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_RDI];
|
|
||||||
+ ResumeWithGuestGPRs(Context, Frame, ucontext, GuestGPRs, 8, 0xFFFF'FFFFULL);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@@ -1,84 +0,0 @@
|
|||||||
#define _GNU_SOURCE
|
|
||||||
#include <pthread.h>
|
|
||||||
#include <signal.h>
|
|
||||||
#include <stdio.h>
|
|
||||||
#include <stdlib.h>
|
|
||||||
#include <sys/syscall.h>
|
|
||||||
#include <ucontext.h>
|
|
||||||
#include <unistd.h>
|
|
||||||
|
|
||||||
volatile long base;
|
|
||||||
static volatile long hits, matched, stale, stop;
|
|
||||||
static long want;
|
|
||||||
static pid_t target;
|
|
||||||
extern char probe_loop_start[], probe_loop_end[];
|
|
||||||
|
|
||||||
static void handler(int sig, siginfo_t *info, void *context) {
|
|
||||||
greg_t *g = ((ucontext_t *)context)->uc_mcontext.gregs;
|
|
||||||
(void)sig;
|
|
||||||
(void)info;
|
|
||||||
if (g[REG_RIP] >= (greg_t)probe_loop_start && g[REG_RIP] < (greg_t)probe_loop_end) {
|
|
||||||
long below = base - g[REG_RSP];
|
|
||||||
if (g[REG_RBX] == 0x1111111111111111L && g[REG_R12] == 0x2222222222222222L && g[REG_R13] == 0x3333333333333333L &&
|
|
||||||
g[REG_R14] == 0x4444444444444444L && g[REG_R15] == 0x5555555555555555L && (unsigned long)g[REG_RCX] <= 4096 &&
|
|
||||||
(below == 0 || below == 8))
|
|
||||||
matched++;
|
|
||||||
else
|
|
||||||
stale++;
|
|
||||||
}
|
|
||||||
hits++;
|
|
||||||
}
|
|
||||||
|
|
||||||
static void *sender(void *arg) {
|
|
||||||
(void)arg;
|
|
||||||
while (!stop) {
|
|
||||||
syscall(SYS_tgkill, getpid(), target, SIGUSR1);
|
|
||||||
usleep(50);
|
|
||||||
}
|
|
||||||
return NULL;
|
|
||||||
}
|
|
||||||
|
|
||||||
int main(int argc, char **argv) {
|
|
||||||
struct sigaction action = {0};
|
|
||||||
pthread_t thread;
|
|
||||||
want = argc > 1 ? atol(argv[1]) : 2000;
|
|
||||||
action.sa_sigaction = handler;
|
|
||||||
action.sa_flags = SA_SIGINFO | SA_RESTART;
|
|
||||||
sigaction(SIGUSR1, &action, NULL);
|
|
||||||
sigset_t usr1;
|
|
||||||
sigemptyset(&usr1);
|
|
||||||
sigaddset(&usr1, SIGUSR1);
|
|
||||||
pthread_sigmask(SIG_UNBLOCK, &usr1, NULL);
|
|
||||||
target = syscall(SYS_gettid);
|
|
||||||
if (pthread_create(&thread, NULL, sender, NULL) != 0) {
|
|
||||||
fprintf(stderr, "cannot start the signal sender\n");
|
|
||||||
return 2;
|
|
||||||
}
|
|
||||||
while (matched + stale < want) {
|
|
||||||
__asm__ volatile("mov $0x1111111111111111, %%rbx\n"
|
|
||||||
"mov $0x2222222222222222, %%r12\n"
|
|
||||||
"mov $0x3333333333333333, %%r13\n"
|
|
||||||
"mov $0x4444444444444444, %%r14\n"
|
|
||||||
"mov $0x5555555555555555, %%r15\n"
|
|
||||||
"mov %%rsp, base(%%rip)\n"
|
|
||||||
"mov $4096, %%ecx\n"
|
|
||||||
".globl probe_loop_start\n"
|
|
||||||
"probe_loop_start:\n"
|
|
||||||
"push %%rax\n"
|
|
||||||
"1: dec %%ecx\n"
|
|
||||||
"jnz 1b\n"
|
|
||||||
"pop %%rax\n"
|
|
||||||
"mov $4096, %%ecx\n"
|
|
||||||
"2: dec %%ecx\n"
|
|
||||||
"jnz 2b\n"
|
|
||||||
".globl probe_loop_end\n"
|
|
||||||
"probe_loop_end:\n"
|
|
||||||
:
|
|
||||||
:
|
|
||||||
: "rbx", "rcx", "r12", "r13", "r14", "r15", "memory");
|
|
||||||
}
|
|
||||||
stop = 1;
|
|
||||||
pthread_join(thread, NULL);
|
|
||||||
printf("signals=%ld matched=%ld stale=%ld\n", hits, matched, stale);
|
|
||||||
return stale ? 1 : 0;
|
|
||||||
}
|
|
||||||
@@ -1,90 +0,0 @@
|
|||||||
#define _GNU_SOURCE
|
|
||||||
#include <setjmp.h>
|
|
||||||
#include <signal.h>
|
|
||||||
#include <stdio.h>
|
|
||||||
#include <stdlib.h>
|
|
||||||
#include <string.h>
|
|
||||||
|
|
||||||
static sigjmp_buf main_env, inner_env;
|
|
||||||
static volatile int depth, nested_mode;
|
|
||||||
static volatile long escapes, nested, returns, wrong;
|
|
||||||
|
|
||||||
static void fault(long i) {
|
|
||||||
*(volatile int *)(long)(8 + (i & 7)) = 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
static void segv(int sig, siginfo_t *info, void *context) {
|
|
||||||
(void)sig;
|
|
||||||
(void)info;
|
|
||||||
(void)context;
|
|
||||||
if (!nested_mode) {
|
|
||||||
escapes++;
|
|
||||||
siglongjmp(main_env, 1);
|
|
||||||
}
|
|
||||||
if (depth == 1) {
|
|
||||||
nested++;
|
|
||||||
siglongjmp(inner_env, 1);
|
|
||||||
}
|
|
||||||
depth = 1;
|
|
||||||
for (volatile int k = 0; k < 3; k++)
|
|
||||||
if (sigsetjmp(inner_env, 0) == 0)
|
|
||||||
fault(k);
|
|
||||||
depth = 0;
|
|
||||||
escapes++;
|
|
||||||
siglongjmp(main_env, 1);
|
|
||||||
}
|
|
||||||
|
|
||||||
static void trap(int sig, siginfo_t *info, void *context) {
|
|
||||||
(void)sig;
|
|
||||||
(void)info;
|
|
||||||
(void)context;
|
|
||||||
returns++;
|
|
||||||
}
|
|
||||||
|
|
||||||
static void install(int onstack) {
|
|
||||||
struct sigaction action;
|
|
||||||
memset(&action, 0, sizeof(action));
|
|
||||||
action.sa_sigaction = segv;
|
|
||||||
action.sa_flags = SA_SIGINFO | SA_NODEFER | (onstack ? SA_ONSTACK : 0);
|
|
||||||
sigaction(SIGSEGV, &action, NULL);
|
|
||||||
}
|
|
||||||
|
|
||||||
static long run(long count, int with_trap) {
|
|
||||||
long start = escapes;
|
|
||||||
for (volatile long i = 0; i < count; i++) {
|
|
||||||
if (with_trap) {
|
|
||||||
volatile long before = i * 3;
|
|
||||||
__asm__ volatile("int3" ::: "memory");
|
|
||||||
if (before != i * 3)
|
|
||||||
wrong++;
|
|
||||||
}
|
|
||||||
if (sigsetjmp(main_env, 1) == 0)
|
|
||||||
fault(i);
|
|
||||||
}
|
|
||||||
return escapes - start;
|
|
||||||
}
|
|
||||||
|
|
||||||
int main(int argc, char **argv) {
|
|
||||||
long want = argc > 1 ? atol(argv[1]) : 50000;
|
|
||||||
stack_t ss = {.ss_sp = malloc(262144), .ss_size = 262144};
|
|
||||||
struct sigaction action;
|
|
||||||
sigaltstack(&ss, NULL);
|
|
||||||
memset(&action, 0, sizeof(action));
|
|
||||||
action.sa_sigaction = trap;
|
|
||||||
action.sa_flags = SA_SIGINFO;
|
|
||||||
sigaction(SIGTRAP, &action, NULL);
|
|
||||||
|
|
||||||
install(1);
|
|
||||||
long onstack = run(want, 0);
|
|
||||||
install(0);
|
|
||||||
long offstack = run(want, 0);
|
|
||||||
install(1);
|
|
||||||
long mixed = run(want, 1);
|
|
||||||
nested_mode = 1;
|
|
||||||
long outer = run(want, 0);
|
|
||||||
|
|
||||||
printf("onstack=%ld offstack=%ld mixed=%ld returns=%ld outer=%ld nested=%ld wrong=%ld\n", onstack, offstack, mixed, returns,
|
|
||||||
outer, nested, wrong);
|
|
||||||
return onstack == want && offstack == want && mixed == want && returns == want && outer == want && nested == 3 * want && !wrong ? 0
|
|
||||||
: 1;
|
|
||||||
}
|
|
||||||
@@ -1,88 +0,0 @@
|
|||||||
#define _GNU_SOURCE
|
|
||||||
#include <signal.h>
|
|
||||||
#include <stdio.h>
|
|
||||||
#include <string.h>
|
|
||||||
#include <sys/time.h>
|
|
||||||
#include <ucontext.h>
|
|
||||||
|
|
||||||
#define MARK 0x5eed
|
|
||||||
|
|
||||||
static volatile sig_atomic_t alarms;
|
|
||||||
static volatile sig_atomic_t give_up;
|
|
||||||
|
|
||||||
static void count_alarm(void) {
|
|
||||||
if (++alarms > 100) {
|
|
||||||
give_up = 1;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
static void on_alarm(int sig, siginfo_t *si, void *ctx) {
|
|
||||||
(void)sig;
|
|
||||||
(void)si;
|
|
||||||
ucontext_t *uc = ctx;
|
|
||||||
count_alarm();
|
|
||||||
#ifdef __x86_64__
|
|
||||||
uc->uc_mcontext.gregs[REG_R12] = MARK;
|
|
||||||
#else
|
|
||||||
uc->uc_mcontext.gregs[REG_ESI] = MARK;
|
|
||||||
#endif
|
|
||||||
}
|
|
||||||
|
|
||||||
#ifdef __i386__
|
|
||||||
static void on_alarm_legacy(int sig, struct sigcontext sc) {
|
|
||||||
(void)sig;
|
|
||||||
count_alarm();
|
|
||||||
((volatile struct sigcontext *)&sc)->esi = MARK;
|
|
||||||
}
|
|
||||||
#endif
|
|
||||||
|
|
||||||
int main(int argc, char **argv) {
|
|
||||||
int legacy = argc > 1 && strcmp(argv[1], "legacy") == 0;
|
|
||||||
struct sigaction sa;
|
|
||||||
memset(&sa, 0, sizeof(sa));
|
|
||||||
sa.sa_flags = SA_RESTART;
|
|
||||||
#ifdef __i386__
|
|
||||||
if (legacy) {
|
|
||||||
sa.sa_handler = (void (*)(int))on_alarm_legacy;
|
|
||||||
} else
|
|
||||||
#endif
|
|
||||||
{
|
|
||||||
legacy = 0;
|
|
||||||
sa.sa_sigaction = on_alarm;
|
|
||||||
sa.sa_flags |= SA_SIGINFO;
|
|
||||||
}
|
|
||||||
sigaction(SIGALRM, &sa, NULL);
|
|
||||||
struct itimerval it = {{0, 20000}, {0, 20000}};
|
|
||||||
setitimer(ITIMER_REAL, &it, NULL);
|
|
||||||
|
|
||||||
unsigned long spins, seen;
|
|
||||||
#ifdef __x86_64__
|
|
||||||
__asm__ volatile("xor %%r12, %%r12\n"
|
|
||||||
"xor %0, %0\n"
|
|
||||||
"1: inc %0\n"
|
|
||||||
"test %%r12, %%r12\n"
|
|
||||||
"jnz 2f\n"
|
|
||||||
"cmpl $0, %2\n"
|
|
||||||
"je 1b\n"
|
|
||||||
"2: mov %%r12, %1\n"
|
|
||||||
: "=&r"(spins), "=&r"(seen)
|
|
||||||
: "m"(give_up)
|
|
||||||
: "r12", "cc");
|
|
||||||
#else
|
|
||||||
__asm__ volatile("xor %%esi, %%esi\n"
|
|
||||||
"xor %0, %0\n"
|
|
||||||
"1: inc %0\n"
|
|
||||||
"test %%esi, %%esi\n"
|
|
||||||
"jnz 2f\n"
|
|
||||||
"cmpl $0, %2\n"
|
|
||||||
"je 1b\n"
|
|
||||||
"2: mov %%esi, %1\n"
|
|
||||||
: "=&r"(spins), "=&r"(seen)
|
|
||||||
: "m"(give_up)
|
|
||||||
: "esi", "cc");
|
|
||||||
#endif
|
|
||||||
struct itimerval off = {{0, 0}, {0, 0}};
|
|
||||||
setitimer(ITIMER_REAL, &off, NULL);
|
|
||||||
printf("frame=%s seen=%d alarms=%d spins=%lu\n", legacy ? "legacy" : "rt", seen == MARK, (int)alarms, spins);
|
|
||||||
return seen == MARK ? 0 : 1;
|
|
||||||
}
|
|
||||||
@@ -1,65 +0,0 @@
|
|||||||
#define _GNU_SOURCE
|
|
||||||
#include <cpuid.h>
|
|
||||||
#include <stdio.h>
|
|
||||||
#include <stdlib.h>
|
|
||||||
#include <sys/syscall.h>
|
|
||||||
|
|
||||||
#define YMM_STEP(a, b) "vpaddq %%ymm" #b ", %%ymm" #a ", %%ymm" #a "\n"
|
|
||||||
#define MMX_STEP(a, b) "paddq %%mm" #b ", %%mm" #a "\n"
|
|
||||||
|
|
||||||
static int has_avx2(void) {
|
|
||||||
unsigned a, b, c, d;
|
|
||||||
if (!__get_cpuid(1, &a, &b, &c, &d) || !(c & bit_AVX) || !(c & bit_OSXSAVE))
|
|
||||||
return 0;
|
|
||||||
unsigned lo, hi;
|
|
||||||
__asm__ volatile("xgetbv" : "=a"(lo), "=d"(hi) : "c"(0));
|
|
||||||
if ((lo & 6) != 6 || !__get_cpuid_count(7, 0, &a, &b, &c, &d))
|
|
||||||
return 0;
|
|
||||||
return (b & bit_AVX2) != 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
static long ymm_round(long n) {
|
|
||||||
long pid = 0;
|
|
||||||
for (long i = 0; i < n; i++) {
|
|
||||||
__asm__ volatile(
|
|
||||||
YMM_STEP(0, 1) YMM_STEP(1, 2) YMM_STEP(2, 3) YMM_STEP(3, 4) YMM_STEP(4, 5) YMM_STEP(5, 6) YMM_STEP(6, 7) YMM_STEP(7, 8)
|
|
||||||
YMM_STEP(8, 9) YMM_STEP(9, 10) YMM_STEP(10, 11) YMM_STEP(11, 12) YMM_STEP(12, 13) YMM_STEP(13, 14) YMM_STEP(14, 15)
|
|
||||||
YMM_STEP(15, 0) YMM_STEP(0, 15) YMM_STEP(1, 14) YMM_STEP(2, 13) YMM_STEP(3, 12) YMM_STEP(4, 11) YMM_STEP(5, 10)
|
|
||||||
YMM_STEP(6, 9) YMM_STEP(7, 8)
|
|
||||||
"mov %1, %%eax\n"
|
|
||||||
"syscall\n"
|
|
||||||
: "=a"(pid)
|
|
||||||
: "i"(SYS_getpid)
|
|
||||||
: "rcx", "r11", "memory", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6", "xmm7", "xmm8", "xmm9", "xmm10",
|
|
||||||
"xmm11", "xmm12", "xmm13", "xmm14", "xmm15");
|
|
||||||
}
|
|
||||||
__asm__ volatile("vzeroupper" ::: "memory");
|
|
||||||
return pid;
|
|
||||||
}
|
|
||||||
|
|
||||||
static long mmx_round(long n) {
|
|
||||||
long pid = 0;
|
|
||||||
for (long i = 0; i < n; i++) {
|
|
||||||
__asm__ volatile(
|
|
||||||
MMX_STEP(0, 1) MMX_STEP(1, 2) MMX_STEP(2, 3) MMX_STEP(3, 4) MMX_STEP(4, 5) MMX_STEP(5, 6) MMX_STEP(6, 7) MMX_STEP(7, 0)
|
|
||||||
"mov %1, %%eax\n"
|
|
||||||
"syscall\n"
|
|
||||||
: "=a"(pid)
|
|
||||||
: "i"(SYS_getpid)
|
|
||||||
: "rcx", "r11", "memory", "mm0", "mm1", "mm2", "mm3", "mm4", "mm5", "mm6", "mm7");
|
|
||||||
}
|
|
||||||
__asm__ volatile("emms" ::: "memory");
|
|
||||||
return pid;
|
|
||||||
}
|
|
||||||
|
|
||||||
int main(int argc, char **argv) {
|
|
||||||
long want = argc > 1 ? atol(argv[1]) : 2000000;
|
|
||||||
int avx = has_avx2();
|
|
||||||
long done = 0;
|
|
||||||
for (; done < want; done += 1000) {
|
|
||||||
if (avx ? ymm_round(1000) <= 0 : mmx_round(1000) <= 0)
|
|
||||||
return 2;
|
|
||||||
}
|
|
||||||
printf("mode=%s syscalls=%ld\n", avx ? "avx" : "mmx", done);
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
@@ -1,49 +0,0 @@
|
|||||||
#define _GNU_SOURCE
|
|
||||||
#include <signal.h>
|
|
||||||
#include <stdio.h>
|
|
||||||
#include <stdlib.h>
|
|
||||||
#include <string.h>
|
|
||||||
#include <sys/time.h>
|
|
||||||
#include <time.h>
|
|
||||||
|
|
||||||
static volatile sig_atomic_t alarms;
|
|
||||||
|
|
||||||
static void on_alarm(int sig) {
|
|
||||||
(void)sig;
|
|
||||||
alarms++;
|
|
||||||
}
|
|
||||||
|
|
||||||
int main(int argc, char **argv) {
|
|
||||||
int seconds = argc > 1 ? atoi(argv[1]) : 3;
|
|
||||||
struct sigaction sa;
|
|
||||||
memset(&sa, 0, sizeof(sa));
|
|
||||||
sa.sa_handler = on_alarm;
|
|
||||||
sa.sa_flags = SA_RESTART;
|
|
||||||
sigaction(SIGALRM, &sa, NULL);
|
|
||||||
struct itimerval it = {{0, 1000}, {0, 1000}};
|
|
||||||
setitimer(ITIMER_REAL, &it, NULL);
|
|
||||||
|
|
||||||
struct timespec start, now, last;
|
|
||||||
clock_gettime(CLOCK_MONOTONIC, &start);
|
|
||||||
last = start;
|
|
||||||
unsigned long calls = 0, bad = 0;
|
|
||||||
unsigned long a = 1, b = 3, c = 1 ^ 0x5a5a5a5a5a5a5a5aUL;
|
|
||||||
do {
|
|
||||||
clock_gettime(CLOCK_MONOTONIC, &now);
|
|
||||||
calls++;
|
|
||||||
__asm__ volatile("" : "+r"(a), "+r"(b), "+r"(c));
|
|
||||||
if (b != a * 3 || c != (a ^ 0x5a5a5a5a5a5a5a5aUL))
|
|
||||||
bad++;
|
|
||||||
if (now.tv_sec < last.tv_sec || (now.tv_sec == last.tv_sec && now.tv_nsec < last.tv_nsec))
|
|
||||||
bad++;
|
|
||||||
last = now;
|
|
||||||
a = a * 6364136223846793005UL + 1442695040888963407UL;
|
|
||||||
b = a * 3;
|
|
||||||
c = a ^ 0x5a5a5a5a5a5a5a5aUL;
|
|
||||||
} while ((now.tv_sec - start.tv_sec) * 1000000000L + (now.tv_nsec - start.tv_nsec) < seconds * 1000000000L);
|
|
||||||
|
|
||||||
struct itimerval off = {{0, 0}, {0, 0}};
|
|
||||||
setitimer(ITIMER_REAL, &off, NULL);
|
|
||||||
printf("calls=%lu alarms=%d bad=%lu\n", calls, (int)alarms, bad);
|
|
||||||
return bad || alarms == 0;
|
|
||||||
}
|
|
||||||
@@ -1206,15 +1206,6 @@ def handle(agent_dir, req):
|
|||||||
raise AgentError("UNKNOWN_REQUEST", "Unknown agent request '%s'" % kind)
|
raise AgentError("UNKNOWN_REQUEST", "Unknown agent request '%s'" % kind)
|
||||||
|
|
||||||
|
|
||||||
def reply(agent_dir, req):
|
|
||||||
try:
|
|
||||||
return dict(handle(agent_dir, req), ok=True)
|
|
||||||
except AgentError as e:
|
|
||||||
return {"ok": False, "error": {"code": e.code, "message": str(e)}}
|
|
||||||
except Exception as e:
|
|
||||||
return {"ok": False, "error": {"code": "AGENT_FAILED", "message": "%s: %s" % (type(e).__name__, e)}}
|
|
||||||
|
|
||||||
|
|
||||||
def answer(agent_dir, path):
|
def answer(agent_dir, path):
|
||||||
rid = path.stem
|
rid = path.stem
|
||||||
try:
|
try:
|
||||||
@@ -1234,7 +1225,12 @@ def answer(agent_dir, path):
|
|||||||
except OSError:
|
except OSError:
|
||||||
pass
|
pass
|
||||||
if req is not None:
|
if req is not None:
|
||||||
result = reply(agent_dir, req)
|
try:
|
||||||
|
result = dict(handle(agent_dir, req), ok=True)
|
||||||
|
except AgentError as e:
|
||||||
|
result = {"ok": False, "error": {"code": e.code, "message": str(e)}}
|
||||||
|
except Exception as e:
|
||||||
|
result = {"ok": False, "error": {"code": "AGENT_FAILED", "message": "%s: %s" % (type(e).__name__, e)}}
|
||||||
write_json(agent_dir / "resp" / (rid + ".json"), result)
|
write_json(agent_dir / "resp" / (rid + ".json"), result)
|
||||||
|
|
||||||
|
|
||||||
@@ -1261,13 +1257,6 @@ def serve(agent_dir, focus=True, poll=0.1):
|
|||||||
|
|
||||||
|
|
||||||
def main(argv):
|
def main(argv):
|
||||||
if argv and argv[0] == "--cdp-inspector":
|
|
||||||
if len(argv) != 4:
|
|
||||||
print("usage: droiddeck-agent --cdp-inspector <inspector url> <seconds> <expression>", file=sys.stderr)
|
|
||||||
return 2
|
|
||||||
print(json.dumps(reply(Path("/"), {"kind": "cdp", "inspector": argv[1], "timeout": argv[2],
|
|
||||||
"expression": argv[3], "commandLineApi": True})))
|
|
||||||
return 0
|
|
||||||
base = os.environ.get("DD_LAUNCH_DIR")
|
base = os.environ.get("DD_LAUNCH_DIR")
|
||||||
if not base:
|
if not base:
|
||||||
print("DD_LAUNCH_DIR is not set", file=sys.stderr)
|
print("DD_LAUNCH_DIR is not set", file=sys.stderr)
|
||||||
|
|||||||
@@ -79,7 +79,8 @@ AGENT_START = 90
|
|||||||
AGENT_HELPER = "agent.js"
|
AGENT_HELPER = "agent.js"
|
||||||
AGENT_RUNTIME = "agent-runtime"
|
AGENT_RUNTIME = "agent-runtime"
|
||||||
AGENT_LOG = "agent.log"
|
AGENT_LOG = "agent.log"
|
||||||
HEADLESS = "/usr/local/bin/droiddeck-headless"
|
AGENT_LOG_LIMIT = 4 << 20
|
||||||
|
HEADLESS = ["--backend", "headless", "-w", "640", "-h", "480"]
|
||||||
PRODUCT = re.compile(r"[a-z0-9_]{1,32}")
|
PRODUCT = re.compile(r"[a-z0-9_]{1,32}")
|
||||||
LOCALE = re.compile(r"[a-z]{2}[A-Z]{2}")
|
LOCALE = re.compile(r"[a-z]{2}[A-Z]{2}")
|
||||||
COUNTRY = re.compile(r"[A-Z]{3}")
|
COUNTRY = re.compile(r"[A-Z]{3}")
|
||||||
@@ -1415,23 +1416,33 @@ def agent_job(root, action, uid, product="", folder="", locale="enUS", country="
|
|||||||
windows = install_path(root, folder)
|
windows = install_path(root, folder)
|
||||||
emit("STATE", "starting")
|
emit("STATE", "starting")
|
||||||
base = os.path.join(CACHE, "agent-%s" % uid)
|
base = os.path.join(CACHE, "agent-%s" % uid)
|
||||||
os.makedirs(CACHE, exist_ok=True)
|
|
||||||
for suffix in (".json", ".game", ".form", ".error"):
|
for suffix in (".json", ".game", ".form", ".error"):
|
||||||
try:
|
try:
|
||||||
os.unlink(base + suffix)
|
os.unlink(base + suffix)
|
||||||
except OSError:
|
except OSError:
|
||||||
pass
|
pass
|
||||||
|
runtime = os.path.join(CACHE, AGENT_RUNTIME)
|
||||||
|
os.makedirs(runtime, mode=0o700, exist_ok=True)
|
||||||
env = agent_env()
|
env = agent_env()
|
||||||
cmd = [HEADLESS, os.path.join(CACHE, AGENT_RUNTIME), "--log", os.path.join(CACHE, AGENT_LOG), "--",
|
for name in ("DISPLAY", "WAYLAND_DISPLAY"):
|
||||||
os.path.abspath(sys.argv[0]), "agent-serve", action, uid, product or "-",
|
env.pop(name, None)
|
||||||
windows or "-", locale, country, region, "Z:" + base.replace("/", "\\")]
|
env["XDG_RUNTIME_DIR"] = runtime
|
||||||
|
cmd = ["gamescope"] + HEADLESS + ["--", os.path.abspath(sys.argv[0]), "agent-serve", action, uid, product or "-",
|
||||||
|
windows or "-", locale, country, region, "Z:" + base.replace("/", "\\")]
|
||||||
say("%s %s through the Agent: %s" % (action, uid, " ".join(cmd)))
|
say("%s %s through the Agent: %s" % (action, uid, " ".join(cmd)))
|
||||||
before = {pid for pid, _ in wine_processes(pfx)}
|
output = os.path.join(CACHE, AGENT_LOG)
|
||||||
try:
|
try:
|
||||||
child = subprocess.Popen(cmd, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, env=env)
|
if os.path.getsize(output) > AGENT_LOG_LIMIT:
|
||||||
except OSError as error:
|
os.replace(output, output + ".1")
|
||||||
emit("ERROR", "stopped gamescope: %s" % error)
|
except OSError:
|
||||||
return 1
|
pass
|
||||||
|
before = {pid for pid, _ in wine_processes(pfx)}
|
||||||
|
with open(output, "ab") as log:
|
||||||
|
try:
|
||||||
|
child = subprocess.Popen(cmd, stdin=subprocess.DEVNULL, stdout=log, stderr=log, env=env)
|
||||||
|
except OSError as error:
|
||||||
|
emit("ERROR", "stopped gamescope: %s" % error)
|
||||||
|
return 1
|
||||||
seen = None
|
seen = None
|
||||||
mark = None
|
mark = None
|
||||||
moved = time.monotonic()
|
moved = time.monotonic()
|
||||||
|
|||||||
@@ -5,17 +5,39 @@ self=${BASH_SOURCE[0]}
|
|||||||
proc=${DD_PROC:-/proc}
|
proc=${DD_PROC:-/proc}
|
||||||
state=${DD_CURSEFORGE_STATE:-${XDG_RUNTIME_DIR:-/tmp}/droiddeck-curseforge}
|
state=${DD_CURSEFORGE_STATE:-${XDG_RUNTIME_DIR:-/tmp}/droiddeck-curseforge}
|
||||||
runner=${DD_APPIMAGE_RUN:-${self%/*}/droiddeck-appimage-run}
|
runner=${DD_APPIMAGE_RUN:-${self%/*}/droiddeck-appimage-run}
|
||||||
headless=${DD_HEADLESS_RUN:-${self%/*}/droiddeck-headless}
|
|
||||||
wait_s=${DD_CURSEFORGE_WAIT:-60}
|
wait_s=${DD_CURSEFORGE_WAIT:-60}
|
||||||
cmd=${1:-}
|
cmd=${1:-}
|
||||||
dir=${2:-}
|
dir=${2:-}
|
||||||
flag=--inspect-publish-uid=stderr
|
flag=--inspect-publish-uid=stderr
|
||||||
case $cmd in start|stop) ;; *) echo "usage: droiddeck-curseforge start|stop <imported AppImage directory>" >&2; exit 2 ;; esac
|
case $cmd in start|hold|stop|display) ;; *) echo "usage: droiddeck-curseforge start|hold|stop|display <imported AppImage directory>" >&2; exit 2 ;; esac
|
||||||
if [ ! -d "$dir/app" ]; then
|
if [ "$cmd" != display ] && [ ! -d "$dir/app" ]; then
|
||||||
echo "droiddeck-curseforge: $dir is not an imported AppImage" >&2
|
echo "droiddeck-curseforge: $dir is not an imported AppImage" >&2
|
||||||
exit 2
|
exit 2
|
||||||
fi
|
fi
|
||||||
|
|
||||||
|
x_display() {
|
||||||
|
if [ -n "${DISPLAY:-}" ]; then
|
||||||
|
printf '%s\n%s\n' "$DISPLAY" "${XAUTHORITY:-}"
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
local p name a prev display auth
|
||||||
|
for p in "$proc"/[0-9]*; do
|
||||||
|
name=$(tr '\0' '\n' 2>/dev/null < "$p/cmdline" | head -n 1)
|
||||||
|
case ${name##*/} in Xwayland|Xorg|Xvfb) ;; *) continue ;; esac
|
||||||
|
display= auth= prev=
|
||||||
|
while IFS= read -r a; do
|
||||||
|
case $a in :[0-9]*) [ -z "$display" ] && display=$a ;; esac
|
||||||
|
[ "$prev" = -auth ] && auth=$a
|
||||||
|
prev=$a
|
||||||
|
done < <(tr '\0' '\n' 2>/dev/null < "$p/cmdline")
|
||||||
|
if [ -n "$display" ]; then
|
||||||
|
printf '%s\n%s\n' "$display" "$auth"
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
running() {
|
running() {
|
||||||
local p
|
local p
|
||||||
for p in "$proc"/[0-9]*; do
|
for p in "$proc"/[0-9]*; do
|
||||||
@@ -57,7 +79,7 @@ inspector() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
start() {
|
start() {
|
||||||
local url pid child=
|
local shown display auth url pid
|
||||||
lock || { echo "droiddeck-curseforge: cannot lock $state" >&2; return 5; }
|
lock || { echo "droiddeck-curseforge: cannot lock $state" >&2; return 5; }
|
||||||
if ! ours >/dev/null; then
|
if ! ours >/dev/null; then
|
||||||
if tracked >/dev/null || running; then
|
if tracked >/dev/null || running; then
|
||||||
@@ -65,18 +87,18 @@ start() {
|
|||||||
echo busy
|
echo busy
|
||||||
return 3
|
return 3
|
||||||
fi
|
fi
|
||||||
mv -f "$state/log" "$state/log.1" 2>/dev/null
|
shown=$(x_display) || { exec 9>&-; echo "no X display" >&2; return 4; }
|
||||||
env -u DBUS_SESSION_BUS_ADDRESS setsid "$headless" "$state/runtime" --log "$state/log" -- \
|
display=$(sed -n 1p <<<"$shown")
|
||||||
"$runner" "$dir" --minimized --inspect=127.0.0.1:0 "$flag" </dev/null >/dev/null 2>&1 9>&- &
|
auth=$(sed -n 2p <<<"$shown")
|
||||||
|
env -u DBUS_SESSION_BUS_ADDRESS -u WAYLAND_DISPLAY -u GAMESCOPE_WAYLAND_DISPLAY DISPLAY="$display" ${auth:+XAUTHORITY="$auth"} \
|
||||||
|
setsid "$runner" "$dir" --minimized --inspect=127.0.0.1:0 "$flag" </dev/null >"$state/log" 2>&1 9>&- &
|
||||||
pid=$!
|
pid=$!
|
||||||
child=$pid
|
|
||||||
printf '%s %s %s\n' "$pid" "$(started_at "$pid")" "$dir" > "$state/pid"
|
printf '%s %s %s\n' "$pid" "$(started_at "$pid")" "$dir" > "$state/pid"
|
||||||
fi
|
fi
|
||||||
exec 9>&-
|
exec 9>&-
|
||||||
for _ in $(seq 1 $((wait_s * 2))); do
|
for _ in $(seq 1 $((wait_s * 2))); do
|
||||||
if url=$(inspector); then
|
if url=$(inspector); then
|
||||||
echo "$url"
|
echo "$url"
|
||||||
hold "$child"
|
|
||||||
return 0
|
return 0
|
||||||
fi
|
fi
|
||||||
ours >/dev/null || break
|
ours >/dev/null || break
|
||||||
@@ -86,18 +108,6 @@ start() {
|
|||||||
return 5
|
return 5
|
||||||
}
|
}
|
||||||
|
|
||||||
hold() {
|
|
||||||
local pid
|
|
||||||
if [ -n "$1" ]; then
|
|
||||||
wait "$1"
|
|
||||||
return 0
|
|
||||||
fi
|
|
||||||
pid=$(ours) || return 0
|
|
||||||
while kill -0 "$pid" 2>/dev/null && [ "$(ours)" = "$pid" ]; do
|
|
||||||
sleep 1
|
|
||||||
done
|
|
||||||
}
|
|
||||||
|
|
||||||
stop() {
|
stop() {
|
||||||
local pid p
|
local pid p
|
||||||
lock || return 1
|
lock || return 1
|
||||||
@@ -108,7 +118,6 @@ stop() {
|
|||||||
sleep 0.5
|
sleep 0.5
|
||||||
done
|
done
|
||||||
kill -KILL -- "-$pid" 2>/dev/null
|
kill -KILL -- "-$pid" 2>/dev/null
|
||||||
kill -KILL "$pid" 2>/dev/null
|
|
||||||
for p in "$proc"/[0-9]*; do
|
for p in "$proc"/[0-9]*; do
|
||||||
tr '\0' '\n' 2>/dev/null < "$p/cmdline" | grep -qF -- "$dir/app/" && kill -KILL "${p##*/}" 2>/dev/null
|
tr '\0' '\n' 2>/dev/null < "$p/cmdline" | grep -qF -- "$dir/app/" && kill -KILL "${p##*/}" 2>/dev/null
|
||||||
done
|
done
|
||||||
@@ -118,10 +127,22 @@ stop() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
case $cmd in
|
case $cmd in
|
||||||
|
display)
|
||||||
|
x_display || exit 4
|
||||||
|
;;
|
||||||
start)
|
start)
|
||||||
start
|
start
|
||||||
exit $?
|
exit $?
|
||||||
;;
|
;;
|
||||||
|
hold)
|
||||||
|
start >/dev/null || exit $?
|
||||||
|
trap 'stop; exit 0' TERM INT HUP
|
||||||
|
while ours >/dev/null; do
|
||||||
|
sleep 1 &
|
||||||
|
wait $!
|
||||||
|
done
|
||||||
|
exit 0
|
||||||
|
;;
|
||||||
stop)
|
stop)
|
||||||
stop
|
stop
|
||||||
exit 0
|
exit 0
|
||||||
|
|||||||
@@ -819,6 +819,8 @@ def read_vdf(text):
|
|||||||
|
|
||||||
|
|
||||||
def run_keys(items, appid=""):
|
def run_keys(items, appid=""):
|
||||||
|
# (hasrunkey, value name, MinimumHasRunValue) of each "run process" entry; Steam runs the process unless the
|
||||||
|
# value is a DWORD of at least that minimum (1 when the script does not say)
|
||||||
appid = next((value for name, value in items if name.lower() == "appid" and isinstance(value, str)), appid)
|
appid = next((value for name, value in items if name.lower() == "appid" and isinstance(value, str)), appid)
|
||||||
found = set()
|
found = set()
|
||||||
for name, value in items:
|
for name, value in items:
|
||||||
@@ -827,30 +829,44 @@ def run_keys(items, appid=""):
|
|||||||
if any(isinstance(v, str) and re.fullmatch(r"process [0-9]+", n.lower()) for n, v in value):
|
if any(isinstance(v, str) and re.fullmatch(r"process [0-9]+", n.lower()) for n, v in value):
|
||||||
key = next((v for n, v in value if n.lower() == "hasrunkey" and isinstance(v, str)),
|
key = next((v for n, v in value if n.lower() == "hasrunkey" and isinstance(v, str)),
|
||||||
"HKEY_LOCAL_MACHINE\\Software\\Valve\\Steam\\Apps\\" + appid)
|
"HKEY_LOCAL_MACHINE\\Software\\Valve\\Steam\\Apps\\" + appid)
|
||||||
found.add((key.lower(), name.lower()))
|
minimum = next((v for n, v in value if n.lower() == "minimumhasrunvalue" and isinstance(v, str)), "1")
|
||||||
|
try:
|
||||||
|
minimum = int(minimum.strip(), 0)
|
||||||
|
except ValueError:
|
||||||
|
minimum = int(minimum.strip()) if minimum.strip().isdigit() else 1
|
||||||
|
found.add((key.lower(), name.lower(), minimum))
|
||||||
found |= run_keys(value, appid)
|
found |= run_keys(value, appid)
|
||||||
return found
|
return found
|
||||||
|
|
||||||
|
|
||||||
def registry_values(path):
|
def registry_values(path):
|
||||||
found, section = set(), None
|
# {(key, value name): DWORD, or None for a value of another type}
|
||||||
|
found, section = {}, None
|
||||||
with open(path, encoding="utf-8", errors="replace") as reg:
|
with open(path, encoding="utf-8", errors="replace") as reg:
|
||||||
for line in reg:
|
for line in reg:
|
||||||
if line.startswith("["):
|
if line.startswith("["):
|
||||||
section = line[1:line.find("]")].replace("\\\\", "\\").lower() if "]" in line else None
|
section = line[1:line.find("]")].replace("\\\\", "\\").lower() if "]" in line else None
|
||||||
elif section and line.startswith('"') and '"=' in line:
|
elif section and line.startswith('"') and '"=' in line:
|
||||||
found.add((section, line[1:line.index('"=')].replace("\\\\", "\\").lower()))
|
name = line[1:line.index('"=')].replace("\\\\", "\\").lower()
|
||||||
|
data = line[line.index('"=') + 2:].strip()
|
||||||
|
dword = None
|
||||||
|
if data.lower().startswith("dword:"):
|
||||||
|
try:
|
||||||
|
dword = int(data[6:], 16)
|
||||||
|
except ValueError:
|
||||||
|
pass
|
||||||
|
found[(section, name)] = dword
|
||||||
return found
|
return found
|
||||||
|
|
||||||
|
|
||||||
def has_run(key, value, values):
|
def has_run(key, value, values, minimum=1):
|
||||||
path = key[len("hkey_local_machine\\"):] if key.startswith("hkey_local_machine\\") else None
|
path = key[len("hkey_local_machine\\"):] if key.startswith("hkey_local_machine\\") else None
|
||||||
if path is None:
|
if path is None:
|
||||||
return False
|
return False
|
||||||
views = [path]
|
views = [path]
|
||||||
if path.startswith("software\\"):
|
if path.startswith("software\\"):
|
||||||
views.append("software\\wow6432node\\" + path[len("software\\"):])
|
views.append("software\\wow6432node\\" + path[len("software\\"):])
|
||||||
return any((view, value) in values for view in views)
|
return any(isinstance(values.get((view, value)), int) and values[(view, value)] >= minimum for view in views)
|
||||||
|
|
||||||
|
|
||||||
def scripts_digest(scripts):
|
def scripts_digest(scripts):
|
||||||
@@ -861,18 +877,49 @@ def scripts_digest(scripts):
|
|||||||
return digest.hexdigest()
|
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):
|
def install_scripts_done(scripts, env):
|
||||||
prefix = Path(env.get("STEAM_COMPAT_DATA_PATH", "/nonexistent")) / "pfx"
|
prefix = Path(env.get("STEAM_COMPAT_DATA_PATH", "/nonexistent")) / "pfx"
|
||||||
try:
|
try:
|
||||||
if (prefix / INSTALL_STAMP).read_text().strip() != scripts_digest(scripts):
|
keys, parsed = set(), []
|
||||||
return False
|
|
||||||
keys = set()
|
|
||||||
for path in scripts:
|
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")
|
values = registry_values(prefix / "system.reg")
|
||||||
except (OSError, ValueError):
|
except (OSError, ValueError):
|
||||||
return False
|
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, minimum) for key, value, minimum 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):
|
def record_install_scripts(digest, env):
|
||||||
|
|||||||
@@ -243,6 +243,7 @@ def run_patch(folder, appid, installer, game):
|
|||||||
previous = dict(os.environ)
|
previous = dict(os.environ)
|
||||||
try:
|
try:
|
||||||
os.environ.update(env)
|
os.environ.update(env)
|
||||||
|
os.environ["DD_STORE_PROTON"] = command
|
||||||
pfx = Path(prefix) / "pfx"
|
pfx = Path(prefix) / "pfx"
|
||||||
if not (pfx / "system.reg").is_file() or not (pfx / "drive_c/windows/system32/reg.exe").is_file():
|
if not (pfx / "system.reg").is_file() or not (pfx / "drive_c/windows/system32/reg.exe").is_file():
|
||||||
subprocess.run([command, "run", "wineboot.exe", "-u"], env=env, timeout=90, check=True)
|
subprocess.run([command, "run", "wineboot.exe", "-u"], env=env, timeout=90, check=True)
|
||||||
|
|||||||
@@ -1,24 +0,0 @@
|
|||||||
#!/bin/bash
|
|
||||||
set -u
|
|
||||||
runtime=${1:-}
|
|
||||||
shift
|
|
||||||
log=
|
|
||||||
if [ "${1:-}" = --log ]; then
|
|
||||||
log=${2:-}
|
|
||||||
shift 2
|
|
||||||
fi
|
|
||||||
if [ -z "$runtime" ] || [ "${1:-}" != -- ] || [ $# -lt 2 ]; then
|
|
||||||
echo "usage: droiddeck-headless <private runtime directory> [--log <file>] -- <command> [args...]" >&2
|
|
||||||
exit 2
|
|
||||||
fi
|
|
||||||
shift
|
|
||||||
umask 077
|
|
||||||
mkdir -p "$runtime" && chmod 700 "$runtime" || exit 1
|
|
||||||
if [ -n "$log" ]; then
|
|
||||||
size=$(stat -c %s "$log" 2>/dev/null || echo 0)
|
|
||||||
[ "$size" -gt "${DD_HEADLESS_LOG_LIMIT:-4194304}" ] && mv -f "$log" "$log.1"
|
|
||||||
exec >>"$log" 2>&1
|
|
||||||
fi
|
|
||||||
unset DISPLAY WAYLAND_DISPLAY GAMESCOPE_WAYLAND_DISPLAY XAUTHORITY
|
|
||||||
export XDG_RUNTIME_DIR=$runtime
|
|
||||||
exec gamescope --backend headless -w 640 -h 480 -- "$@"
|
|
||||||
@@ -13,8 +13,10 @@ RELEASES = "https://api.github.com/repos/%s/releases"
|
|||||||
SOURCES = {
|
SOURCES = {
|
||||||
"ge": ("GloriousEggroll/proton-ge-custom", re.compile(r"aarch64\.tar\.(gz|xz)$")),
|
"ge": ("GloriousEggroll/proton-ge-custom", re.compile(r"aarch64\.tar\.(gz|xz)$")),
|
||||||
"cachyos": ("CachyOS/proton-cachyos", re.compile(r"arm64\.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"
|
USER_AGENT = "droiddeck-proton-extra"
|
||||||
NEED_BYTES = 4 * 1024 * 1024 * 1024
|
NEED_BYTES = 4 * 1024 * 1024 * 1024
|
||||||
|
|
||||||
@@ -33,7 +35,7 @@ def fetch_json(url):
|
|||||||
def pick_asset(source):
|
def pick_asset(source):
|
||||||
repo, pattern = SOURCES[source]
|
repo, pattern = SOURCES[source]
|
||||||
for release in fetch_json(RELEASES % repo + "?per_page=15"):
|
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
|
continue
|
||||||
assets = {a["name"]: a["browser_download_url"] for a in release.get("assets", ())}
|
assets = {a["name"]: a["browser_download_url"] for a in release.get("assets", ())}
|
||||||
for name in sorted(assets):
|
for name in sorted(assets):
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
import base64
|
import base64
|
||||||
import binascii
|
import binascii
|
||||||
|
import functools
|
||||||
import json
|
import json
|
||||||
import os
|
import os
|
||||||
import re
|
import re
|
||||||
@@ -156,7 +157,27 @@ def ask(channel, request, timeout=TIMEOUT, claim=False):
|
|||||||
|
|
||||||
|
|
||||||
def windows_path(unix):
|
def windows_path(unix):
|
||||||
return "Z:" + unix.replace("/", "\\")
|
tool = bionic_tool(os.environ.get("DD_STORE_PROTON", ""))
|
||||||
|
return (tool and bionic_path(tool, unix)) or "Z:" + unix.replace("/", "\\")
|
||||||
|
|
||||||
|
|
||||||
|
def bionic_tool(proton):
|
||||||
|
if not proton or not os.environ.get("DDNATV_ROOT"):
|
||||||
|
return None
|
||||||
|
tool = Path(proton).parent
|
||||||
|
return str(tool / "proton") if (tool / "bionic" / "launch.sh").is_file() else None
|
||||||
|
|
||||||
|
|
||||||
|
@functools.lru_cache(maxsize=None)
|
||||||
|
def bionic_path(proton, unix):
|
||||||
|
# DroidDeck-Bionic's Wine sees Android's root on Z:, so a guest path is named by the Android file it maps to.
|
||||||
|
try:
|
||||||
|
result = subprocess.run([proton, "getcompatpath", unix], stdin=subprocess.DEVNULL, capture_output=True,
|
||||||
|
text=True, timeout=TIMEOUT)
|
||||||
|
except (OSError, subprocess.SubprocessError):
|
||||||
|
return None
|
||||||
|
path = result.stdout.strip()
|
||||||
|
return path if result.returncode == 0 and path[:3] == "Z:\\" else None
|
||||||
|
|
||||||
|
|
||||||
def reg_escape(value):
|
def reg_escape(value):
|
||||||
|
|||||||
@@ -187,6 +187,9 @@ dd_components() {
|
|||||||
# The selected system PowerVR runtime supplies DXVK at launch. Keep saved selections
|
# 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.
|
# for a later manual-driver session without rewriting this Proton's bundled files now.
|
||||||
[ "$comp" = dxvk ] && [ -n "${DROIDDECK_POWERVR_RUNTIME:-}" ] && continue
|
[ "$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")
|
cm_rows+=("$comp"$'\\t'"$rel"$'\\t'"$sum"$'\\t'"$src")
|
||||||
[ "$src" != "-" ] && [ -f "$base/$rel" ] && cm_files+=("$base/$rel")
|
[ "$src" != "-" ] && [ -f "$base/$rel" ] && cm_files+=("$base/$rel")
|
||||||
done <<< "$cm_selected"
|
done <<< "$cm_selected"
|
||||||
@@ -290,6 +293,23 @@ 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
|
||||||
|
echo "droiddeck-proton: DroidDeck-Bionic needs Run without proot, and no DroidDeck-Proton is installed to run this launch instead; turn on Run without proot or install DroidDeck-Proton" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
"""
|
||||||
|
|
||||||
DD_DRIVER_QUERY_SKIP = """
|
DD_DRIVER_QUERY_SKIP = """
|
||||||
case "$verb:${1##*/}:${STEAM_COMPAT_DATA_PATH%/}" in
|
case "$verb:${1##*/}:${STEAM_COMPAT_DATA_PATH%/}" in
|
||||||
run:d3ddriverquery64.exe:*/compatdata/0 | run:d3ddriverquery.exe:*/compatdata/0)
|
run:d3ddriverquery64.exe:*/compatdata/0 | run:d3ddriverquery.exe:*/compatdata/0)
|
||||||
@@ -487,7 +507,7 @@ dd_run ${DD_TASKSET:-} /usr/local/bin/droiddeck-game-env "$DD_STORE_PROTON" "$ve
|
|||||||
def extra_wrapper_sh(entry_point):
|
def extra_wrapper_sh(entry_point):
|
||||||
return (EXTRA_WRAPPER_SH % entry_point).replace(
|
return (EXTRA_WRAPPER_SH % entry_point).replace(
|
||||||
'here=$(dirname "$0")',
|
'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)
|
+ DD_IDTECH3_SETUP + DD_VACDIAG_SETUP + DD_COMPONENTS_SETUP + DD_LIBPATH_SETUP + DD_STORE_SETUP, 1)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -1413,8 +1413,7 @@ class AgentJobTest(Harness):
|
|||||||
self.assertEqual(code, 0)
|
self.assertEqual(code, 0)
|
||||||
self.assertTrue(os.path.isdir(folder))
|
self.assertTrue(os.path.isdir(folder))
|
||||||
cmd = self.started[0]
|
cmd = self.started[0]
|
||||||
self.assertEqual(cmd[:4], ["/usr/local/bin/droiddeck-headless", str(self.tmp / "cache" / "agent-runtime"), "--log",
|
self.assertEqual(cmd[:6], ["gamescope", "--backend", "headless", "-w", "640", "-h"])
|
||||||
str(self.tmp / "cache" / "agent.log")])
|
|
||||||
self.assertEqual(cmd[cmd.index("--") + 2:-1], ["agent-serve", "install", "gryphon", "gryphon", "Z:" + folder, "enUS", "USA", "US"])
|
self.assertEqual(cmd[cmd.index("--") + 2:-1], ["agent-serve", "install", "gryphon", "gryphon", "Z:" + folder, "enUS", "USA", "US"])
|
||||||
self.assertEqual([kind for kind, _ in self.lines], ["STATE", "PROGRESS", "DONE"])
|
self.assertEqual([kind for kind, _ in self.lines], ["STATE", "PROGRESS", "DONE"])
|
||||||
self.assertEqual(json.loads(self.lines[-1][1]), {"install_dir": "Z:" + folder, "exe": "WarcraftRumble.exe", "version": "16.1.2.119725"})
|
self.assertEqual(json.loads(self.lines[-1][1]), {"install_dir": "Z:" + folder, "exe": "WarcraftRumble.exe", "version": "16.1.2.119725"})
|
||||||
@@ -1642,6 +1641,16 @@ class AgentJobTest(Harness):
|
|||||||
path.write_bytes(json.dumps({"state": 1004}).encode("utf-8"))
|
path.write_bytes(json.dumps({"state": 1004}).encode("utf-8"))
|
||||||
self.assertEqual(BNET["read_status"](str(path)), {"state": 1004})
|
self.assertEqual(BNET["read_status"](str(path)), {"state": 1004})
|
||||||
|
|
||||||
|
def test_a_large_agent_log_is_rotated_before_a_job(self):
|
||||||
|
self.install()
|
||||||
|
os.makedirs(self.tmp / "cache")
|
||||||
|
log = self.tmp / "cache" / "agent.log"
|
||||||
|
log.write_bytes(b"x" * (BNET["AGENT_LOG_LIMIT"] + 1))
|
||||||
|
self.files = {".game": json.dumps({"installed": False})}
|
||||||
|
BNET["agent_job"](self.root, "uninstall", "gryphon", poll=0)
|
||||||
|
self.assertEqual((self.tmp / "cache" / "agent.log.1").stat().st_size, BNET["AGENT_LOG_LIMIT"] + 1)
|
||||||
|
self.assertEqual(log.stat().st_size, 0)
|
||||||
|
|
||||||
def test_it_queues_behind_another_battle_net_job(self):
|
def test_it_queues_behind_another_battle_net_job(self):
|
||||||
self.install()
|
self.install()
|
||||||
self.files = {".game": json.dumps({"installed": False})}
|
self.files = {".game": json.dumps({"installed": False})}
|
||||||
@@ -1672,11 +1681,13 @@ class AgentJobTest(Harness):
|
|||||||
self.assertEqual(self.lines[0], ("STATE", "waiting"))
|
self.assertEqual(self.lines[0], ("STATE", "waiting"))
|
||||||
self.assertEqual(self.lines[1], ("STATE", "starting"))
|
self.assertEqual(self.lines[1], ("STATE", "starting"))
|
||||||
|
|
||||||
def test_the_agent_keeps_the_display_gamescope_gives_it_and_launches_through_the_shared_headless_helper(self):
|
def test_gamescope_gets_no_display_but_the_agent_keeps_the_one_gamescope_gives_it(self):
|
||||||
self.install()
|
self.install()
|
||||||
|
os.environ.update(DISPLAY=":5", WAYLAND_DISPLAY="wayland-1")
|
||||||
self.files = {".game": json.dumps({"installed": False})}
|
self.files = {".game": json.dumps({"installed": False})}
|
||||||
BNET["agent_job"](self.root, "uninstall", "gryphon", poll=0)
|
BNET["agent_job"](self.root, "uninstall", "gryphon", poll=0)
|
||||||
self.assertEqual(self.started[0][0], BNET["HEADLESS"])
|
self.assertNotIn("DISPLAY", self.envs[0])
|
||||||
|
self.assertNotIn("WAYLAND_DISPLAY", self.envs[0])
|
||||||
self.assertEqual(self.envs[0]["PROTON_USE_XALIA"], "0")
|
self.assertEqual(self.envs[0]["PROTON_USE_XALIA"], "0")
|
||||||
os.environ["DISPLAY"] = ":0"
|
os.environ["DISPLAY"] = ":0"
|
||||||
self.assertEqual(BNET["agent_env"]()["DISPLAY"], ":0")
|
self.assertEqual(BNET["agent_env"]()["DISPLAY"], ":0")
|
||||||
|
|||||||
@@ -0,0 +1,180 @@
|
|||||||
|
import importlib.machinery
|
||||||
|
import importlib.util
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import shutil
|
||||||
|
import subprocess
|
||||||
|
import tempfile
|
||||||
|
import unittest
|
||||||
|
from pathlib import Path
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
TOOLS = Path(__file__).resolve().parents[1]
|
||||||
|
PROTON = TOOLS / 'bionic-runtime/tool/proton'
|
||||||
|
LAUNCH = TOOLS / 'bionic-runtime/tool/launch.sh'
|
||||||
|
BIN = TOOLS / 'linuxfs/overlay/usr/local/bin'
|
||||||
|
SHARE = TOOLS.parent / 'app/src/main/java/com/droiddeck/launcher/session/EnhancedSessionLogShare.kt'
|
||||||
|
ANDROID = '/data/user/0/com.droiddeck.launcher/files/linuxfs'
|
||||||
|
BINDS = '/storage/emulated/0/Games:/home/games|/storage/1234-5678/Steam:/mnt/sd'
|
||||||
|
|
||||||
|
|
||||||
|
def load(name):
|
||||||
|
loader = importlib.machinery.SourceFileLoader(name.replace('-', '_'), str(BIN / name))
|
||||||
|
spec = importlib.util.spec_from_loader(loader.name, loader)
|
||||||
|
module = importlib.util.module_from_spec(spec)
|
||||||
|
loader.exec_module(module)
|
||||||
|
return module
|
||||||
|
|
||||||
|
|
||||||
|
store = load('droiddeck-store-launch')
|
||||||
|
|
||||||
|
|
||||||
|
def proton_function(call, *args, **env):
|
||||||
|
text = PROTON.read_text()
|
||||||
|
functions = text[text.index('real() {'):text.index('\nhere=')]
|
||||||
|
env = dict(os.environ, DDNATV_ROOT=ANDROID, DDNATV_BINDS=BINDS, **env)
|
||||||
|
return subprocess.run(['bash', '-c', functions + '\n' + call, 'proton', *args], env=env,
|
||||||
|
capture_output=True, text=True, check=True).stdout.rstrip('\n')
|
||||||
|
|
||||||
|
|
||||||
|
def zpath(arg):
|
||||||
|
return proton_function('zpath "$1"', arg)
|
||||||
|
|
||||||
|
|
||||||
|
def session_logs(verb, **env):
|
||||||
|
return proton_function('verb=$1; session_logs', verb, **env)
|
||||||
|
|
||||||
|
|
||||||
|
class ToolArguments(unittest.TestCase):
|
||||||
|
def test_a_guest_path_names_its_android_file(self):
|
||||||
|
self.assertEqual('Z:\\data\\user\\0\\com.droiddeck.launcher\\files\\linuxfs\\usr\\local\\lib\\droiddeck-ubisoft\\droiddeck-upc.exe',
|
||||||
|
zpath('Z:\\usr\\local\\lib\\droiddeck-ubisoft\\droiddeck-upc.exe'))
|
||||||
|
|
||||||
|
def test_a_bound_folder_names_its_android_side(self):
|
||||||
|
self.assertEqual('Z:\\storage\\emulated\\0\\Games\\Brotato\\setup.exe', zpath('Z:\\home\\games\\Brotato\\setup.exe'))
|
||||||
|
self.assertEqual('Z:\\storage\\1234-5678\\Steam\\a.reg', zpath('z:/mnt/sd/a.reg'))
|
||||||
|
|
||||||
|
def test_a_switch_value_is_mapped(self):
|
||||||
|
self.assertEqual('/DIR=Z:\\storage\\emulated\\0\\Games\\Game', zpath('/DIR=Z:\\home\\games\\Game'))
|
||||||
|
|
||||||
|
def test_android_and_other_paths_stay(self):
|
||||||
|
for arg in ('Z:\\storage\\emulated\\0\\Download\\a.exe', 'Z:\\data\\user\\0\\com.droiddeck.launcher\\files\\linuxfs\\tmp\\a.bat',
|
||||||
|
'C:\\windows\\system32\\reg.exe', 'X:\\Brotato.exe', '-dx12', '-n', '-e', 'cmd.exe', '/d', ''):
|
||||||
|
self.assertEqual(arg, zpath(arg))
|
||||||
|
|
||||||
|
def test_wine_keeps_the_guest_root(self):
|
||||||
|
self.assertIn('DROIDDECK_GUEST_ROOT) ;;', LAUNCH.read_text())
|
||||||
|
|
||||||
|
|
||||||
|
class SessionLogs(unittest.TestCase):
|
||||||
|
SESSION = '/data/user/0/com.droiddeck.launcher/files/logs/2026-11-22-09-steam'
|
||||||
|
|
||||||
|
def test_a_game_launch_gets_a_folder_of_its_own_in_the_session(self):
|
||||||
|
folder = session_logs('waitforexitandrun', DD_DEBUG_DIR=self.SESSION + '/', SteamAppId='341940')
|
||||||
|
self.assertRegex(folder, '^' + re.escape(self.SESSION) + r'/games/[0-9]{4}-[0-9]{2}-[0-9]{2}-[0-9]{6}-bionic-341940$')
|
||||||
|
|
||||||
|
def test_the_folder_name_survives_share_logs(self):
|
||||||
|
pattern = re.search(r'Regex\("(\[0-9\]\{4\}-[^"]+)"\)', SHARE.read_text()).group(1).replace('\\\\', '\\')
|
||||||
|
name = session_logs('waitforexitandrun', DD_DEBUG_DIR=self.SESSION, SteamAppId='341940').rsplit('/', 1)[1]
|
||||||
|
self.assertRegex(name, '^(?:' + pattern + ')$')
|
||||||
|
self.assertIn('"droiddeck-bionic.log"', SHARE.read_text())
|
||||||
|
|
||||||
|
def test_detailed_graphics_logs_keep_the_game_log_folder(self):
|
||||||
|
self.assertEqual(ANDROID + '/tmp/logs/games/20261122-201105-ab12-341940',
|
||||||
|
session_logs('waitforexitandrun', DD_DEBUG_DIR=self.SESSION, PROTON_LOG_DIR='/tmp/logs/games/20261122-201105-ab12-341940'))
|
||||||
|
|
||||||
|
def test_other_verbs_and_sessions_without_a_folder_get_none(self):
|
||||||
|
self.assertEqual('', session_logs('run', DD_DEBUG_DIR=self.SESSION))
|
||||||
|
self.assertEqual('', session_logs('runinprefix', DD_DEBUG_DIR=self.SESSION))
|
||||||
|
env = dict(os.environ)
|
||||||
|
env.pop('DD_DEBUG_DIR', None)
|
||||||
|
with patch.dict(os.environ, env, clear=True):
|
||||||
|
self.assertEqual('', session_logs('waitforexitandrun'))
|
||||||
|
|
||||||
|
|
||||||
|
class LaunchLog(unittest.TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
self.tmp = tempfile.TemporaryDirectory()
|
||||||
|
self.addCleanup(self.tmp.cleanup)
|
||||||
|
self.root = Path(self.tmp.name)
|
||||||
|
self.compat = self.root / 'compatdata/341940'
|
||||||
|
self.logs = self.root / 'session/games/2026-11-22-201105-bionic-341940'
|
||||||
|
|
||||||
|
def run_block(self, verb, logs=''):
|
||||||
|
text = LAUNCH.read_text()
|
||||||
|
block = text[text.index('mkdir -p "$COMPAT"'):text.index('exec >> "$LOG" 2>&1')]
|
||||||
|
script = 'set -e\n' + block + 'echo "line from %s" >> "$LOG"\n' % verb
|
||||||
|
subprocess.run(['sh', '-c', script], check=True, env=dict(os.environ, COMPAT=str(self.compat), LOGS=str(logs), verb=verb))
|
||||||
|
return self.compat / 'droiddeck-bionic.log'
|
||||||
|
|
||||||
|
def test_a_game_log_lives_in_the_session_folder_with_one_name(self):
|
||||||
|
self.compat.mkdir(parents=True)
|
||||||
|
(self.compat / 'droiddeck-bionic.log').write_text('previous launch\n')
|
||||||
|
log = self.run_block('waitforexitandrun', self.logs)
|
||||||
|
shared = self.logs / 'droiddeck-bionic.log'
|
||||||
|
self.assertTrue(log.is_symlink())
|
||||||
|
self.assertEqual(shared, Path(os.readlink(log)))
|
||||||
|
self.assertEqual('line from waitforexitandrun\n', shared.read_text())
|
||||||
|
self.assertEqual(1, shared.stat().st_nlink)
|
||||||
|
self.assertEqual('previous launch\n', (self.compat / 'droiddeck-bionic.log.1').read_text())
|
||||||
|
|
||||||
|
def test_a_removed_session_folder_leaves_no_dangling_log(self):
|
||||||
|
self.run_block('waitforexitandrun', self.logs)
|
||||||
|
shutil.rmtree(self.root / 'session')
|
||||||
|
log = self.run_block('runinprefix')
|
||||||
|
self.assertFalse(log.is_symlink())
|
||||||
|
self.assertEqual('line from runinprefix\n', log.read_text())
|
||||||
|
|
||||||
|
def test_without_a_session_folder_the_log_stays_in_the_prefix(self):
|
||||||
|
log = self.run_block('run')
|
||||||
|
self.assertFalse(log.is_symlink())
|
||||||
|
self.assertEqual('line from run\n', log.read_text())
|
||||||
|
|
||||||
|
def test_graphics_logs_follow_the_launch(self):
|
||||||
|
text = LAUNCH.read_text()
|
||||||
|
self.assertIn('DXVK_LOG_PATH|VKD3D_LOG_FILE|MESA_LOG_FILE) ;;', text)
|
||||||
|
self.assertIn('DXVK_LOG_PATH=${DXVK_LOG_PATH:-$COMPAT}', text)
|
||||||
|
|
||||||
|
|
||||||
|
class StorePaths(unittest.TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
self.tmp = tempfile.TemporaryDirectory()
|
||||||
|
self.addCleanup(self.tmp.cleanup)
|
||||||
|
self.tool = Path(self.tmp.name) / 'compatibilitytools.d/DroidDeck-Bionic-12.8-r41-Proton'
|
||||||
|
(self.tool / 'bionic').mkdir(parents=True)
|
||||||
|
shutil.copy(PROTON, self.tool / 'proton')
|
||||||
|
(self.tool / 'proton').chmod(0o755)
|
||||||
|
(self.tool / 'bionic/launch.sh').write_text('')
|
||||||
|
|
||||||
|
def env(self, **extra):
|
||||||
|
values = {'DD_STORE_PROTON': str(self.tool / 'proton'), 'DDNATV_ROOT': ANDROID, 'DDNATV_BINDS': BINDS}
|
||||||
|
values.update(extra)
|
||||||
|
return patch.dict(os.environ, values)
|
||||||
|
|
||||||
|
def test_a_bionic_game_gets_android_paths(self):
|
||||||
|
with self.env():
|
||||||
|
self.assertEqual('Z:\\data\\user\\0\\com.droiddeck.launcher\\files\\linuxfs\\root\\.cache\\droiddeck-ubisoft\\bridge-274',
|
||||||
|
store.windows_path('/root/.cache/droiddeck-ubisoft/bridge-274'))
|
||||||
|
self.assertEqual('Z:\\storage\\emulated\\0\\Games\\Watch_Dogs\\bin\\Watch_Dogs.exe',
|
||||||
|
store.windows_path('/home/games/Watch_Dogs/bin/Watch_Dogs.exe'))
|
||||||
|
|
||||||
|
def test_the_wrapper_names_the_same_tool(self):
|
||||||
|
with self.env(DD_STORE_PROTON=str(self.tool / 'droiddeck-proton-wrap')):
|
||||||
|
self.assertEqual('Z:\\storage\\emulated\\0\\Games\\a.reg', store.windows_path('/home/games/a.reg'))
|
||||||
|
|
||||||
|
def test_other_tools_keep_guest_paths(self):
|
||||||
|
(self.tool / 'bionic/launch.sh').unlink()
|
||||||
|
with self.env():
|
||||||
|
self.assertEqual('Z:\\home\\games\\a.reg', store.windows_path('/home/games/a.reg'))
|
||||||
|
with patch.dict(os.environ, {'DD_STORE_PROTON': str(self.tool / 'proton')}):
|
||||||
|
os.environ.pop('DDNATV_ROOT', None)
|
||||||
|
self.assertEqual('Z:\\home\\games\\b.reg', store.windows_path('/home/games/b.reg'))
|
||||||
|
|
||||||
|
def test_a_failing_tool_keeps_the_guest_path(self):
|
||||||
|
(self.tool / 'proton').write_text('#!/bin/sh\nexit 1\n')
|
||||||
|
with self.env():
|
||||||
|
self.assertEqual('Z:\\home\\games\\c.reg', store.windows_path('/home/games/c.reg'))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
unittest.main()
|
||||||
@@ -1,67 +1,17 @@
|
|||||||
import os
|
import os
|
||||||
import shlex
|
import shlex
|
||||||
import shutil
|
import shutil
|
||||||
|
import signal
|
||||||
import subprocess
|
import subprocess
|
||||||
import tempfile
|
import tempfile
|
||||||
import time
|
import time
|
||||||
import unittest
|
import unittest
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
BIN = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin"
|
HELPER = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-curseforge"
|
||||||
HELPER = BIN / "droiddeck-curseforge"
|
|
||||||
HEADLESS = BIN / "droiddeck-headless"
|
|
||||||
URL = "ws://127.0.0.1:43117/0f8fad5b-d9cb-469f-a165-70867728950e"
|
URL = "ws://127.0.0.1:43117/0f8fad5b-d9cb-469f-a165-70867728950e"
|
||||||
|
|
||||||
|
|
||||||
class HeadlessTest(unittest.TestCase):
|
|
||||||
def setUp(self):
|
|
||||||
self.tmp = Path(tempfile.mkdtemp())
|
|
||||||
self.addCleanup(shutil.rmtree, self.tmp, True)
|
|
||||||
self.bin = self.tmp / "bin"
|
|
||||||
self.bin.mkdir()
|
|
||||||
self.seen = self.tmp / "seen"
|
|
||||||
gamescope = self.bin / "gamescope"
|
|
||||||
gamescope.write_text(
|
|
||||||
"#!/bin/bash\n"
|
|
||||||
"printf '%%s\\n' \"DISPLAY=${DISPLAY-}\" \"WAYLAND=${WAYLAND_DISPLAY-}\" \"GAMESCOPE=${GAMESCOPE_WAYLAND_DISPLAY-}\" "
|
|
||||||
"\"XAUTH=${XAUTHORITY-}\" \"RUNTIME=$XDG_RUNTIME_DIR\" \"$@\" > %s\n"
|
|
||||||
"echo logged-by-gamescope\n" % shlex.quote(str(self.seen)))
|
|
||||||
gamescope.chmod(0o755)
|
|
||||||
|
|
||||||
def env(self, extra=None):
|
|
||||||
base = dict(os.environ, PATH="%s:%s" % (self.bin, os.environ["PATH"]), DISPLAY=":0", WAYLAND_DISPLAY="wayland-0",
|
|
||||||
GAMESCOPE_WAYLAND_DISPLAY="gamescope-0", XAUTHORITY="/run/xauth")
|
|
||||||
base.update(extra or {})
|
|
||||||
return base
|
|
||||||
|
|
||||||
def run_headless(self, *args, env=None):
|
|
||||||
return subprocess.run(["bash", str(HEADLESS), *args], env=self.env(env), capture_output=True, text=True, timeout=30)
|
|
||||||
|
|
||||||
def test_it_runs_the_command_in_headless_gamescope_with_a_private_runtime_and_no_session_display(self):
|
|
||||||
runtime = self.tmp / "runtime"
|
|
||||||
out = self.run_headless(str(runtime), "--", "prog", "arg one")
|
|
||||||
self.assertEqual(0, out.returncode, out.stderr)
|
|
||||||
self.assertEqual(["DISPLAY=", "WAYLAND=", "GAMESCOPE=", "XAUTH=", "RUNTIME=%s" % runtime, "--backend", "headless",
|
|
||||||
"-w", "640", "-h", "480", "--", "prog", "arg one"], self.seen.read_text().splitlines())
|
|
||||||
self.assertEqual(0o700, runtime.stat().st_mode & 0o777)
|
|
||||||
|
|
||||||
def test_output_goes_to_the_log_which_rotates_when_large(self):
|
|
||||||
log = self.tmp / "agent.log"
|
|
||||||
log.write_bytes(b"x" * 100)
|
|
||||||
self.assertEqual(0, self.run_headless(str(self.tmp / "r"), "--log", str(log), "--", "prog").returncode)
|
|
||||||
self.assertTrue(log.read_text().endswith("logged-by-gamescope\n"))
|
|
||||||
self.assertEqual(100, log.stat().st_size - len("logged-by-gamescope\n"))
|
|
||||||
self.assertFalse((self.tmp / "agent.log.1").exists())
|
|
||||||
self.run_headless(str(self.tmp / "r"), "--log", str(log), "--", "prog", env={"DD_HEADLESS_LOG_LIMIT": "50"})
|
|
||||||
self.assertEqual(100 + len("logged-by-gamescope\n"), (self.tmp / "agent.log.1").stat().st_size)
|
|
||||||
self.assertEqual("logged-by-gamescope\n", log.read_text())
|
|
||||||
|
|
||||||
def test_bad_arguments_are_refused(self):
|
|
||||||
self.assertEqual(2, self.run_headless(str(self.tmp / "r"), "prog").returncode)
|
|
||||||
self.assertEqual(2, self.run_headless(str(self.tmp / "r"), "--").returncode)
|
|
||||||
self.assertEqual(2, self.run_headless().returncode)
|
|
||||||
|
|
||||||
|
|
||||||
class CurseForgeHelperTest(unittest.TestCase):
|
class CurseForgeHelperTest(unittest.TestCase):
|
||||||
def setUp(self):
|
def setUp(self):
|
||||||
self.tmp = Path(tempfile.mkdtemp())
|
self.tmp = Path(tempfile.mkdtemp())
|
||||||
@@ -71,23 +21,18 @@ class CurseForgeHelperTest(unittest.TestCase):
|
|||||||
self.dir = self.tmp / "curseforge"
|
self.dir = self.tmp / "curseforge"
|
||||||
(self.dir / "app").mkdir(parents=True)
|
(self.dir / "app").mkdir(parents=True)
|
||||||
self.state = self.tmp / "state"
|
self.state = self.tmp / "state"
|
||||||
self.bin = self.tmp / "bin"
|
|
||||||
self.bin.mkdir()
|
|
||||||
self.runner = self.tmp / "runner"
|
self.runner = self.tmp / "runner"
|
||||||
self.seen = self.tmp / "seen"
|
self.seen = self.tmp / "seen"
|
||||||
self.runner.write_text(
|
self.runner.write_text(
|
||||||
"#!/bin/bash\n"
|
"#!/bin/bash\n"
|
||||||
"printf '%%s\\n' \"DISPLAY=${DISPLAY-}\" \"WAYLAND=${WAYLAND_DISPLAY-}\" \"DBUS=${DBUS_SESSION_BUS_ADDRESS-}\" "
|
"printf '%%s\\n' \"DISPLAY=$DISPLAY\" \"XAUTHORITY=${XAUTHORITY-}\" \"WAYLAND=${WAYLAND_DISPLAY-}\" "
|
||||||
"\"RUNTIME=$XDG_RUNTIME_DIR\" \"$@\" > %s\n"
|
"\"DBUS=${DBUS_SESSION_BUS_ADDRESS-}\" \"$@\" > %s\n"
|
||||||
"mkdir -p %s/$$ && printf '%%s\\0' bash \"$0\" \"$@\" > %s/$$/cmdline\n"
|
"mkdir -p %s/$$ && printf '%%s\\0' bash \"$0\" \"$@\" > %s/$$/cmdline\n"
|
||||||
"echo 'Debugger listening on %s' >&2\n"
|
"echo 'Debugger listening on %s'\n"
|
||||||
"echo 'For help, see: https://nodejs.org/en/docs/inspector' >&2\n"
|
"echo 'For help, see: https://nodejs.org/en/docs/inspector'\n"
|
||||||
"sleep 60\n"
|
"exec sleep 60\n"
|
||||||
% (shlex.quote(str(self.seen)), shlex.quote(str(self.proc)), shlex.quote(str(self.proc)), URL))
|
% (shlex.quote(str(self.seen)), shlex.quote(str(self.proc)), shlex.quote(str(self.proc)), URL))
|
||||||
self.runner.chmod(0o755)
|
self.runner.chmod(0o755)
|
||||||
gamescope = self.bin / "gamescope"
|
|
||||||
gamescope.write_text('#!/bin/bash\nwhile [ "$1" != -- ]; do shift; done\nshift\n"$@"\n')
|
|
||||||
gamescope.chmod(0o755)
|
|
||||||
|
|
||||||
def fake(self, pid, *argv):
|
def fake(self, pid, *argv):
|
||||||
d = self.proc / str(pid)
|
d = self.proc / str(pid)
|
||||||
@@ -95,27 +40,15 @@ class CurseForgeHelperTest(unittest.TestCase):
|
|||||||
(d / "cmdline").write_bytes(b"".join(a.encode() + b"\0" for a in argv))
|
(d / "cmdline").write_bytes(b"".join(a.encode() + b"\0" for a in argv))
|
||||||
|
|
||||||
def env(self, extra=None):
|
def env(self, extra=None):
|
||||||
base = dict(os.environ, PATH="%s:%s" % (self.bin, os.environ["PATH"]), DD_PROC=str(self.proc),
|
base = {k: v for k, v in os.environ.items() if k not in ("DISPLAY", "XAUTHORITY")}
|
||||||
DD_CURSEFORGE_STATE=str(self.state), DD_APPIMAGE_RUN=str(self.runner), DD_HEADLESS_RUN=str(HEADLESS),
|
base.update(DD_PROC=str(self.proc), DD_CURSEFORGE_STATE=str(self.state), DD_APPIMAGE_RUN=str(self.runner),
|
||||||
DD_CURSEFORGE_WAIT="10", DISPLAY=":0", WAYLAND_DISPLAY="wayland-0", XDG_RUNTIME_DIR="/run/user/session",
|
DD_CURSEFORGE_WAIT="10", WAYLAND_DISPLAY="wayland-0", DBUS_SESSION_BUS_ADDRESS="unix:path=/x")
|
||||||
DBUS_SESSION_BUS_ADDRESS="unix:path=/x")
|
|
||||||
base.update(extra or {})
|
base.update(extra or {})
|
||||||
return base
|
return base
|
||||||
|
|
||||||
def run_helper(self, *args, env=None):
|
def run_helper(self, *args, env=None):
|
||||||
return subprocess.run(["bash", str(HELPER), *args], env=self.env(env), capture_output=True, text=True, timeout=60)
|
return subprocess.run(["bash", str(HELPER), *args], env=self.env(env), capture_output=True, text=True, timeout=60)
|
||||||
|
|
||||||
def launch(self, directory=None):
|
|
||||||
holder = subprocess.Popen(["bash", str(HELPER), "start", str(directory or self.dir)], env=self.env(),
|
|
||||||
stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
|
|
||||||
self.addCleanup(self.finish, holder)
|
|
||||||
return holder, holder.stdout.readline().strip()
|
|
||||||
|
|
||||||
def finish(self, holder):
|
|
||||||
if holder.poll() is None:
|
|
||||||
holder.kill()
|
|
||||||
holder.communicate()
|
|
||||||
|
|
||||||
def stop(self):
|
def stop(self):
|
||||||
self.run_helper("stop", str(self.dir))
|
self.run_helper("stop", str(self.dir))
|
||||||
|
|
||||||
@@ -131,56 +64,86 @@ class CurseForgeHelperTest(unittest.TestCase):
|
|||||||
time.sleep(0.1)
|
time.sleep(0.1)
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
def test_the_desktop_x_display_is_found_from_xwayland(self):
|
||||||
|
self.fake(40, "/usr/bin/kwin_wayland", ":9")
|
||||||
|
self.fake(41, "/usr/bin/Xwayland", ":0", "-rootless", "-auth", "/run/droiddeck/xauth_abc", "-listenfd", "5")
|
||||||
|
out = self.run_helper("display", "")
|
||||||
|
self.assertEqual(0, out.returncode, out.stderr)
|
||||||
|
self.assertEqual([":0", "/run/droiddeck/xauth_abc"], out.stdout.splitlines())
|
||||||
|
|
||||||
|
def test_the_session_display_wins(self):
|
||||||
|
self.fake(41, "/usr/bin/Xwayland", ":3")
|
||||||
|
out = self.run_helper("display", "", env={"DISPLAY": ":0"})
|
||||||
|
self.assertEqual(":0", out.stdout.splitlines()[0])
|
||||||
|
|
||||||
|
def test_no_display_is_reported(self):
|
||||||
|
out = self.run_helper("start", str(self.dir))
|
||||||
|
self.assertEqual(4, out.returncode)
|
||||||
|
|
||||||
def test_a_running_instance_without_the_inspector_is_busy(self):
|
def test_a_running_instance_without_the_inspector_is_busy(self):
|
||||||
self.fake(50, "/usr/bin/FEX", str(self.dir) + "/app/curseforge", "--no-sandbox")
|
self.fake(50, "/usr/bin/FEX", str(self.dir) + "/app/curseforge", "--no-sandbox")
|
||||||
out = self.run_helper("start", str(self.dir))
|
out = self.run_helper("start", str(self.dir), env={"DISPLAY": ":0"})
|
||||||
self.assertEqual(3, out.returncode)
|
self.assertEqual(3, out.returncode)
|
||||||
self.assertEqual("busy", out.stdout.strip())
|
self.assertEqual("busy", out.stdout.strip())
|
||||||
self.stop()
|
self.stop()
|
||||||
self.assertTrue((self.proc / "50").exists())
|
self.assertTrue((self.proc / "50").exists())
|
||||||
|
|
||||||
def test_start_runs_the_app_in_headless_gamescope_with_a_secret_inspector_and_no_session_display(self):
|
def test_start_uses_a_random_port_and_a_secret_inspector_url_kept_private(self):
|
||||||
holder, url = self.launch()
|
self.fake(41, "/usr/bin/Xwayland", ":0", "-auth", "/run/droiddeck/xauth_abc")
|
||||||
|
out = self.run_helper("start", str(self.dir))
|
||||||
self.addCleanup(self.stop)
|
self.addCleanup(self.stop)
|
||||||
self.assertEqual(URL, url)
|
self.assertEqual(0, out.returncode, out.stderr)
|
||||||
|
self.assertEqual(URL, out.stdout.strip())
|
||||||
seen = self.seen.read_text().splitlines()
|
seen = self.seen.read_text().splitlines()
|
||||||
self.assertEqual(["DISPLAY=", "WAYLAND=", "DBUS=", "RUNTIME=%s/runtime" % self.state, str(self.dir), "--minimized",
|
self.assertEqual(["DISPLAY=:0", "XAUTHORITY=/run/droiddeck/xauth_abc", "WAYLAND=", "DBUS=", str(self.dir),
|
||||||
"--inspect=127.0.0.1:0", "--inspect-publish-uid=stderr"], seen)
|
"--minimized", "--inspect=127.0.0.1:0", "--inspect-publish-uid=stderr"], seen)
|
||||||
self.assertEqual(0o700, self.state.stat().st_mode & 0o777)
|
self.assertEqual(0o700, self.state.stat().st_mode & 0o777)
|
||||||
self.assertEqual(0o700, (self.state / "runtime").stat().st_mode & 0o777)
|
|
||||||
self.assertEqual(0o600, (self.state / "log").stat().st_mode & 0o777)
|
self.assertEqual(0o600, (self.state / "log").stat().st_mode & 0o777)
|
||||||
_, again = self.launch()
|
again = self.run_helper("start", str(self.dir))
|
||||||
self.assertEqual(URL, again)
|
self.assertEqual(URL, again.stdout.strip())
|
||||||
|
pid = self.pid()
|
||||||
def test_start_holds_the_app_until_it_is_stopped(self):
|
|
||||||
holder, url = self.launch()
|
|
||||||
self.assertEqual(URL, url)
|
|
||||||
app = self.pid()
|
|
||||||
time.sleep(1)
|
|
||||||
self.assertIsNone(holder.poll())
|
|
||||||
os.kill(app, 0)
|
|
||||||
self.stop()
|
|
||||||
self.assertEqual(0, holder.wait(timeout=30))
|
|
||||||
self.assertTrue(self.gone(app), "the app is still running")
|
|
||||||
|
|
||||||
def test_stop_ends_the_app_and_the_gamescope_it_ran_in(self):
|
|
||||||
(self.bin / "gamescope").write_text('#!/bin/bash\nwhile [ "$1" != -- ]; do shift; done\nshift\n"$@" &\nwait\n')
|
|
||||||
self.assertEqual(URL, self.launch()[1])
|
|
||||||
gamescope = self.pid()
|
|
||||||
app = int(next(self.proc.iterdir()).name)
|
|
||||||
self.assertNotEqual(gamescope, app)
|
|
||||||
os.kill(app, 0)
|
|
||||||
self.stop()
|
self.stop()
|
||||||
self.assertFalse((self.state / "pid").exists())
|
self.assertFalse((self.state / "pid").exists())
|
||||||
self.assertTrue(self.gone(gamescope), "gamescope is still running")
|
self.assertTrue(self.gone(pid), "the started instance is still running")
|
||||||
self.assertTrue(self.gone(app), "the app is still running")
|
|
||||||
|
|
||||||
def test_a_launch_for_another_directory_is_busy_and_left_alone(self):
|
def test_hold_keeps_the_app_until_it_is_signalled(self):
|
||||||
|
held = subprocess.Popen(["bash", str(HELPER), "hold", str(self.dir)], env=self.env({"DISPLAY": ":0"}),
|
||||||
|
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||||
|
self.addCleanup(self.end, held)
|
||||||
|
for _ in range(100):
|
||||||
|
if (self.state / "pid").exists() and self.seen.exists():
|
||||||
|
break
|
||||||
|
time.sleep(0.1)
|
||||||
|
pid = self.pid()
|
||||||
|
time.sleep(1)
|
||||||
|
self.assertIsNone(held.poll())
|
||||||
|
held.send_signal(signal.SIGTERM)
|
||||||
|
self.assertEqual(0, held.wait(timeout=30))
|
||||||
|
self.assertTrue(self.gone(pid), "hold left the app running")
|
||||||
|
self.assertFalse((self.state / "pid").exists())
|
||||||
|
|
||||||
|
def end(self, held):
|
||||||
|
if held.poll() is None:
|
||||||
|
held.send_signal(signal.SIGTERM)
|
||||||
|
try:
|
||||||
|
held.wait(timeout=15)
|
||||||
|
except subprocess.TimeoutExpired:
|
||||||
|
held.kill()
|
||||||
|
held.wait()
|
||||||
|
record = self.state / "pid"
|
||||||
|
if record.exists():
|
||||||
|
try:
|
||||||
|
os.killpg(self.pid(), signal.SIGKILL)
|
||||||
|
except (ProcessLookupError, PermissionError):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def test_a_launch_for_another_directory_is_busy(self):
|
||||||
other = self.tmp / "other"
|
other = self.tmp / "other"
|
||||||
(other / "app").mkdir(parents=True)
|
(other / "app").mkdir(parents=True)
|
||||||
|
first = self.run_helper("start", str(self.dir), env={"DISPLAY": ":0"})
|
||||||
self.addCleanup(self.stop)
|
self.addCleanup(self.stop)
|
||||||
self.assertEqual(URL, self.launch()[1])
|
self.assertEqual(0, first.returncode, first.stderr)
|
||||||
out = self.run_helper("start", str(other))
|
out = self.run_helper("start", str(other), env={"DISPLAY": ":0"})
|
||||||
self.assertEqual(3, out.returncode)
|
self.assertEqual(3, out.returncode)
|
||||||
self.assertEqual("busy", out.stdout.strip())
|
self.assertEqual("busy", out.stdout.strip())
|
||||||
pid = self.pid()
|
pid = self.pid()
|
||||||
@@ -188,25 +151,22 @@ class CurseForgeHelperTest(unittest.TestCase):
|
|||||||
self.assertEqual(pid, self.pid())
|
self.assertEqual(pid, self.pid())
|
||||||
os.kill(pid, 0)
|
os.kill(pid, 0)
|
||||||
|
|
||||||
def test_each_launch_starts_a_fresh_log(self):
|
def test_hold_ends_when_the_app_exits(self):
|
||||||
first, _ = self.launch()
|
proc = shlex.quote(str(self.proc))
|
||||||
self.stop()
|
self.runner.write_text("#!/bin/bash\nmkdir -p %s/$$ && printf '%%s\\0' bash \"$0\" \"$@\" > %s/$$/cmdline\n"
|
||||||
first.wait(timeout=30)
|
"echo 'Debugger listening on %s'\nsleep 2\nrm -r %s/$$\n" % (proc, proc, URL, proc))
|
||||||
self.addCleanup(self.stop)
|
out = subprocess.run(["bash", str(HELPER), "hold", str(self.dir)], env=self.env({"DISPLAY": ":0"}),
|
||||||
self.assertEqual(URL, self.launch()[1])
|
capture_output=True, text=True, timeout=60)
|
||||||
self.assertEqual(1, (self.state / "log").read_text().count("Debugger listening"))
|
self.assertEqual(0, out.returncode, out.stderr)
|
||||||
self.assertTrue((self.state / "log.1").exists())
|
|
||||||
|
|
||||||
def test_stop_without_a_launch_is_quiet(self):
|
def test_stop_without_a_launch_is_quiet(self):
|
||||||
out = self.run_helper("stop", str(self.dir))
|
out = self.run_helper("stop", str(self.dir))
|
||||||
self.assertEqual(0, out.returncode)
|
self.assertEqual(0, out.returncode)
|
||||||
self.assertEqual("", out.stderr)
|
self.assertEqual("", out.stderr)
|
||||||
self.assertEqual("", out.stdout)
|
|
||||||
|
|
||||||
def test_bad_arguments_are_refused(self):
|
def test_bad_arguments_are_refused(self):
|
||||||
self.assertEqual(2, self.run_helper("start", str(self.tmp / "missing")).returncode)
|
self.assertEqual(2, self.run_helper("start", str(self.tmp / "missing")).returncode)
|
||||||
self.assertEqual(2, self.run_helper("launch", str(self.dir)).returncode)
|
self.assertEqual(2, self.run_helper("launch", str(self.dir)).returncode)
|
||||||
self.assertEqual(2, self.run_helper("hold", str(self.dir)).returncode)
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
|||||||
@@ -348,28 +348,6 @@ class AgentTest(unittest.TestCase):
|
|||||||
self.assertEqual("INVALID_TARGET", caught.exception.code)
|
self.assertEqual("INVALID_TARGET", caught.exception.code)
|
||||||
connect.assert_not_called()
|
connect.assert_not_called()
|
||||||
|
|
||||||
def test_one_shot_inspector_eval_prints_the_session_answer_without_a_launch_dir(self):
|
|
||||||
import contextlib
|
|
||||||
import io
|
|
||||||
url = "ws://127.0.0.1:43117/0f8fad5b-d9cb-469f-a165-70867728950e"
|
|
||||||
seen = {}
|
|
||||||
|
|
||||||
def evaluate(agent_dir, expression, target=None, await_promise=True, timeout=15, inspector=None, command_line_api=False):
|
|
||||||
seen.update(expression=expression, timeout=timeout, inspector=inspector, api=command_line_api)
|
|
||||||
return {"target": "inspector", "type": "string", "value": "ok", "description": None}
|
|
||||||
|
|
||||||
out = io.StringIO()
|
|
||||||
with patch.dict(os.environ, {}, clear=False), patch.object(agent, "cdp_eval", evaluate), contextlib.redirect_stdout(out):
|
|
||||||
os.environ.pop("DD_LAUNCH_DIR", None)
|
|
||||||
self.assertEqual(0, agent.main(["--cdp-inspector", url, "12.5", "1 + 1"]))
|
|
||||||
self.assertEqual({"target": "inspector", "type": "string", "value": "ok", "description": None, "ok": True}, json.loads(out.getvalue()))
|
|
||||||
self.assertEqual({"expression": "1 + 1", "timeout": 12.5, "inspector": url, "api": True}, seen)
|
|
||||||
out = io.StringIO()
|
|
||||||
with contextlib.redirect_stdout(out):
|
|
||||||
self.assertEqual(0, agent.main(["--cdp-inspector", "ws://example.com:9229/x", "5", "1"]))
|
|
||||||
self.assertEqual("INVALID_REQUEST", json.loads(out.getvalue())["error"]["code"])
|
|
||||||
self.assertEqual(2, agent.main(["--cdp-inspector", url]))
|
|
||||||
|
|
||||||
def test_a_devtools_endpoint_lost_while_sending_is_reported_as_gone(self):
|
def test_a_devtools_endpoint_lost_while_sending_is_reported_as_gone(self):
|
||||||
class Lost:
|
class Lost:
|
||||||
def __init__(self, *args, **kwargs):
|
def __init__(self, *args, **kwargs):
|
||||||
|
|||||||
@@ -1,117 +0,0 @@
|
|||||||
import platform
|
|
||||||
import re
|
|
||||||
import shutil
|
|
||||||
import subprocess
|
|
||||||
import tempfile
|
|
||||||
import unittest
|
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
FEX = Path(__file__).resolve().parents[1] / "fex"
|
|
||||||
PATCH = FEX / "patches/0009-signal-handler-escape-frees-host-stack.patch"
|
|
||||||
PROBE = FEX / "probes/signal-handler-escape.c"
|
|
||||||
DELEGATOR = "Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp"
|
|
||||||
CONTEXT = "Source/Tools/LinuxEmulation/ArchHelpers/MContext.h"
|
|
||||||
THREADS = "Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h"
|
|
||||||
FIELDS = ["PrevGuestFrame", "GuestFrameEnd", "GuestInterruptedSP", "GuestAltBase", "GuestAltEnd"]
|
|
||||||
|
|
||||||
|
|
||||||
def files():
|
|
||||||
sections = re.split(r"^diff --git a/(\S+) \S+\n", PATCH.read_text(), flags=re.M)
|
|
||||||
return {sections[i]: sections[i + 1] for i in range(1, len(sections), 2)}
|
|
||||||
|
|
||||||
|
|
||||||
def hunks(section):
|
|
||||||
return re.findall(r"^@@ [^@]+ @@ ?(.*)\n((?:[ +\-].*\n?)*)", section, re.M)
|
|
||||||
|
|
||||||
|
|
||||||
def added(body):
|
|
||||||
return [line[1:].strip() for line in body.splitlines() if line.startswith("+") and not line.startswith("+++")]
|
|
||||||
|
|
||||||
|
|
||||||
def removed(body):
|
|
||||||
return [line for line in body.splitlines() if line.startswith("-") and not line.startswith("---")]
|
|
||||||
|
|
||||||
|
|
||||||
class SignalHandlerEscapeTest(unittest.TestCase):
|
|
||||||
def test_only_signal_state_files_change(self):
|
|
||||||
self.assertEqual(sorted(files()), sorted([CONTEXT, DELEGATOR, THREADS]))
|
|
||||||
|
|
||||||
def test_nothing_is_removed(self):
|
|
||||||
for name, section in files().items():
|
|
||||||
self.assertEqual(removed(section), [], name)
|
|
||||||
|
|
||||||
def test_added_code_has_no_comments(self):
|
|
||||||
for name, section in files().items():
|
|
||||||
for line in added(section):
|
|
||||||
self.assertFalse("//" in line or "/*" in line, f"{name}: {line}")
|
|
||||||
|
|
||||||
def test_both_context_backups_record_the_guest_frame(self):
|
|
||||||
lines = added(files()[CONTEXT])
|
|
||||||
self.assertEqual(lines, [f"uint64_t {field};" for field in FIELDS] * 2)
|
|
||||||
|
|
||||||
def test_each_thread_keeps_its_frame_chain(self):
|
|
||||||
self.assertEqual([line for line in added(files()[THREADS]) if line], ["uint64_t GuestFrames {};", "uint32_t GuestFrameCount {};"])
|
|
||||||
|
|
||||||
def test_delivery_pushes_and_reclaims_only_left_frames_at_the_dispatch_level(self):
|
|
||||||
found = hunks(files()[DELEGATOR])
|
|
||||||
delivery = "".join(body for function, body in found if "HandleDispatcherGuestSignal" in function)
|
|
||||||
lines = added(delivery)
|
|
||||||
self.assertIn("#ifdef ARCHITECTURE_arm64", lines)
|
|
||||||
gate = " ".join(lines)
|
|
||||||
self.assertIn("WasInJIT && Newest && ContextBackup->PrevSP == SignalInfo.GuestFrames", gate)
|
|
||||||
self.assertIn("Frame->SignalHandlerRefCounter == SignalInfo.GuestFrameCount + 1", gate)
|
|
||||||
self.assertIn("GuestLeftFrame(Newest, OldGuestSP", gate)
|
|
||||||
self.assertIn("ContextBackup->PrevSP = HostTop;", lines)
|
|
||||||
self.assertIn("Frame->SignalHandlerRefCounter -= LeftFrames;", lines)
|
|
||||||
self.assertIn("SignalInfo.GuestFrames = reinterpret_cast<uint64_t>(ContextBackup);", lines)
|
|
||||||
self.assertIn("++SignalInfo.GuestFrameCount;", lines)
|
|
||||||
self.assertLess(lines.index("#endif"), lines.index("ContextBackup->PrevGuestFrame = SignalInfo.GuestFrames;"))
|
|
||||||
|
|
||||||
def test_signal_return_pops_its_frame_and_any_newer_ones(self):
|
|
||||||
found = hunks(files()[DELEGATOR])
|
|
||||||
restore = "".join(body for function, body in found if "RestoreThreadState" in function)
|
|
||||||
lines = added(restore)
|
|
||||||
self.assertIn("if (Entry == OldSP) {", lines)
|
|
||||||
self.assertIn("SignalInfo.GuestFrames = EntryBackup->PrevGuestFrame;", lines)
|
|
||||||
self.assertIn("Thread->CurrentFrame->SignalHandlerRefCounter -= Depth - 1;", lines)
|
|
||||||
self.assertNotIn("TYPE_PAUSE", " ".join(lines))
|
|
||||||
|
|
||||||
def test_thread_stop_clears_the_chain(self):
|
|
||||||
found = hunks(files()[DELEGATOR])
|
|
||||||
pause = "".join(body for function, body in found if "HandleSignalPause" in function)
|
|
||||||
self.assertEqual(added(pause), ["ThreadObject->SignalInfo.GuestFrames = 0;", "ThreadObject->SignalInfo.GuestFrameCount = 0;"])
|
|
||||||
|
|
||||||
def test_patch_follows_the_syscall_state_patch_on_every_release(self):
|
|
||||||
names = sorted(path.name for path in (FEX / "patches").glob("*.patch"))
|
|
||||||
self.assertEqual(names[names.index(PATCH.name) - 1], "0008-signal-return-restores-syscall-state.patch")
|
|
||||||
self.assertNotIn("Fixed-upstream", PATCH.read_text())
|
|
||||||
self.assertIn("tools/fex/patches/*.patch", (FEX / "build-in-arch.sh").read_text())
|
|
||||||
|
|
||||||
|
|
||||||
@unittest.skipUnless(platform.machine() == "x86_64", "the probe is x86-64 code")
|
|
||||||
class SignalHandlerEscapeProbeTest(unittest.TestCase):
|
|
||||||
@classmethod
|
|
||||||
def setUpClass(cls):
|
|
||||||
compiler = shutil.which("cc") or shutil.which("gcc") or shutil.which("clang")
|
|
||||||
if not compiler:
|
|
||||||
raise unittest.SkipTest("no C compiler")
|
|
||||||
cls.tmp = Path(tempfile.mkdtemp(prefix="fex-signal-escape-"))
|
|
||||||
cls.binary = cls.tmp / "probe"
|
|
||||||
subprocess.run([compiler, "-O2", "-o", str(cls.binary), str(PROBE)], check=True, capture_output=True, text=True)
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def tearDownClass(cls):
|
|
||||||
shutil.rmtree(cls.tmp, ignore_errors=True)
|
|
||||||
|
|
||||||
def test_native_kernel_survives_every_escape(self):
|
|
||||||
result = subprocess.run([str(self.binary), "20000"], capture_output=True, text=True, timeout=120)
|
|
||||||
self.assertEqual(result.returncode, 0, result.stdout)
|
|
||||||
counts = dict(part.split("=") for part in result.stdout.split())
|
|
||||||
for phase in ("onstack", "offstack", "mixed", "returns", "outer"):
|
|
||||||
self.assertEqual(counts[phase], "20000", phase)
|
|
||||||
self.assertEqual(counts["nested"], "60000")
|
|
||||||
self.assertEqual(counts["wrong"], "0")
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
unittest.main()
|
|
||||||
@@ -1,134 +0,0 @@
|
|||||||
import platform
|
|
||||||
import re
|
|
||||||
import shutil
|
|
||||||
import subprocess
|
|
||||||
import tempfile
|
|
||||||
import unittest
|
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
FEX = Path(__file__).resolve().parents[1] / "fex"
|
|
||||||
PATCH = FEX / "patches/0012-signal-return-applies-guest-registers.patch"
|
|
||||||
PROBE = FEX / "probes/signal-register-update.c"
|
|
||||||
HEADER = "Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h"
|
|
||||||
FRAMES = "Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp"
|
|
||||||
X64_ORDER = ["RAX", "RCX", "RDX", "RBX", "RSP", "RBP", "RSI", "RDI", "R8", "R9", "R10", "R11", "R12", "R13", "R14", "R15"]
|
|
||||||
|
|
||||||
|
|
||||||
def files():
|
|
||||||
sections = re.split(r"^diff --git a/(\S+) \S+\n", PATCH.read_text(), flags=re.M)
|
|
||||||
return {sections[i]: sections[i + 1] for i in range(1, len(sections), 2)}
|
|
||||||
|
|
||||||
|
|
||||||
def added(section):
|
|
||||||
return [line[1:].strip() for line in section.splitlines() if line.startswith("+") and not line.startswith("+++")]
|
|
||||||
|
|
||||||
|
|
||||||
def removed(section):
|
|
||||||
return [line[1:].strip() for line in section.splitlines() if line.startswith("-") and not line.startswith("---")]
|
|
||||||
|
|
||||||
|
|
||||||
def helper():
|
|
||||||
lines = added(files()[FRAMES])
|
|
||||||
start = next(i for i, line in enumerate(lines) if line.startswith("void SignalDelegator::ResumeWithGuestGPRs("))
|
|
||||||
end = lines.index("#endif", start)
|
|
||||||
return lines[start:end + 1]
|
|
||||||
|
|
||||||
|
|
||||||
class SignalRegisterUpdateTest(unittest.TestCase):
|
|
||||||
def test_only_signal_frame_files_change(self):
|
|
||||||
self.assertEqual(sorted(files()), sorted([FRAMES, HEADER]))
|
|
||||||
|
|
||||||
def test_patch_only_adds_code(self):
|
|
||||||
for name, section in files().items():
|
|
||||||
self.assertEqual(removed(section), [], name)
|
|
||||||
|
|
||||||
def test_added_code_has_no_comments(self):
|
|
||||||
for name, section in files().items():
|
|
||||||
for line in added(section):
|
|
||||||
self.assertNotIn("//", line, name)
|
|
||||||
self.assertNotIn("/*", line, name)
|
|
||||||
|
|
||||||
def test_helper_is_declared_once(self):
|
|
||||||
self.assertEqual(sum(line.startswith("void ResumeWithGuestGPRs(") for line in added(files()[HEADER])), 1)
|
|
||||||
|
|
||||||
def test_only_changed_registers_are_written_back(self):
|
|
||||||
body = helper()
|
|
||||||
self.assertIn("if (((Delivered ^ GuestGPRs[i]) & Mask) == 0) {", body)
|
|
||||||
self.assertEqual(body[body.index("if (((Delivered ^ GuestGPRs[i]) & Mask) == 0) {") + 1], "continue;")
|
|
||||||
|
|
||||||
def test_spilled_registers_go_to_the_frame_and_live_ones_to_host_registers(self):
|
|
||||||
body = helper()
|
|
||||||
self.assertIn("const bool InFrame = AllSpilled || (Spilled & (1U << HostReg));", body)
|
|
||||||
self.assertIn("Frame->State.gregs[i] = GuestGPRs[i];", body)
|
|
||||||
self.assertIn("ArchHelpers::Context::SetArmReg(ucontext, HostReg, GuestGPRs[i]);", body)
|
|
||||||
self.assertIn("for (size_t i = 0; i < Count && i < Config.SRAGPRCount; i++) {", body)
|
|
||||||
|
|
||||||
def test_signals_outside_jit_code_are_left_alone(self):
|
|
||||||
body = helper()
|
|
||||||
guard = body.index("if (!AllSpilled && !(Context->Flags & ArchHelpers::Context::ContextFlags::CONTEXT_FLAG_INJIT)) {")
|
|
||||||
self.assertEqual(body[guard + 1], "return;")
|
|
||||||
self.assertEqual(body[2], "#ifdef ARCHITECTURE_arm64")
|
|
||||||
|
|
||||||
def test_every_frame_type_applies_registers_when_rip_is_unchanged(self):
|
|
||||||
lines = added(files()[FRAMES])
|
|
||||||
calls = [line for line in lines if line.startswith("ResumeWithGuestGPRs(")]
|
|
||||||
self.assertEqual(calls, [
|
|
||||||
"ResumeWithGuestGPRs(Context, Frame, ucontext, GuestGPRs, FEXCore::Core::CPUState::NUM_GPRS, ~0ULL);",
|
|
||||||
"ResumeWithGuestGPRs(Context, Frame, ucontext, GuestGPRs, 8, 0xFFFF'FFFFULL);",
|
|
||||||
"ResumeWithGuestGPRs(Context, Frame, ucontext, GuestGPRs, 8, 0xFFFF'FFFFULL);",
|
|
||||||
])
|
|
||||||
branches = [lines[i + 1] for i, line in enumerate(lines[:-1]) if line == "} else {" and lines[i + 1].startswith("uint64_t GuestGPRs[")]
|
|
||||||
self.assertEqual(branches, ["uint64_t GuestGPRs[FEXCore::Core::CPUState::NUM_GPRS];", "uint64_t GuestGPRs[8];", "uint64_t GuestGPRs[8];"])
|
|
||||||
|
|
||||||
def test_registers_are_stored_by_guest_register_index(self):
|
|
||||||
lines = added(files()[FRAMES])
|
|
||||||
x64 = [m.group(1) for line in lines for m in [re.fullmatch(r"COPY_REG\((\w+)\);", line)] if m]
|
|
||||||
self.assertEqual(sorted(x64), sorted(X64_ORDER))
|
|
||||||
self.assertIn("#define COPY_REG(x) GuestGPRs[FEXCore::X86State::REG_##x] = guest_uctx->uc_mcontext.gregs[FEXCore::x86_64::FEX_REG_##x];", lines)
|
|
||||||
legacy = re.findall(r"GuestGPRs\[FEXCore::X86State::REG_(\w+)\] = guest_uctx->sc\.(\w+);", "\n".join(lines))
|
|
||||||
self.assertEqual(sorted(legacy), sorted((r, r[1:].lower()) for r in X64_ORDER[:8]))
|
|
||||||
rt = re.findall(r"GuestGPRs\[FEXCore::X86State::REG_(\w+)\] = guest_uctx->uc\.uc_mcontext\.gregs\[FEXCore::x86::FEX_REG_(\w+)\];", "\n".join(lines))
|
|
||||||
self.assertEqual(sorted(rt), sorted((r, r) for r in X64_ORDER[:8]))
|
|
||||||
|
|
||||||
def test_patch_follows_the_thunk_patch_on_every_release(self):
|
|
||||||
names = sorted(path.name for path in (FEX / "patches").glob("*.patch"))
|
|
||||||
self.assertEqual(names[names.index(PATCH.name) - 1], "0011-thunk-calls-mark-spilled-state.patch")
|
|
||||||
self.assertNotIn("Fixed-upstream", PATCH.read_text())
|
|
||||||
|
|
||||||
|
|
||||||
@unittest.skipUnless(platform.machine() == "x86_64", "the probe is x86 code")
|
|
||||||
class SignalRegisterUpdateProbeTest(unittest.TestCase):
|
|
||||||
@classmethod
|
|
||||||
def setUpClass(cls):
|
|
||||||
cls.compiler = shutil.which("cc") or shutil.which("gcc") or shutil.which("clang")
|
|
||||||
if not cls.compiler:
|
|
||||||
raise unittest.SkipTest("no C compiler")
|
|
||||||
cls.tmp = Path(tempfile.mkdtemp(prefix="fex-signal-regs-"))
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def tearDownClass(cls):
|
|
||||||
shutil.rmtree(cls.tmp, ignore_errors=True)
|
|
||||||
|
|
||||||
def build(self, *flags):
|
|
||||||
binary = self.tmp / ("probe" + "".join(flags))
|
|
||||||
result = subprocess.run([self.compiler, "-O2", *flags, "-o", str(binary), str(PROBE)], capture_output=True, text=True)
|
|
||||||
return binary if result.returncode == 0 else None
|
|
||||||
|
|
||||||
def check(self, binary, *args):
|
|
||||||
result = subprocess.run([str(binary), *args], capture_output=True, text=True, timeout=60)
|
|
||||||
self.assertEqual(result.returncode, 0, result.stdout)
|
|
||||||
self.assertIn("seen=1", result.stdout)
|
|
||||||
|
|
||||||
def test_native_kernel_applies_handler_register_changes(self):
|
|
||||||
self.check(self.build())
|
|
||||||
|
|
||||||
def test_native_kernel_applies_handler_register_changes_in_32_bit_frames(self):
|
|
||||||
binary = self.build("-m32")
|
|
||||||
if binary is None:
|
|
||||||
self.skipTest("no 32-bit toolchain")
|
|
||||||
self.check(binary)
|
|
||||||
self.check(binary, "legacy")
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
unittest.main()
|
|
||||||
@@ -1,78 +0,0 @@
|
|||||||
import platform
|
|
||||||
import re
|
|
||||||
import shutil
|
|
||||||
import subprocess
|
|
||||||
import tempfile
|
|
||||||
import unittest
|
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
FEX = Path(__file__).resolve().parents[1] / "fex"
|
|
||||||
PATCH = FEX / "patches/0008-signal-return-restores-syscall-state.patch"
|
|
||||||
PROBE = FEX / "probes/async-signal-context.c"
|
|
||||||
RESTORE = "Frame->InSyscallInfo = Context->InSyscallInfo;"
|
|
||||||
|
|
||||||
|
|
||||||
def hunks():
|
|
||||||
text = PATCH.read_text()
|
|
||||||
files = re.findall(r"^diff --git a/(\S+) ", text, re.M)
|
|
||||||
return files, re.findall(r"^@@ [^@]+ @@ ?(.*)\n((?:[ +\-].*\n?)*)", text, re.M)
|
|
||||||
|
|
||||||
|
|
||||||
class SignalReturnSyscallStateTest(unittest.TestCase):
|
|
||||||
def test_only_the_signal_delegator_changes(self):
|
|
||||||
files, found = hunks()
|
|
||||||
self.assertEqual(files, ["Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp"])
|
|
||||||
self.assertEqual(len(found), 1)
|
|
||||||
|
|
||||||
def test_only_returns_to_jit_code_restore_the_saved_syscall_state(self):
|
|
||||||
_, found = hunks()
|
|
||||||
function, body = found[0]
|
|
||||||
self.assertIn("SignalDelegator::RestoreThreadState", function)
|
|
||||||
lines = body.splitlines()
|
|
||||||
added = [line[1:].strip() for line in lines if line.startswith("+")]
|
|
||||||
removed = [line for line in lines if line.startswith("-")]
|
|
||||||
self.assertEqual(added, [RESTORE])
|
|
||||||
self.assertEqual(removed, [])
|
|
||||||
context = [line[1:].strip() for line in lines]
|
|
||||||
self.assertEqual(context[0], "auto Frame = Thread->CurrentFrame;")
|
|
||||||
in_jit = context.index("if (Context->Flags & ArchHelpers::Context::ContextFlags::CONTEXT_FLAG_INJIT) {")
|
|
||||||
restore = context.index(RESTORE)
|
|
||||||
self.assertLess(in_jit, restore)
|
|
||||||
self.assertEqual(context[restore + 1], "}")
|
|
||||||
self.assertLess(restore, context.index("RestoreFrame_x64(Thread, Context, Frame, ucontext);"))
|
|
||||||
|
|
||||||
def test_thread_pause_returns_are_untouched(self):
|
|
||||||
_, found = hunks()
|
|
||||||
body = found[0][1]
|
|
||||||
self.assertNotIn("TYPE_PAUSE", "".join(line for line in body.splitlines() if line.startswith("+")))
|
|
||||||
|
|
||||||
def test_patch_is_applied_to_every_release(self):
|
|
||||||
self.assertNotIn("Fixed-upstream", PATCH.read_text())
|
|
||||||
self.assertIn("tools/fex/patches/*.patch", (FEX / "build-in-arch.sh").read_text())
|
|
||||||
|
|
||||||
|
|
||||||
@unittest.skipUnless(platform.machine() == "x86_64", "the probe is x86-64 code")
|
|
||||||
class AsyncSignalContextProbeTest(unittest.TestCase):
|
|
||||||
@classmethod
|
|
||||||
def setUpClass(cls):
|
|
||||||
compiler = shutil.which("cc") or shutil.which("gcc") or shutil.which("clang")
|
|
||||||
if not compiler:
|
|
||||||
raise unittest.SkipTest("no C compiler")
|
|
||||||
cls.tmp = Path(tempfile.mkdtemp(prefix="fex-async-signal-"))
|
|
||||||
cls.binary = cls.tmp / "probe"
|
|
||||||
subprocess.run([compiler, "-O2", "-pthread", "-o", str(cls.binary), str(PROBE)], check=True, capture_output=True, text=True)
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def tearDownClass(cls):
|
|
||||||
shutil.rmtree(cls.tmp, ignore_errors=True)
|
|
||||||
|
|
||||||
def test_native_kernel_reports_the_interrupted_registers(self):
|
|
||||||
result = subprocess.run([str(self.binary), "500"], capture_output=True, text=True, timeout=120)
|
|
||||||
self.assertEqual(result.returncode, 0, result.stdout)
|
|
||||||
counts = dict(part.split("=") for part in result.stdout.split())
|
|
||||||
self.assertGreaterEqual(int(counts["matched"]), 500)
|
|
||||||
self.assertEqual(counts["stale"], "0")
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
unittest.main()
|
|
||||||
@@ -1,67 +0,0 @@
|
|||||||
import platform
|
|
||||||
import re
|
|
||||||
import shutil
|
|
||||||
import subprocess
|
|
||||||
import tempfile
|
|
||||||
import unittest
|
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
FEX = Path(__file__).resolve().parents[1] / "fex"
|
|
||||||
PATCH = FEX / "patches/0010-syscall-exit-resets-host-stack.patch"
|
|
||||||
PROBE = FEX / "probes/syscall-host-stack.c"
|
|
||||||
BRANCH_OPS = "FEXCore/Source/Interface/Core/JIT/BranchOps.cpp"
|
|
||||||
|
|
||||||
|
|
||||||
def hunks():
|
|
||||||
text = PATCH.read_text()
|
|
||||||
files = re.findall(r"^diff --git a/(\S+) ", text, re.M)
|
|
||||||
return files, re.findall(r"^@@ [^@]+ @@ ?(.*)\n((?:[ +\-].*\n?)*)", text, re.M)
|
|
||||||
|
|
||||||
|
|
||||||
class SyscallHostStackTest(unittest.TestCase):
|
|
||||||
def test_only_the_branch_ops_change(self):
|
|
||||||
files, found = hunks()
|
|
||||||
self.assertEqual(files, [BRANCH_OPS])
|
|
||||||
self.assertEqual(len(found), 2)
|
|
||||||
|
|
||||||
def test_both_ops_that_leave_the_block_reset_the_stack_after_spilling(self):
|
|
||||||
_, found = hunks()
|
|
||||||
for (function, body), op in zip(found, ("DEF_OP(Syscall)", "DEF_OP(ThreadRemoveCodeEntry)")):
|
|
||||||
lines = body.splitlines()
|
|
||||||
added = [line[1:].strip() for line in lines if line.startswith("+")]
|
|
||||||
self.assertEqual([line for line in added if line], ["ResetStack();"], op)
|
|
||||||
self.assertEqual([line for line in lines if line.startswith("-")], [], op)
|
|
||||||
context = [line[1:].strip() for line in lines]
|
|
||||||
self.assertIn(op, function + " " + " ".join(context))
|
|
||||||
self.assertLess(context.index("SpillStaticRegs(TMP1);"), context.index("ResetStack();"), op)
|
|
||||||
|
|
||||||
def test_patch_is_skipped_once_upstream_ships_it(self):
|
|
||||||
self.assertEqual(PATCH.read_text().splitlines()[0], "Fixed-upstream: FEX-2612")
|
|
||||||
self.assertIn("Fixed-upstream: FEX-", (FEX / "build-in-arch.sh").read_text())
|
|
||||||
|
|
||||||
|
|
||||||
@unittest.skipUnless(platform.machine() == "x86_64", "the probe is x86-64 code")
|
|
||||||
class SyscallHostStackProbeTest(unittest.TestCase):
|
|
||||||
@classmethod
|
|
||||||
def setUpClass(cls):
|
|
||||||
compiler = shutil.which("cc") or shutil.which("gcc") or shutil.which("clang")
|
|
||||||
if not compiler:
|
|
||||||
raise unittest.SkipTest("no C compiler")
|
|
||||||
cls.tmp = Path(tempfile.mkdtemp(prefix="fex-syscall-stack-"))
|
|
||||||
cls.binary = cls.tmp / "probe"
|
|
||||||
subprocess.run([compiler, "-O2", "-o", str(cls.binary), str(PROBE)], check=True, capture_output=True, text=True)
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def tearDownClass(cls):
|
|
||||||
shutil.rmtree(cls.tmp, ignore_errors=True)
|
|
||||||
|
|
||||||
def test_native_kernel_runs_every_syscall(self):
|
|
||||||
result = subprocess.run([str(self.binary), "200000"], capture_output=True, text=True, timeout=120)
|
|
||||||
self.assertEqual(result.returncode, 0, result.stdout)
|
|
||||||
counts = dict(part.split("=") for part in result.stdout.split())
|
|
||||||
self.assertIn(counts["mode"], ("avx", "mmx"))
|
|
||||||
self.assertEqual(counts["syscalls"], "200000")
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
unittest.main()
|
|
||||||
@@ -1,124 +0,0 @@
|
|||||||
import platform
|
|
||||||
import re
|
|
||||||
import shutil
|
|
||||||
import subprocess
|
|
||||||
import tempfile
|
|
||||||
import unittest
|
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
FEX = Path(__file__).resolve().parents[1] / "fex"
|
|
||||||
PATCH = FEX / "patches/0011-thunk-calls-mark-spilled-state.patch"
|
|
||||||
PROBE = FEX / "probes/vdso-signal-state.c"
|
|
||||||
CORE = "FEXCore/Source/Interface/Core/Core.cpp"
|
|
||||||
BRANCH_OPS = "FEXCore/Source/Interface/Core/JIT/BranchOps.cpp"
|
|
||||||
DELEGATOR = "Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp"
|
|
||||||
FRAMES = "Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp"
|
|
||||||
MARK = "str(TMP1, STATE, offsetof(FEXCore::Core::CpuStateFrame, InSyscallInfo));"
|
|
||||||
CLEAR = "str(ARMEmitter::XReg::zr, STATE, offsetof(FEXCore::Core::CpuStateFrame, InSyscallInfo));"
|
|
||||||
RESTORE = "Frame->InSyscallInfo = Context->InSyscallInfo;"
|
|
||||||
|
|
||||||
|
|
||||||
def files():
|
|
||||||
sections = re.split(r"^diff --git a/(\S+) \S+\n", PATCH.read_text(), flags=re.M)
|
|
||||||
return {sections[i]: sections[i + 1] for i in range(1, len(sections), 2)}
|
|
||||||
|
|
||||||
|
|
||||||
def hunks(section):
|
|
||||||
return re.findall(r"^@@ [^@]+ @@ ?(.*)\n((?:[ +\-].*\n?)*)", section, re.M)
|
|
||||||
|
|
||||||
|
|
||||||
def added(body):
|
|
||||||
return [line[1:].strip() for line in body.splitlines() if line.startswith("+") and not line.startswith("+++")]
|
|
||||||
|
|
||||||
|
|
||||||
def removed(body):
|
|
||||||
return [line[1:].strip() for line in body.splitlines() if line.startswith("-") and not line.startswith("---")]
|
|
||||||
|
|
||||||
|
|
||||||
def context(body):
|
|
||||||
return [line[1:].strip() for line in body.splitlines() if line[:1] in (" ", "+")]
|
|
||||||
|
|
||||||
|
|
||||||
class ThunkSignalStateTest(unittest.TestCase):
|
|
||||||
def test_only_signal_state_files_change(self):
|
|
||||||
self.assertEqual(sorted(files()), sorted([BRANCH_OPS, CORE, DELEGATOR, FRAMES]))
|
|
||||||
|
|
||||||
def test_added_code_has_no_new_comments(self):
|
|
||||||
for name, section in files().items():
|
|
||||||
moved = set(removed(section))
|
|
||||||
for line in added(section):
|
|
||||||
if "//" in line or "/*" in line:
|
|
||||||
self.assertIn(line, moved, f"{name}: {line}")
|
|
||||||
|
|
||||||
def test_thunk_call_marks_all_state_spilled_until_the_refill(self):
|
|
||||||
section = files()[BRANCH_OPS]
|
|
||||||
lines = context(section)
|
|
||||||
self.assertEqual([line for line in added(section) if line], ["LoadConstant(ARMEmitter::Size::i64Bit, TMP1, 0xFFFF);", MARK, CLEAR])
|
|
||||||
self.assertEqual(removed(section), [])
|
|
||||||
self.assertLess(lines.index("PushDynamicRegs(TMP1);"), lines.index(MARK))
|
|
||||||
self.assertLess(lines.index(MARK), lines.index("InsertNamedThunkRelocation(ARMEmitter::Reg::r2, Op->ThunkNameHash);"))
|
|
||||||
refill = lines.index("FillStaticRegs({")
|
|
||||||
self.assertEqual(lines[refill + 1:refill + 3], [".NZCV = false,", "});"])
|
|
||||||
self.assertLess(refill, lines.index(CLEAR))
|
|
||||||
|
|
||||||
def test_fully_spilled_state_is_never_respilled_from_host_registers(self):
|
|
||||||
found = hunks(files()[DELEGATOR])
|
|
||||||
spill = "".join(body for function, body in found if "SpillSRA" in function or "IgnoreMask" in body)
|
|
||||||
lines = context(spill)
|
|
||||||
guard = lines.index("if ((IgnoreMask & 0xFFFF) == 0xFFFF) {")
|
|
||||||
self.assertIn("RestoreRIPFromHostPC", lines[guard - 2])
|
|
||||||
self.assertEqual(lines[guard + 1], "return;")
|
|
||||||
self.assertIn("for (size_t i = 0; i < Config.SRAGPRCount; i++) {", lines[guard + 2:guard + 5])
|
|
||||||
|
|
||||||
def test_every_guest_signal_saves_and_clears_the_mark(self):
|
|
||||||
section = files()[DELEGATOR]
|
|
||||||
lines = added(section)
|
|
||||||
self.assertIn("ContextBackup->InSyscallInfo = Frame->InSyscallInfo;", lines)
|
|
||||||
self.assertIn("Frame->InSyscallInfo = 0;", lines)
|
|
||||||
self.assertIn(RESTORE, lines)
|
|
||||||
self.assertIn("if (Context->Flags & ArchHelpers::Context::ContextFlags::CONTEXT_FLAG_INJIT) {", removed(section))
|
|
||||||
self.assertNotIn("TYPE_PAUSE", " ".join(lines))
|
|
||||||
|
|
||||||
def test_redirected_returns_restart_with_no_mark(self):
|
|
||||||
section = files()[FRAMES]
|
|
||||||
self.assertEqual(added(section), ["Frame->InSyscallInfo = 0;"] * 3)
|
|
||||||
self.assertEqual(removed(section), [RESTORE] * 3)
|
|
||||||
|
|
||||||
def test_guest_callbacks_run_with_no_mark(self):
|
|
||||||
lines = added(files()[CORE])
|
|
||||||
self.assertEqual(lines[1:3], ["const auto InSyscallInfo = Frame->InSyscallInfo;", "Frame->InSyscallInfo = 0;"])
|
|
||||||
self.assertEqual(lines[-1], "Frame->InSyscallInfo = InSyscallInfo;")
|
|
||||||
self.assertIn("ExecuteJITCallback(Frame, RIP);", lines[-2])
|
|
||||||
|
|
||||||
def test_patch_follows_the_host_stack_patch_on_every_release(self):
|
|
||||||
names = sorted(path.name for path in (FEX / "patches").glob("*.patch"))
|
|
||||||
self.assertEqual(names[names.index(PATCH.name) - 1], "0010-syscall-exit-resets-host-stack.patch")
|
|
||||||
self.assertNotIn("Fixed-upstream", PATCH.read_text())
|
|
||||||
|
|
||||||
|
|
||||||
@unittest.skipUnless(platform.machine() == "x86_64", "the probe is x86-64 code")
|
|
||||||
class VdsoSignalStateProbeTest(unittest.TestCase):
|
|
||||||
@classmethod
|
|
||||||
def setUpClass(cls):
|
|
||||||
compiler = shutil.which("cc") or shutil.which("gcc") or shutil.which("clang")
|
|
||||||
if not compiler:
|
|
||||||
raise unittest.SkipTest("no C compiler")
|
|
||||||
cls.tmp = Path(tempfile.mkdtemp(prefix="fex-vdso-signal-"))
|
|
||||||
cls.binary = cls.tmp / "probe"
|
|
||||||
subprocess.run([compiler, "-O2", "-o", str(cls.binary), str(PROBE)], check=True, capture_output=True, text=True)
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def tearDownClass(cls):
|
|
||||||
shutil.rmtree(cls.tmp, ignore_errors=True)
|
|
||||||
|
|
||||||
def test_native_kernel_keeps_registers_across_interrupted_clock_calls(self):
|
|
||||||
result = subprocess.run([str(self.binary), "1"], capture_output=True, text=True, timeout=60)
|
|
||||||
self.assertEqual(result.returncode, 0, result.stdout)
|
|
||||||
counts = dict(part.split("=") for part in result.stdout.split())
|
|
||||||
self.assertGreater(int(counts["calls"]), 0)
|
|
||||||
self.assertGreater(int(counts["alarms"]), 0)
|
|
||||||
self.assertEqual(counts["bad"], "0")
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
unittest.main()
|
|
||||||
@@ -1147,9 +1147,12 @@ class GameEnvironmentTest(unittest.TestCase):
|
|||||||
def test_install_script_run_keys_default_to_the_app_key(self):
|
def test_install_script_run_keys_default_to_the_app_key(self):
|
||||||
keys = MODULE["run_keys"](MODULE["read_vdf"](self.SCRIPT))
|
keys = MODULE["run_keys"](MODULE["read_vdf"](self.SCRIPT))
|
||||||
self.assertEqual(keys, {
|
self.assertEqual(keys, {
|
||||||
("hkey_local_machine\\software\\valve\\steam\\apps\\commonredist\\vcredist\\2019", "x64 14.28.29334.0"),
|
("hkey_local_machine\\software\\valve\\steam\\apps\\commonredist\\vcredist\\2019", "x64 14.28.29334.0", 1),
|
||||||
("hkey_local_machine\\software\\valve\\steam\\apps\\228980", "setup"),
|
("hkey_local_machine\\software\\valve\\steam\\apps\\228980", "setup", 1),
|
||||||
})
|
})
|
||||||
|
with_minimum = self.SCRIPT.replace('"Setup" { "process 1"', '"Setup" { "MinimumHasRunValue" "3" "process 1"')
|
||||||
|
self.assertIn(("hkey_local_machine\\software\\valve\\steam\\apps\\228980", "setup", 3),
|
||||||
|
MODULE["run_keys"](MODULE["read_vdf"](with_minimum)))
|
||||||
with self.assertRaises(ValueError):
|
with self.assertRaises(ValueError):
|
||||||
MODULE["read_vdf"]('"a" { "b" }')
|
MODULE["read_vdf"]('"a" { "b" }')
|
||||||
|
|
||||||
@@ -1168,12 +1171,59 @@ class GameEnvironmentTest(unittest.TestCase):
|
|||||||
self.assertFalse(done([str(script)], env))
|
self.assertFalse(done([str(script)], env))
|
||||||
(prefix / "system.reg").write_text(self.REDIST + self.SETUP)
|
(prefix / "system.reg").write_text(self.REDIST + self.SETUP)
|
||||||
self.assertTrue(done([str(script)], env))
|
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"))
|
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))
|
self.assertFalse(done([str(script)], env))
|
||||||
script.write_text('"InstallScript" { "Registry" { "HKEY_LOCAL_MACHINE\\\\Software\\\\Game" { "string" { "Path" "%INSTALLDIR%" } } } }')
|
script.write_text('"InstallScript" { "Registry" { "HKEY_LOCAL_MACHINE\\\\Software\\\\Game" { "string" { "Path" "%INSTALLDIR%" } } } }')
|
||||||
MODULE["record_install_scripts"](MODULE["scripts_digest"]([str(script)]), env)
|
MODULE["record_install_scripts"](MODULE["scripts_digest"]([str(script)]), env)
|
||||||
self.assertFalse(done([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_install_scripts_need_their_dword_guards_satisfied(self):
|
||||||
|
with tempfile.TemporaryDirectory() as tmp:
|
||||||
|
script = Path(tmp) / "evaluatorscript_1.vdf"
|
||||||
|
script.write_text(self.SCRIPT)
|
||||||
|
prefix = Path(tmp) / "compat/pfx"
|
||||||
|
prefix.mkdir(parents=True)
|
||||||
|
env = {"STEAM_COMPAT_DATA_PATH": str(prefix.parent)}
|
||||||
|
done = MODULE["install_scripts_done"]
|
||||||
|
MODULE["record_install_scripts"](MODULE["scripts_digest"]([str(script)]), env)
|
||||||
|
# a guard DWORD of 0 means Steam still runs the process, recorded or not
|
||||||
|
(prefix / "system.reg").write_text(self.REDIST + self.SETUP.replace("dword:00000001", "dword:00000000"))
|
||||||
|
self.assertFalse(done([str(script)], env))
|
||||||
|
(prefix / MODULE["INSTALL_STAMP"]).unlink()
|
||||||
|
self.assertFalse(done([str(script)], env))
|
||||||
|
# a value that is not a DWORD does not count either
|
||||||
|
(prefix / "system.reg").write_text(self.REDIST + self.SETUP.replace("dword:00000001", '"1"'))
|
||||||
|
self.assertFalse(done([str(script)], env))
|
||||||
|
# MinimumHasRunValue: below it the process runs again, at or above it the scripts are done
|
||||||
|
script.write_text(self.SCRIPT.replace('"Setup" { "process 1"', '"Setup" { "MinimumHasRunValue" "2" "process 1"'))
|
||||||
|
(prefix / "system.reg").write_text(self.REDIST + self.SETUP)
|
||||||
|
self.assertFalse(done([str(script)], env))
|
||||||
|
(prefix / "system.reg").write_text(self.REDIST + self.SETUP.replace("dword:00000001", "dword:00000002"))
|
||||||
|
self.assertTrue(done([str(script)], env))
|
||||||
|
|
||||||
def test_the_evaluator_is_skipped_once_it_finished_the_same_scripts(self):
|
def test_the_evaluator_is_skipped_once_it_finished_the_same_scripts(self):
|
||||||
with tempfile.TemporaryDirectory() as tmp:
|
with tempfile.TemporaryDirectory() as tmp:
|
||||||
root = Path(tmp)
|
root = Path(tmp)
|
||||||
@@ -1189,8 +1239,12 @@ class GameEnvironmentTest(unittest.TestCase):
|
|||||||
proton.write_text("#!/bin/sh\necho run >> %s\nexit ${EXIT_CODE:-0}\n" % shlex.quote(str(runs)))
|
proton.write_text("#!/bin/sh\necho run >> %s\nexit ${EXIT_CODE:-0}\n" % shlex.quote(str(runs)))
|
||||||
proton.chmod(0o755)
|
proton.chmod(0o755)
|
||||||
|
|
||||||
def evaluate(exit_code="0"):
|
# a registry action besides the marked runs: Steam's evaluator has work to do, so it runs once
|
||||||
script.write_text(self.SCRIPT if exit_code != "changed" else self.SCRIPT.replace("setup.exe", "setup-update.exe"))
|
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),
|
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)
|
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",
|
result = subprocess.run([sys.executable, str(BIN / "droiddeck-game-env"), str(proton), "run",
|
||||||
@@ -1203,6 +1257,8 @@ class GameEnvironmentTest(unittest.TestCase):
|
|||||||
self.assertEqual(evaluate(), (0, 2))
|
self.assertEqual(evaluate(), (0, 2))
|
||||||
self.assertEqual(evaluate(), (0, 2))
|
self.assertEqual(evaluate(), (0, 2))
|
||||||
self.assertEqual(evaluate("changed"), (0, 3))
|
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):
|
def test_the_mali_bridge_caps_the_vkd3d_feature_level(self):
|
||||||
bridge = {"DD_VKBRIDGE": "1", "VKD3D_FEATURE_LEVEL": "12_2"}
|
bridge = {"DD_VKBRIDGE": "1", "VKD3D_FEATURE_LEVEL": "12_2"}
|
||||||
@@ -1392,6 +1448,61 @@ class GameEnvironmentTest(unittest.TestCase):
|
|||||||
self.assertFalse(leftover.exists())
|
self.assertFalse(leftover.exists())
|
||||||
self.assertEqual(selection.read_bytes(), saved)
|
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):
|
def test_component_scope_matches_environment_scope_for_shortcut_ids(self):
|
||||||
with tempfile.TemporaryDirectory() as tmp:
|
with tempfile.TemporaryDirectory() as tmp:
|
||||||
root = Path(tmp)
|
root = Path(tmp)
|
||||||
@@ -2235,6 +2346,46 @@ class GameEnvironmentTest(unittest.TestCase):
|
|||||||
env=env, capture_output=True, text=True, check=True).stdout
|
env=env, capture_output=True, text=True, check=True).stdout
|
||||||
self.assertEqual(out, "continued\n", (verb, args, prefix))
|
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):
|
def test_wrappers_preload_the_session_library_before_the_input_shim(self):
|
||||||
overlay = "/root/.local/share/Steam/ubuntu12_64/gameoverlayrenderer.so"
|
overlay = "/root/.local/share/Steam/ubuntu12_64/gameoverlayrenderer.so"
|
||||||
with tempfile.TemporaryDirectory() as tmp:
|
with tempfile.TemporaryDirectory() as tmp:
|
||||||
|
|||||||
@@ -43,11 +43,15 @@ class HdrLiveSwitchTest(unittest.TestCase):
|
|||||||
def test_the_gate_follows_the_display_not_the_setting(self):
|
def test_the_gate_follows_the_display_not_the_setting(self):
|
||||||
text = (APP / "SessionActivity.kt").read_text()
|
text = (APP / "SessionActivity.kt").read_text()
|
||||||
start = text.index("val attached = CompositorHost.isStarted")
|
start = text.index("val attached = CompositorHost.isStarted")
|
||||||
block = text[start:text.index("DriverSetupLog.write", start)]
|
block = text[start:text.index("CompositorHost.start(", start)]
|
||||||
request = block[block.index("nativeSetHdrRequest("):block.index("Log.i", block.index("nativeSetHdrRequest("))]
|
request = block[block.index("nativeSetHdrRequest("):block.index("Log.i", block.index("nativeSetHdrRequest("))]
|
||||||
self.assertNotIn("SessionPrefs.hdr", block[:block.index("if (!SessionState.running)")])
|
self.assertNotIn("SessionPrefs.hdr", block)
|
||||||
self.assertIn("capable, false", request)
|
self.assertIn("capable, false", request)
|
||||||
self.assertIn("SessionState.hdrCapable && SessionPrefs.hdr(this, mode)", block)
|
self.assertIn("if (!SessionState.running) CompositorHost.applyHdr(this, mode)", block)
|
||||||
|
host = (APP / "wayland/CompositorHost.kt").read_text()
|
||||||
|
gate = host[host.index("fun applyHdr("):]
|
||||||
|
gate = gate[:gate.index("\n }")]
|
||||||
|
self.assertIn("SessionState.hdrCapable && SessionPrefs.hdr(context, mode)", gate)
|
||||||
|
|
||||||
def test_both_switches_apply_to_the_running_session(self):
|
def test_both_switches_apply_to_the_running_session(self):
|
||||||
helper = (APP / "session/SessionHdr.kt").read_text()
|
helper = (APP / "session/SessionHdr.kt").read_text()
|
||||||
|
|||||||
@@ -27,13 +27,26 @@ def droiddeck_release(ver, prerelease=False, draft=False):
|
|||||||
|
|
||||||
class ProtonExtraTest(unittest.TestCase):
|
class ProtonExtraTest(unittest.TestCase):
|
||||||
def test_sources_and_their_arm64_assets(self):
|
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"]
|
repo, pattern = EXTRA["SOURCES"]["droiddeck"]
|
||||||
self.assertEqual(repo, "Droid-Deck/DroidDeck-Proton")
|
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-7.5-aarch64.tar.gz"))
|
||||||
self.assertTrue(pattern.search("DroidDeck-Proton-11-8-aarch64.tar.xz"))
|
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.sha512sum"))
|
||||||
self.assertFalse(pattern.search("DroidDeck-Proton-11-7.5-aarch64.build-info.json"))
|
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):
|
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")]
|
releases = [droiddeck_release("11-8", prerelease=True), droiddeck_release("11-7.9", draft=True), droiddeck_release("11-7.5")]
|
||||||
|
|||||||
Loaded 100 of 101 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user