Compare commits
24
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
eb44931973 | ||
|
|
59cac100e8 | ||
|
|
371e87fa31 | ||
|
|
e9a7ef5f44 | ||
|
|
40461caf4a | ||
|
|
1e877fa602 | ||
|
|
906009a33a | ||
|
|
08559a02f8 | ||
|
|
1d93626453 | ||
|
|
9d0989374b | ||
|
|
3278afaa1a | ||
|
|
bf221ffbbd | ||
|
|
c636eea355 | ||
|
|
ffaa906cd1 | ||
|
|
d61af961c1 | ||
|
|
bc01b77752 | ||
|
|
a1b01a04a8 | ||
|
|
b44235c495 | ||
|
|
b80d5db176 | ||
|
|
d3c0d258b7 | ||
|
|
9dcdbf245a | ||
|
|
369e218afb | ||
|
|
119d24bf6b | ||
|
|
2a905510d5 |
No files matched your search
@@ -57,6 +57,22 @@ jobs:
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Version bumps are isolated
|
||||
if: github.event_name == 'pull_request'
|
||||
run: |
|
||||
set -euo pipefail
|
||||
git fetch --no-tags origin main
|
||||
base=$(git merge-base origin/main HEAD)
|
||||
diff=$(git diff -U0 "$base..HEAD" -- app/build.gradle)
|
||||
grep -Eq '^[+-][[:space:]]*version(Code|Name)[[:space:]]' <<<"$diff" || exit 0
|
||||
other_files=$(git diff --name-only "$base..HEAD" | grep -v '^app/build.gradle$' || true)
|
||||
other_gradle=$(grep -E '^[+-]' <<<"$diff" | grep -Ev '^(---|\+\+\+)' | grep -Ev '^[+-][[:space:]]*version(Code|Name)[[:space:]]' || true)
|
||||
if [[ -n "$other_files" || -n "$other_gradle" ]]; then
|
||||
echo "::error::versionCode/versionName changes must be isolated in their own PR"
|
||||
echo "A version PR may only change the versionCode/versionName lines in app/build.gradle." >> "$GITHUB_STEP_SUMMARY"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Merge onto main, or say what conflicts
|
||||
if: github.event_name == 'pull_request'
|
||||
run: |
|
||||
@@ -157,7 +173,7 @@ jobs:
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: app/src/main/assets/linuxfs
|
||||
key: preloads-${{ env.PRELOAD_CACHE_VERSION }}-${{ hashFiles('app/src/main/cpp/fakeinput_steam.cpp', 'tools/linuxfs/preload/*.c', 'tools/linuxfs/build-x86-preloads.sh', 'tools/linuxfs/fex/*', 'tools/linuxfs/clipboard/*.c', 'tools/proot/fastpath/*.c', 'tools/linuxfs/overlay/usr/local/bin/*', 'tools/linuxfs/overlay/usr/bin/**', 'tools/linuxfs/desktop/*', 'tools/gamescope/release.env', 'tools/wlroots/release.env', 'tools/linuxfs/uruntime.env', 'tools/linuxfs/licenses/*', 'tools/mangoapp/*') }}
|
||||
key: preloads-${{ env.PRELOAD_CACHE_VERSION }}-${{ hashFiles('app/src/main/cpp/fakeinput_steam.cpp', 'tools/linuxfs/preload/*.c', 'tools/linuxfs/build-x86-preloads.sh', 'tools/linuxfs/fex/*', 'tools/linuxfs/clipboard/*.c', 'tools/linuxfs/ssbs/*.c', 'tools/proot/fastpath/*.c', 'tools/linuxfs/overlay/usr/local/bin/*', 'tools/linuxfs/overlay/usr/bin/**', 'tools/linuxfs/desktop/*', 'tools/gamescope/release.env', 'tools/wlroots/release.env', 'tools/linuxfs/uruntime.env', 'tools/linuxfs/licenses/*', 'tools/mangoapp/*', 'tools/msitools/**') }}
|
||||
|
||||
- name: Build libfakeinput.so and libblsession.so (glibc aarch64)
|
||||
if: steps.preloads.outputs.cache-hit != 'true'
|
||||
@@ -179,6 +195,10 @@ jobs:
|
||||
aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -pthread \
|
||||
-o "$D/libblfastpath.so" tools/proot/fastpath/fastpath.c -ldl
|
||||
aarch64-linux-gnu-strip --strip-unneeded "$D/libblfastpath.so"
|
||||
# Force-SSBS adapter, preloaded into a game's Wine only when the game asks for it.
|
||||
aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -pthread \
|
||||
-o "$D/libssbs.so" tools/linuxfs/ssbs/ssbs_adapter.c -ldl
|
||||
aarch64-linux-gnu-strip --strip-unneeded "$D/libssbs.so"
|
||||
mkdir -p "$D/usr/local/bin"
|
||||
aarch64-linux-gnu-gcc -O2 -Wall -Wextra -o "$D/usr/local/bin/droiddeck-clipboard" tools/linuxfs/clipboard/clipboard.c -ldl
|
||||
aarch64-linux-gnu-strip --strip-unneeded "$D/usr/local/bin/droiddeck-clipboard"
|
||||
@@ -230,6 +250,26 @@ jobs:
|
||||
install -Dm644 tools/mangoapp/mangoapp "$D/usr/local/bin/mangoapp"
|
||||
rm -rf mango-pkgs
|
||||
ls -l "$M"
|
||||
# The Windows components installer's tools (tools/msitools/packages.txt).
|
||||
T="$D/usr/local/lib/droiddeck-msitools"
|
||||
mkdir -p "$T" msi-pkgs
|
||||
grep -v '^#' tools/msitools/packages.txt | while read -r sum url; do
|
||||
[ -n "$url" ] || continue
|
||||
curl -fsSL --retry 3 -o msi-pkgs/pkg.tar.xz "$url"
|
||||
echo "$sum msi-pkgs/pkg.tar.xz" | sha256sum -c -
|
||||
tar -xJf msi-pkgs/pkg.tar.xz -C msi-pkgs
|
||||
rm msi-pkgs/pkg.tar.xz
|
||||
done
|
||||
install -m644 msi-pkgs/usr/bin/msiinfo "$T/msiinfo"
|
||||
install -m644 msi-pkgs/usr/bin/cabextract "$T/cabextract"
|
||||
for so in libmsi-1.0.so.0 libgsf-1.so.114 libgcab-1.0.so.0; do
|
||||
cp -L "msi-pkgs/usr/lib/$so" "$T/$so"
|
||||
done
|
||||
for f in NOTICE GPL-2 GPL-3 LGPL-2.1; do
|
||||
install -Dm644 "tools/msitools/licenses/$f" "$D/usr/local/share/licenses/droiddeck-msitools/$f"
|
||||
done
|
||||
rm -rf msi-pkgs
|
||||
ls -l "$T"
|
||||
install -Dm644 tools/linuxfs/desktop/droiddeck-desktop "$D/usr/local/bin/droiddeck-desktop"
|
||||
install -Dm644 tools/linuxfs/desktop/droiddeck-gpu "$D/usr/local/bin/droiddeck-gpu"
|
||||
install -Dm644 tools/linuxfs/desktop/droiddeck-desktop-gpu "$D/usr/local/bin/droiddeck-desktop-gpu"
|
||||
@@ -343,11 +383,23 @@ jobs:
|
||||
echo "::error::libfakeinput.so exports the C++ runtime"; exit 1
|
||||
fi
|
||||
SESSION=$(syms "$D/libblsession.so")
|
||||
for sym in socket bind getsockname setsockopt statfs statvfs syscall shm_open shm_unlink mmap mmap64 munmap drmPrimeFDToHandle drmCloseBufferHandle drmIoctl; do
|
||||
for sym in socket bind getsockname setsockopt statfs statvfs syscall shm_open shm_unlink mmap mmap64 munmap drmPrimeFDToHandle drmCloseBufferHandle; do
|
||||
grep -qx "$sym" <<<"$SESSION" || { echo "::error::libblsession.so does not export $sym"; exit 1; }
|
||||
done
|
||||
# Zink's GEM_CLOSE is caught at ioctl(); an exported drmIoctl made NMS replay old frames.
|
||||
if grep -qx drmIoctl <<<"$SESSION"; then
|
||||
echo "::error::libblsession.so exports drmIoctl"; exit 1
|
||||
fi
|
||||
SSBS=$(syms "$D/libssbs.so")
|
||||
for sym in sigaction signal bsd_signal sysv_signal; do
|
||||
grep -qx "$sym" <<<"$SSBS" || { echo "::error::libssbs.so does not export $sym"; exit 1; }
|
||||
done
|
||||
test -f "$D/usr/local/bin/droiddeck-session"
|
||||
test -f "$D/usr/local/bin/droiddeck-proton-extra"
|
||||
test -f "$D/usr/local/bin/droiddeck-msi-install"
|
||||
for f in msiinfo cabextract libmsi-1.0.so.0 libgsf-1.so.114 libgcab-1.0.so.0; do
|
||||
test -f "$D/usr/local/lib/droiddeck-msitools/$f" || { echo "::error::droiddeck-msitools/$f missing"; exit 1; }
|
||||
done
|
||||
|
||||
- name: Cache the CMake build tree
|
||||
uses: actions/cache@v4
|
||||
|
||||
@@ -15,7 +15,7 @@ DroidDeck brings the SteamOS experience to Android: Valve's Steam client in Big
|
||||
|
||||
## Requirements and install
|
||||
|
||||
Use Android 9 or newer on a supported Adreno device (730 or newer, or 8xx). Mali, Xclipse, PowerVR, and Adreno 710 are unsupported. No root is required. Allow about 3 GB for the runtime and 1.1 GB more for the desktop and emulators. Install the APK from [Releases](https://github.com/Droid-Deck/DroidDeck/releases), install the Linux runtime, then press **Play** and sign in. Steam downloads on first launch. Install **Desktop & apps** to use the desktop and emulators. The **Store** installs Linux apps and games from Flathub (ARM64 builds) with Flatpak; with additional options to install Appimages and set up scripts.
|
||||
Use Android 9 or newer on a supported Adreno device (730 or newer, or 8xx). Adreno 6xx is experimental: DirectX 11 uses DXVK 2 and may run, and DirectX 12 games can still crash. Mali, Xclipse, PowerVR, and Adreno 710 are unsupported. No root is required. Allow about 3 GB for the runtime and 1.1 GB more for the desktop and emulators. Install the APK from [Releases](https://github.com/Droid-Deck/DroidDeck/releases), install the Linux runtime, then press **Play** and sign in. Steam downloads on first launch. Install **Desktop & apps** to use the desktop and emulators. The **Store** installs Linux apps and games from Flathub (ARM64 builds) with Flatpak; with additional options to install Appimages and set up scripts.
|
||||
|
||||
Before Steam launches, you must turn off **Restrict child processes** in Developer options. If this option is not available in developer settings (Android 12 and 13 devices), first launch of Steam will present a "Fix it for me" button, which will help automate the setup process.
|
||||
|
||||
|
||||
@@ -190,6 +190,8 @@ dependencies {
|
||||
// The runtime tarball is a zstd-compressed tar.
|
||||
implementation 'com.github.luben:zstd-jni:1.5.2-3@aar'
|
||||
implementation 'org.apache.commons:commons-compress:1.27.1'
|
||||
// Bannerlator's Windows components come as .tar.xz (WinComponents).
|
||||
implementation 'org.tukaani:xz:1.10'
|
||||
// The UI: every menu, dialog and overlay is Compose. The session's SurfaceView and the
|
||||
// on-screen pad are Views underneath it, which is what they are in every Compose app.
|
||||
implementation platform('androidx.compose:compose-bom:2024.02.00')
|
||||
|
||||
@@ -44,6 +44,11 @@ add_subdirectory(waylandcomp)
|
||||
add_library(sdnative SHARED sdnative/sdnative.c)
|
||||
target_link_libraries(sdnative log)
|
||||
|
||||
# The device info window's Vulkan section: the phone's own driver, asked once through the system
|
||||
# loader (opened with dlopen, so a phone without Vulkan still loads the app).
|
||||
add_library(deviceinfo SHARED deviceinfo/vkinfo.c)
|
||||
target_link_libraries(deviceinfo dl)
|
||||
|
||||
# Rebuild Termux terminal-emulator's PTY JNI helper with the app's NDK instead of carrying its
|
||||
# prebuilt libtermux.so with a redundant libstdc++.so dependency.
|
||||
add_library(termux SHARED termux/termux.c)
|
||||
@@ -0,0 +1,112 @@
|
||||
// What the phone's own Vulkan driver says about its GPU, for the app's device info window: one
|
||||
// instance on the system loader, the first physical device's properties, a few limits and the
|
||||
// extensions DXVK and VKD3D-Proton lean on. Returned as "key=value" lines; nothing is kept open.
|
||||
#include <dlfcn.h>
|
||||
#include <jni.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#define VK_NO_PROTOTYPES
|
||||
#include <vulkan/vulkan.h>
|
||||
|
||||
#define LINE(...) do { if (used < sizeof(out)) used += snprintf(out + used, sizeof(out) - used, __VA_ARGS__); } while (0)
|
||||
|
||||
static const char *const EXTENSIONS[] = {
|
||||
"VK_EXT_robustness2", "VK_EXT_transform_feedback", "VK_EXT_custom_border_color",
|
||||
"VK_KHR_dynamic_rendering", "VK_EXT_extended_dynamic_state3", "VK_EXT_descriptor_indexing",
|
||||
"VK_KHR_timeline_semaphore", "VK_EXT_mesh_shader", "VK_KHR_ray_query",
|
||||
};
|
||||
|
||||
static const char *type_name(VkPhysicalDeviceType type) {
|
||||
switch (type) {
|
||||
case VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU: return "integrated GPU";
|
||||
case VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU: return "discrete GPU";
|
||||
case VK_PHYSICAL_DEVICE_TYPE_VIRTUAL_GPU: return "virtual GPU";
|
||||
case VK_PHYSICAL_DEVICE_TYPE_CPU: return "CPU";
|
||||
default: return "other";
|
||||
}
|
||||
}
|
||||
|
||||
JNIEXPORT jstring JNICALL
|
||||
Java_com_droiddeck_launcher_gpu_VulkanInfo_nativeQuery(JNIEnv *env, jclass clazz) {
|
||||
static char out[4096];
|
||||
size_t used = 0;
|
||||
out[0] = 0;
|
||||
void *lib = dlopen("libvulkan.so", RTLD_NOW | RTLD_LOCAL);
|
||||
if (!lib) { LINE("error=no Vulkan loader\n"); return (*env)->NewStringUTF(env, out); }
|
||||
PFN_vkGetInstanceProcAddr gipa = (PFN_vkGetInstanceProcAddr) dlsym(lib, "vkGetInstanceProcAddr");
|
||||
PFN_vkCreateInstance create = gipa ? (PFN_vkCreateInstance) gipa(NULL, "vkCreateInstance") : NULL;
|
||||
PFN_vkEnumerateInstanceVersion instanceVersion = gipa ? (PFN_vkEnumerateInstanceVersion) gipa(NULL, "vkEnumerateInstanceVersion") : NULL;
|
||||
if (!create) { LINE("error=no vkCreateInstance\n"); dlclose(lib); return (*env)->NewStringUTF(env, out); }
|
||||
uint32_t loader = VK_API_VERSION_1_0;
|
||||
if (instanceVersion) instanceVersion(&loader);
|
||||
LINE("loader=%u.%u.%u\n", VK_API_VERSION_MAJOR(loader), VK_API_VERSION_MINOR(loader), VK_API_VERSION_PATCH(loader));
|
||||
|
||||
VkApplicationInfo app = { .sType = VK_STRUCTURE_TYPE_APPLICATION_INFO, .pApplicationName = "DroidDeck device info",
|
||||
.apiVersion = loader >= VK_API_VERSION_1_1 ? VK_API_VERSION_1_1 : VK_API_VERSION_1_0 };
|
||||
VkInstanceCreateInfo info = { .sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO, .pApplicationInfo = &app };
|
||||
VkInstance instance = VK_NULL_HANDLE;
|
||||
if (create(&info, NULL, &instance) != VK_SUCCESS) { LINE("error=vkCreateInstance failed\n"); dlclose(lib); return (*env)->NewStringUTF(env, out); }
|
||||
|
||||
#define GET(name) PFN_##name name = (PFN_##name) gipa(instance, #name)
|
||||
GET(vkDestroyInstance); GET(vkEnumeratePhysicalDevices); GET(vkGetPhysicalDeviceProperties);
|
||||
GET(vkGetPhysicalDeviceProperties2); GET(vkGetPhysicalDeviceMemoryProperties);
|
||||
GET(vkEnumerateDeviceExtensionProperties); GET(vkGetPhysicalDeviceFeatures);
|
||||
uint32_t count = 1;
|
||||
VkPhysicalDevice device = VK_NULL_HANDLE;
|
||||
VkResult listed = vkEnumeratePhysicalDevices ? vkEnumeratePhysicalDevices(instance, &count, &device) : VK_ERROR_INITIALIZATION_FAILED;
|
||||
if ((listed != VK_SUCCESS && listed != VK_INCOMPLETE) || count == 0 || !device || !vkGetPhysicalDeviceProperties) {
|
||||
LINE("error=no Vulkan device\n");
|
||||
} else {
|
||||
VkPhysicalDeviceProperties p;
|
||||
vkGetPhysicalDeviceProperties(device, &p);
|
||||
LINE("device=%s\n", p.deviceName);
|
||||
LINE("type=%s\n", type_name(p.deviceType));
|
||||
LINE("api=%u.%u.%u\n", VK_API_VERSION_MAJOR(p.apiVersion), VK_API_VERSION_MINOR(p.apiVersion), VK_API_VERSION_PATCH(p.apiVersion));
|
||||
// Qualcomm packs its driver version as 10.10.12 bits, the same layout as VK_MAKE_VERSION.
|
||||
LINE("driver_version=%u.%u.%u\n", p.driverVersion >> 22, (p.driverVersion >> 12) & 0x3ff, p.driverVersion & 0xfff);
|
||||
LINE("vendor_id=0x%04x\ndevice_id=0x%08x\n", p.vendorID, p.deviceID);
|
||||
LINE("max_image_2d=%u\n", p.limits.maxImageDimension2D);
|
||||
|
||||
// Driver name and build string (Vulkan 1.2 or VK_KHR_driver_properties).
|
||||
uint32_t extCount = 0;
|
||||
if (vkEnumerateDeviceExtensionProperties) vkEnumerateDeviceExtensionProperties(device, NULL, &extCount, NULL);
|
||||
static VkExtensionProperties exts[512];
|
||||
if (extCount > 512) extCount = 512;
|
||||
if (extCount && vkEnumerateDeviceExtensionProperties) vkEnumerateDeviceExtensionProperties(device, NULL, &extCount, exts);
|
||||
int driverProps = p.apiVersion >= VK_API_VERSION_1_2;
|
||||
for (uint32_t i = 0; i < extCount; i++)
|
||||
if (!strcmp(exts[i].extensionName, "VK_KHR_driver_properties")) driverProps = 1;
|
||||
if (driverProps && vkGetPhysicalDeviceProperties2) {
|
||||
VkPhysicalDeviceDriverProperties driver = { .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES };
|
||||
VkPhysicalDeviceProperties2 p2 = { .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, .pNext = &driver };
|
||||
vkGetPhysicalDeviceProperties2(device, &p2);
|
||||
LINE("driver_name=%s\n", driver.driverName);
|
||||
LINE("driver_info=%s\n", driver.driverInfo);
|
||||
LINE("conformance=%u.%u.%u.%u\n", driver.conformanceVersion.major, driver.conformanceVersion.minor,
|
||||
driver.conformanceVersion.subminor, driver.conformanceVersion.patch);
|
||||
}
|
||||
LINE("extension_count=%u\n", extCount);
|
||||
for (size_t e = 0; e < sizeof(EXTENSIONS) / sizeof(*EXTENSIONS); e++) {
|
||||
int has = 0;
|
||||
for (uint32_t i = 0; i < extCount && !has; i++) has = !strcmp(exts[i].extensionName, EXTENSIONS[e]);
|
||||
LINE("ext.%s=%s\n", EXTENSIONS[e], has ? "yes" : "no");
|
||||
}
|
||||
if (vkGetPhysicalDeviceFeatures) {
|
||||
VkPhysicalDeviceFeatures f;
|
||||
vkGetPhysicalDeviceFeatures(device, &f);
|
||||
LINE("geometry_shader=%s\ntessellation_shader=%s\ntexture_bc=%s\n",
|
||||
f.geometryShader ? "yes" : "no", f.tessellationShader ? "yes" : "no", f.textureCompressionBC ? "yes" : "no");
|
||||
}
|
||||
if (vkGetPhysicalDeviceMemoryProperties) {
|
||||
VkPhysicalDeviceMemoryProperties m;
|
||||
vkGetPhysicalDeviceMemoryProperties(device, &m);
|
||||
VkDeviceSize largest = 0;
|
||||
for (uint32_t i = 0; i < m.memoryHeapCount; i++)
|
||||
if ((m.memoryHeaps[i].flags & VK_MEMORY_HEAP_DEVICE_LOCAL_BIT) && m.memoryHeaps[i].size > largest) largest = m.memoryHeaps[i].size;
|
||||
LINE("device_heap_mb=%llu\n", (unsigned long long) (largest >> 20));
|
||||
}
|
||||
}
|
||||
if (vkDestroyInstance) vkDestroyInstance(instance, NULL);
|
||||
dlclose(lib);
|
||||
return (*env)->NewStringUTF(env, out);
|
||||
}
|
||||
@@ -155,7 +155,6 @@ class MainActivity : ComponentActivity() {
|
||||
private var showPhantomGate by mutableStateOf(false)
|
||||
private var directAudio by mutableStateOf(false)
|
||||
private var clientDirectAudio by mutableStateOf(false)
|
||||
private var forceFullscreen by mutableStateOf(false)
|
||||
private var stretch16x9 by mutableStateOf(false)
|
||||
private var launcherFullscreen by mutableStateOf(true)
|
||||
private var animationsEnabled by mutableStateOf(true)
|
||||
@@ -311,6 +310,7 @@ class MainActivity : ComponentActivity() {
|
||||
private var settingsMode by mutableStateOf<String?>(null)
|
||||
private var resolution by mutableStateOf(com.droiddeck.launcher.session.SessionDisplay.DEFAULT_RESOLUTION)
|
||||
private var fexPreset by mutableStateOf("")
|
||||
private var forceSsbs by mutableStateOf(false)
|
||||
private var steamChannel by mutableStateOf("steamdeck_publicbeta")
|
||||
private var runSteamAtStartup by mutableStateOf(false)
|
||||
private var theme by mutableStateOf("graphite")
|
||||
@@ -327,6 +327,7 @@ class MainActivity : ComponentActivity() {
|
||||
private var renderer by mutableStateOf("vulkan")
|
||||
private var gameStorage by mutableStateOf("")
|
||||
private var storageDiagnostics by mutableStateOf(false)
|
||||
private var skipPreallocation by mutableStateOf(false)
|
||||
private var storageOptions by mutableStateOf<List<Pair<String, String>>>(emptyList())
|
||||
private val pickGameStorage = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
|
||||
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedPath(r.data)?.let { path -> setGameStorage(path, GameStorage.labelFor(this, path)) }
|
||||
@@ -440,7 +441,7 @@ class MainActivity : ComponentActivity() {
|
||||
}
|
||||
}
|
||||
|
||||
private fun launchGame(game: Library.SteamGame): Boolean {
|
||||
private fun launchGame(game: Library.SteamGame, returnHome: Boolean = false): Boolean {
|
||||
if (protons.protonBusyId != null || ProtonExtras.installInProgress || pkgStage != null) {
|
||||
android.widget.Toast.makeText(this, "Wait for the install to finish before launching a game", android.widget.Toast.LENGTH_SHORT).show()
|
||||
return false
|
||||
@@ -455,10 +456,12 @@ class MainActivity : ComponentActivity() {
|
||||
return false
|
||||
}
|
||||
startActivity(Intent(this, SessionActivity::class.java).setAction(SessionService.ACTION_RESUME)
|
||||
.putExtra(SessionActivity.EXTRA_RETURN_HOME, returnHome)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP))
|
||||
return true
|
||||
}
|
||||
return startSession(Intent(this, SessionActivity::class.java)
|
||||
.putExtra(SessionActivity.EXTRA_RETURN_HOME, returnHome)
|
||||
.putExtra(SessionService.EXTRA_STEAM_URL,
|
||||
com.droiddeck.launcher.frontend.GameLaunchLink.steamUrl(game.gameIdString)), steamSession = true)
|
||||
}
|
||||
@@ -473,7 +476,7 @@ class MainActivity : ComponentActivity() {
|
||||
intent.action = Intent.ACTION_MAIN
|
||||
intent.removeExtra(GameLaunchIntent.EXTRA_APP_ID)
|
||||
android.widget.Toast.makeText(this, R.string.game_link_missing, android.widget.Toast.LENGTH_LONG).show()
|
||||
} else if (launchGame(game)) {
|
||||
} else if (launchGame(game, returnHome = true)) {
|
||||
pendingGameLink = null
|
||||
intent.data = null
|
||||
intent.action = Intent.ACTION_MAIN
|
||||
@@ -636,13 +639,10 @@ class MainActivity : ComponentActivity() {
|
||||
logsEnabled = SessionPrefs.logsEnabled(this)
|
||||
},
|
||||
onShareLogs = {
|
||||
Thread({
|
||||
val zip = runCatching { SessionLogShare.zipLatest(this) }.getOrNull()
|
||||
ui.post {
|
||||
if (zip == null) android.widget.Toast.makeText(this, "No session logs yet: run a session first.", android.widget.Toast.LENGTH_LONG).show()
|
||||
else startActivity(SessionLogShare.shareIntent(this, zip))
|
||||
}
|
||||
}, "share-logs").start()
|
||||
SessionLogShare.prepare(this, { SessionLogShare.latest(this) }) { zip ->
|
||||
if (zip == null) android.widget.Toast.makeText(this, "No session logs yet: run a session first.", android.widget.Toast.LENGTH_LONG).show()
|
||||
else startActivity(SessionLogShare.shareIntent(this, zip))
|
||||
}
|
||||
},
|
||||
onClearLogs = {
|
||||
Thread({
|
||||
@@ -1149,14 +1149,15 @@ class MainActivity : ComponentActivity() {
|
||||
backActionsInverted = backActionsInverted,
|
||||
directAudio = if (mode == SessionService.MODE_STEAM) directAudio else null,
|
||||
clientDirectAudio = clientDirectAudio,
|
||||
forceFullscreen = if (mode == SessionService.MODE_STEAM) forceFullscreen else null,
|
||||
stretch16x9 = if (mode == SessionService.MODE_STEAM) stretch16x9 else null,
|
||||
mic = if (mode == SessionService.MODE_STEAM) mic else null,
|
||||
renderer = if (mode == SessionService.MODE_DESKTOP) renderer else null,
|
||||
gameStorage = if (mode == SessionService.MODE_STEAM) gameStorage else null,
|
||||
storageOptions = storageOptions,
|
||||
storageDiagnostics = mode == SessionService.MODE_STEAM && storageDiagnostics,
|
||||
skipPreallocation = mode == SessionService.MODE_STEAM && skipPreallocation,
|
||||
fexPreset = if (mode == SessionService.MODE_STEAM) fexPreset else null,
|
||||
forceSsbs = forceSsbs,
|
||||
syncBackend = if (mode == SessionService.MODE_STEAM) SessionPrefs.syncBackendOf(fastSync, fsyncFirst, syncFallback) else null,
|
||||
steamChannel = if (mode == SessionService.MODE_STEAM) steamChannel else null,
|
||||
steamDeckMode = mode == SessionService.MODE_STEAM && steamDeckMode,
|
||||
@@ -1209,7 +1210,6 @@ class MainActivity : ComponentActivity() {
|
||||
},
|
||||
onDirectAudio = { on -> SessionPrefs.setDirectAudio(this, on); directAudio = on },
|
||||
onClientDirectAudio = { on -> SessionPrefs.setClientDirectAudio(this, on); clientDirectAudio = on },
|
||||
onForceFullscreen = { on -> SessionPrefs.setForceFullscreen(this, on); forceFullscreen = on },
|
||||
onStretch16x9 = { on -> SessionPrefs.setStretch16x9(this, on); stretch16x9 = on },
|
||||
onMic = { on ->
|
||||
SessionPrefs.setMicEnabled(this, on)
|
||||
@@ -1229,7 +1229,12 @@ class MainActivity : ComponentActivity() {
|
||||
SessionPrefs.setStorageDiagnosticsEnabled(this, on)
|
||||
storageDiagnostics = on
|
||||
},
|
||||
onSkipPreallocation = { on ->
|
||||
SessionPrefs.setSkipLibraryPreallocation(this, on)
|
||||
skipPreallocation = on
|
||||
},
|
||||
onFexPreset = { id -> SessionPrefs.setFexPreset(this, id); fexPreset = id },
|
||||
onForceSsbs = { on -> SessionPrefs.setForceSsbs(this, on); forceSsbs = on },
|
||||
onSyncBackend = { id ->
|
||||
SessionPrefs.setSyncBackend(this, id)
|
||||
fastSync = SessionPrefs.fastSync(this)
|
||||
@@ -1351,6 +1356,7 @@ class MainActivity : ComponentActivity() {
|
||||
showMapping = false
|
||||
resolution = SessionPrefs.resolutionChoice(this, mode, com.droiddeck.launcher.session.SessionDisplay.panelSize(this))
|
||||
fexPreset = SessionPrefs.fexPreset(this)
|
||||
forceSsbs = SessionPrefs.forceSsbs(this)
|
||||
fastSync = SessionPrefs.fastSync(this)
|
||||
fsyncFirst = SessionPrefs.fsyncFirst(this)
|
||||
syncFallback = SessionPrefs.syncFallback(this)
|
||||
@@ -1372,13 +1378,13 @@ class MainActivity : ComponentActivity() {
|
||||
backActionsInverted = SessionPrefs.backActionsInverted(this)
|
||||
directAudio = SessionPrefs.directAudio(this)
|
||||
clientDirectAudio = SessionPrefs.clientDirectAudio(this)
|
||||
forceFullscreen = SessionPrefs.forceFullscreen(this)
|
||||
stretch16x9 = SessionPrefs.stretch16x9(this)
|
||||
mic = SessionPrefs.micEnabled(this)
|
||||
refreshWifiDiscovery()
|
||||
renderer = SessionPrefs.desktopRenderer(this)
|
||||
gameStorage = SessionPrefs.gameStorage(this)
|
||||
storageDiagnostics = SessionPrefs.storageDiagnosticsEnabled(this)
|
||||
skipPreallocation = SessionPrefs.skipLibraryPreallocation(this)
|
||||
settingsMode = mode
|
||||
// The page opens at once, on what was last read; the slow part (driver files, a walk of the
|
||||
// added-games folders, the storage volumes) lands while it animates in.
|
||||
|
||||
@@ -229,7 +229,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
/** The on-screen PC keyboard (ui/PcKeyboard): real key presses, Esc and F1 included. */
|
||||
private var pcKeyboardOpen by mutableStateOf(false)
|
||||
private var hudOn by mutableStateOf(true)
|
||||
private var fillScreen by mutableStateOf(true)
|
||||
private var upscaler by mutableStateOf(0)
|
||||
private var upscaleSharpness by mutableStateOf(75)
|
||||
private var effects by mutableStateOf(ScreenEffects.OFF)
|
||||
@@ -501,7 +500,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
isHomeApp = isHomeApp,
|
||||
androidApps = androidApps,
|
||||
hudOn = hudOn,
|
||||
fillScreen = if (SessionState.mode == SessionService.MODE_STEAM) fillScreen else null,
|
||||
upscaler = upscaler, upscaleSharpness = upscaleSharpness,
|
||||
effects = effects, textureAnisotropy = textureAnisotropy, textureLodBias = textureLodBias,
|
||||
frameGen = frameGen,
|
||||
@@ -513,7 +511,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
secondScreenDisplays = secondScreenDisplays,
|
||||
selectedSecondScreenDisplay = selectedSecondScreenDisplay,
|
||||
onHud = { on -> SessionPrefs.setHudEnabled(this@SessionActivity, on); hudOn = on; hud.refresh() },
|
||||
onFillScreen = { on -> SessionPrefs.setForceFullscreen(this@SessionActivity, on); fillScreen = on },
|
||||
onUpscaler = { m ->
|
||||
SessionPrefs.setUpscaler(this@SessionActivity, m); upscaler = m
|
||||
WaylandCompositor.nativeSetUpscaler(m)
|
||||
@@ -744,28 +741,22 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
Toast.makeText(this, "No logs for this session.", Toast.LENGTH_LONG).show()
|
||||
return
|
||||
}
|
||||
Thread({
|
||||
val zip = runCatching { SessionLogShare.zipFolder(this, folder) }
|
||||
.onFailure { Log.w(TAG, "could not package current session logs", it) }
|
||||
.getOrNull()
|
||||
uiHandler.post {
|
||||
if (zip == null) {
|
||||
Toast.makeText(this, "Could not create the session log archive.", Toast.LENGTH_LONG).show()
|
||||
} else {
|
||||
runCatching { startActivity(SessionLogShare.shareIntent(this, zip)) }
|
||||
.onFailure {
|
||||
Log.w(TAG, "could not share current session logs", it)
|
||||
Toast.makeText(this, "Could not share the session logs.", Toast.LENGTH_LONG).show()
|
||||
}
|
||||
}
|
||||
SessionLogShare.prepare(this, { folder }) { zip ->
|
||||
if (zip == null) {
|
||||
Toast.makeText(this, "Could not create the session log archive.", Toast.LENGTH_LONG).show()
|
||||
} else {
|
||||
runCatching { startActivity(SessionLogShare.shareIntent(this, zip)) }
|
||||
.onFailure {
|
||||
Log.w(TAG, "could not share current session logs", it)
|
||||
Toast.makeText(this, "Could not share the session logs.", Toast.LENGTH_LONG).show()
|
||||
}
|
||||
}
|
||||
}, "share-session-logs").start()
|
||||
}
|
||||
}
|
||||
|
||||
private fun readPrefs() {
|
||||
pipAutoEnter = SessionPrefs.pipAutoEnter(this)
|
||||
hudOn = SessionPrefs.hudEnabled(this)
|
||||
fillScreen = SessionPrefs.forceFullscreen(this)
|
||||
upscaler = SessionPrefs.upscaler(this)
|
||||
upscaleSharpness = SessionPrefs.upscaleSharpness(this)
|
||||
effects = SessionPrefs.screenEffects(this)
|
||||
@@ -1145,6 +1136,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
// the request landed in this instance's onNewIntent and went with its finish().
|
||||
SessionState.relaunch?.let { next ->
|
||||
SessionState.relaunch = null
|
||||
next.putExtra(EXTRA_RETURN_HOME, intent.getBooleanExtra(EXTRA_RETURN_HOME, false))
|
||||
setIntent(next)
|
||||
recreate()
|
||||
return@runOnUiThread
|
||||
@@ -1906,6 +1898,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
recreate()
|
||||
return
|
||||
}
|
||||
// Home/notification resumes must retain the external frontend's return destination.
|
||||
if (this.intent.getBooleanExtra(EXTRA_RETURN_HOME, false)) intent.putExtra(EXTRA_RETURN_HOME, true)
|
||||
setIntent(intent)
|
||||
if (intent.action == SessionService.ACTION_HOME_GUIDE) {
|
||||
handleHomeGuideIntent(intent)
|
||||
@@ -2046,6 +2040,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
* off, it just closes.
|
||||
*/
|
||||
override fun finish() {
|
||||
if (isFinishing) return
|
||||
if (!quitFlooded && !closeAtOnce && com.droiddeck.launcher.ui.Motion.scale != 0f &&
|
||||
lifecycle.currentState.isAtLeast(androidx.lifecycle.Lifecycle.State.RESUMED)) {
|
||||
if (!leaving) {
|
||||
@@ -2056,6 +2051,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
return
|
||||
}
|
||||
super.finish()
|
||||
if (!closeAtOnce && intent.getBooleanExtra(EXTRA_RETURN_HOME, false)) {
|
||||
com.droiddeck.launcher.ui.QuitFlood.take()
|
||||
com.droiddeck.launcher.ui.LaunchOrigin.flooding = null
|
||||
startActivity(Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_HOME)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
|
||||
}
|
||||
if (quitFlooded) overridePendingTransition(0, 0)
|
||||
else overridePendingTransition(R.anim.session_hold, R.anim.session_sink)
|
||||
}
|
||||
@@ -2071,6 +2072,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val EXTRA_RETURN_HOME = "returnHome"
|
||||
/** How long the leaving flood may take before the session closes without it. */
|
||||
private const val LEAVE_TIMEOUT_MS = 1_500L
|
||||
private const val TAG = "SessionActivity"
|
||||
|
||||
@@ -109,8 +109,11 @@ object DeviceReport {
|
||||
k("Session output", SessionState.outputSize?.let { "${it.first}x${it.second}" })
|
||||
k("Session refresh", String.format(Locale.US, "%.2f Hz", SessionState.refreshHz))
|
||||
val panelSize = com.droiddeck.launcher.session.SessionDisplay.panelSize(context)
|
||||
k("Resolution (Steam)", SessionPrefs.resolutionChoice(context, SessionService.MODE_STEAM, panelSize))
|
||||
k("Resolution (Desktop)", SessionPrefs.resolutionChoice(context, SessionService.MODE_DESKTOP, panelSize))
|
||||
for ((label, mode) in listOf("Resolution (Steam)" to SessionService.MODE_STEAM, "Resolution (Desktop)" to SessionService.MODE_DESKTOP)) {
|
||||
val choice = SessionPrefs.resolutionChoice(context, mode, panelSize)
|
||||
val size = com.droiddeck.launcher.session.SessionDisplay.resolveChoice(panelSize, choice)
|
||||
k(label, "$choice (${size.first}x${size.second})")
|
||||
}
|
||||
k("Foldable", context.packageManager.hasSystemFeature("android.hardware.sensor.hinge_angle"))
|
||||
|
||||
h("Drivers")
|
||||
@@ -163,7 +166,6 @@ object DeviceReport {
|
||||
k("proot fast path", SessionPrefs.prootFastPath(context))
|
||||
k("Guest host name", SessionPrefs.guestHostname(context))
|
||||
k("DirectAudio for games", SessionPrefs.directAudio(context))
|
||||
k("Stretch games to fill", SessionPrefs.forceFullscreen(context))
|
||||
k("Stretch 16:9 to panel", SessionPrefs.stretch16x9(context))
|
||||
k("Client audio", if (SessionPrefs.clientDirectAudio(context)) "DirectAudio" else "classic")
|
||||
k("Microphone", SessionPrefs.micEnabled(context))
|
||||
@@ -175,6 +177,7 @@ object DeviceReport {
|
||||
SessionPrefs.GAME_STORAGE_OFF -> "internal only"
|
||||
else -> g
|
||||
})
|
||||
k("Skip space reservation", SessionPrefs.skipLibraryPreallocation(context))
|
||||
|
||||
h("Android process limits")
|
||||
k("Phantom proc monitor", PhantomProcessLimit.reportValue(PhantomProcessLimit.read(context)))
|
||||
|
||||
@@ -25,7 +25,7 @@ object GameEnvironment {
|
||||
fun validValue(value: String) = '\u0000' !in value && value.length <= 8192
|
||||
fun validScope(scope: String) = scope.isEmpty() || (Regex("[1-9][0-9]*").matches(scope) && scope.toLongOrNull()?.let { it in 1..4294967295L } == true)
|
||||
|
||||
fun defaults(preset: String): Map<String, String?> = linkedMapOf<String, String?>(
|
||||
fun defaults(preset: String, forceSsbs: Boolean = false): Map<String, String?> = linkedMapOf<String, String?>(
|
||||
"MESA_SHADER_CACHE_DISABLE" to "false",
|
||||
"VKD3D_FEATURE_LEVEL" to "12_2",
|
||||
"VKD3D_SHADER_MODEL" to "6_9",
|
||||
@@ -37,8 +37,12 @@ object GameEnvironment {
|
||||
"DOTNET_EnableWriteXorExecute" to "0",
|
||||
).apply {
|
||||
FexPreset.env(preset).forEach { put(it.substringBefore('='), it.substringAfter('=')) }
|
||||
// Steam settings' Force SSBS: droiddeck-game-env preloads libssbs.so into the game's Wine.
|
||||
if (forceSsbs) put(FORCE_SSBS, "1")
|
||||
}
|
||||
|
||||
fun effective(config: Config, preset: String, scope: String): Map<String, String?> =
|
||||
defaults(preset) + config.shared + if (scope.isEmpty()) emptyMap() else config.games[scope].orEmpty()
|
||||
const val FORCE_SSBS = "DROIDDECK_FORCE_SSBS"
|
||||
|
||||
fun effective(config: Config, preset: String, scope: String, forceSsbs: Boolean = false): Map<String, String?> =
|
||||
defaults(preset, forceSsbs) + config.shared + if (scope.isEmpty()) emptyMap() else config.games[scope].orEmpty()
|
||||
}
|
||||
@@ -190,6 +190,14 @@ object LogRedactor {
|
||||
false
|
||||
}
|
||||
|
||||
/**
|
||||
* Bump whenever a pattern is added or tightened. A session folder records the version it was
|
||||
* scrubbed under (SessionArtifacts.SCRUBBED_TREE_MARKER), and a share copies a file as it is
|
||||
* only when that matches, so a folder scrubbed under older rules is scrubbed again on the way
|
||||
* out.
|
||||
*/
|
||||
const val RULES_VERSION = 1
|
||||
|
||||
/** [src]'s lines, scrubbed, to [out]. */
|
||||
fun scrubTo(src: java.io.File, out: java.io.Writer) {
|
||||
src.forEachLine { line -> out.write(redact(line)); out.write("\n") }
|
||||
|
||||
@@ -0,0 +1,253 @@
|
||||
package com.droiddeck.launcher.frontend
|
||||
|
||||
import java.io.File
|
||||
import java.util.Locale
|
||||
|
||||
/**
|
||||
* Best-effort detection of the Windows redistributables a game bundles, by scanning its install
|
||||
* folder for the redist installers Steam/Epic/GOG ship (`_CommonRedist/`, `_Redist/`,
|
||||
* `Redistributables/`, loose `vcredist_x64.exe`, …) and mapping them to entries in our component
|
||||
* catalog (WinComponents, Bannerlator's components.json `name` keys). The result drives the
|
||||
* Recommended part of a game's Windows components; the user still switches each one on.
|
||||
* Bannerlator's detector, unchanged but for this note and its package.
|
||||
*
|
||||
* Wine-aware: keeps the redists that actually matter under Wine/DXVK (VC++ runtimes, .NET, PhysX,
|
||||
* OpenAL, XACT, XNA, GFWL) and SKIPS the ones DXVK/VKD3D already provide (DX12 Agility SDK) or that
|
||||
* aren't our components (anti-cheat, Rockstar/Social-Club/launcher setups). Never throws; returns an
|
||||
* empty list on anything unexpected. Pure filesystem — no network, no Android deps (unit-testable).
|
||||
*/
|
||||
object DependencyDetector {
|
||||
|
||||
/** How a recommendation was found — drives the UI's "recommended vs optional" split. */
|
||||
enum class Kind {
|
||||
/** The game bundles the redist installer (in _CommonRedist etc.) — meant to be installed. */
|
||||
BUNDLED,
|
||||
/** A runtime DLL the game ships loose — usually already works from the game folder; install
|
||||
* only if the game misbehaves. */
|
||||
SHIPPED,
|
||||
/** Steam installs it with the game from Steamworks Shared ([SteamRedists]). */
|
||||
STEAM,
|
||||
}
|
||||
|
||||
/** A recommended component: the catalog [componentName] to install, a display [label], the on-disk
|
||||
* redist that triggered it ([reason]), and [kind] (bundled installer vs shipped DLL). */
|
||||
data class Recommendation(val componentName: String, val label: String, val reason: String, val kind: Kind = Kind.BUNDLED)
|
||||
|
||||
private const val MAX_DEPTH = 5
|
||||
private const val MAX_ENTRIES = 8000 // cost guard against giant game trees
|
||||
|
||||
/** A loose VC++ installer with no year in its path — resolved to "latest" only if no specific
|
||||
* vcredistYYYY was found anywhere (else it's just a duplicate of the versioned one). */
|
||||
private const val VCREDIST_LOOSE = "__vcredist_loose"
|
||||
|
||||
/** Directory names that are redist containers worth descending into. */
|
||||
private val REDIST_DIR_RE = Regex(
|
||||
"""(?i)^(_?commonredist|_?redist(ributables)?|__?installer|vcredist|vc_redist|directx|direct_x|physx|openal|dotnet(fx)?|\.net|xna|xact|redist|support)$"""
|
||||
)
|
||||
|
||||
/** Skip whole subtrees that are never our components. */
|
||||
private val SKIP_DIR_RE = Regex("""(?i)^(d3d12.*|.*agility.*|dxvk|vkd3d|battleye|easyanticheat|eac|anticheat)$""")
|
||||
|
||||
private val YEAR_TO_VCREDIST = mapOf(
|
||||
"2005" to "vcredist2005", "2008" to "vcredist2008", "2010" to "vcredist2010",
|
||||
"2012" to "vcredist2012", "2013" to "vcredist2013", "2015" to "vcredist2015",
|
||||
"2017" to "vcredist2015", "2019" to "vcredist2019", "2022" to "vcredist2022",
|
||||
)
|
||||
|
||||
private val LABELS = mapOf(
|
||||
"vcredist2005" to "Visual C++ 2005", "vcredist2008" to "Visual C++ 2008",
|
||||
"vcredist2010" to "Visual C++ 2010", "vcredist2012" to "Visual C++ 2012",
|
||||
"vcredist2013" to "Visual C++ 2013", "vcredist2015" to "Visual C++ 2015-2017",
|
||||
"vcredist2019" to "Visual C++ 2019", "vcredist2022" to "Visual C++ 2015-2022",
|
||||
"physx" to "NVIDIA PhysX", "oalinst" to "OpenAL", "xact" to "DirectX XACT audio",
|
||||
"xact_x64" to "DirectX XACT audio (x64)", "xna40" to "XNA Framework 4.0",
|
||||
"xna31" to "XNA Framework 3.1", "d3dx9" to "DirectX 9 (d3dx9)", "d3dx11" to "DirectX 11 (d3dx11)",
|
||||
"XLiveRedist" to "Games for Windows Live", "dotnet40" to ".NET Framework 4.0",
|
||||
"dotnet45" to ".NET Framework 4.5", "dotnet452" to ".NET Framework 4.5.2",
|
||||
"dotnet46" to ".NET Framework 4.6", "dotnet472" to ".NET Framework 4.7.2",
|
||||
"dotnet48" to ".NET Framework 4.8", "dotnet35" to ".NET Framework 3.5",
|
||||
"dotnetcoredesktop6" to ".NET Desktop 6", "dotnetcoredesktop7" to ".NET Desktop 7",
|
||||
"dotnetcoredesktop8" to ".NET Desktop 8",
|
||||
)
|
||||
|
||||
/** Preferred install order (runtimes others may depend on first). */
|
||||
private val INSTALL_ORDER = listOf(
|
||||
"vcredist2005", "vcredist2008", "vcredist2010", "vcredist2012", "vcredist2013",
|
||||
"vcredist2015", "vcredist2019", "vcredist2022",
|
||||
"dotnet35", "dotnet40", "dotnet45", "dotnet452", "dotnet46", "dotnet472", "dotnet48",
|
||||
"dotnetcoredesktop6", "dotnetcoredesktop7", "dotnetcoredesktop8",
|
||||
"d3dx9", "d3dx11", "xact", "xact_x64", "xna31", "xna40", "physx", "oalinst", "XLiveRedist",
|
||||
)
|
||||
|
||||
/**
|
||||
* Detect from the .exe the user picked, resolving the game root first: walk up from the exe's
|
||||
* folder (bounded) to the nearest ancestor that holds a redist container (`_CommonRedist`, …) at
|
||||
* its top level, and scan from there — so a nested exe (`…/Game/bin/x.exe`) still finds a root-level
|
||||
* `_CommonRedist`, without over-reaching into a shared `steamapps/common` (which has no redist
|
||||
* container of its own). Falls back to scanning the exe's own folder.
|
||||
*/
|
||||
fun detectForExe(exeFile: File): List<Recommendation> {
|
||||
val start = exeFile.absoluteFile.parentFile ?: return emptyList()
|
||||
var d: File? = start
|
||||
var depth = 0
|
||||
while (d != null && depth < 4) {
|
||||
val hasRedistContainer = try {
|
||||
d.listFiles()?.any { it.isDirectory && REDIST_DIR_RE.matches(it.name.lowercase(Locale.US)) } == true
|
||||
} catch (_: Throwable) { false }
|
||||
if (hasRedistContainer) return detect(d)
|
||||
d = d.parentFile
|
||||
depth++
|
||||
}
|
||||
return detect(start)
|
||||
}
|
||||
|
||||
/**
|
||||
* Scan [gameDir] and return the recommended components, de-duplicated (first reason wins), in a
|
||||
* stable install-friendly order. Empty when nothing is detected or [gameDir] isn't a directory.
|
||||
*/
|
||||
fun detect(gameDir: File): List<Recommendation> {
|
||||
if (!gameDir.isDirectory) return emptyList()
|
||||
val hits = LinkedHashMap<String, Recommendation>() // componentName -> first recommendation
|
||||
var visited = 0
|
||||
|
||||
fun consider(f: File, isDir: Boolean, insideRedist: Boolean) {
|
||||
val name = f.name.lowercase(Locale.US)
|
||||
val path = f.path.replace('\\', '/').lowercase(Locale.US)
|
||||
// Bundled = in a redist container or an installer (exe/msi/cab); shipped = a loose runtime DLL.
|
||||
val kind = if (insideRedist || isDir || name.endsWith(".exe") || name.endsWith(".msi") || name.endsWith(".cab"))
|
||||
Kind.BUNDLED else Kind.SHIPPED
|
||||
for (comp in classify(path, name, isDir)) {
|
||||
val existing = hits[comp]
|
||||
if (existing == null) {
|
||||
hits[comp] = Recommendation(comp, LABELS[comp] ?: comp, relativeReason(gameDir, f), kind)
|
||||
} else if (existing.kind == Kind.SHIPPED && kind == Kind.BUNDLED) {
|
||||
hits[comp] = existing.copy(kind = Kind.BUNDLED) // a bundled installer outranks a shipped DLL
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun walk(dir: File, depth: Int, insideRedist: Boolean) {
|
||||
if (depth > MAX_DEPTH || visited > MAX_ENTRIES) return
|
||||
val entries = dir.listFiles() ?: return
|
||||
for (f in entries) {
|
||||
if (visited++ > MAX_ENTRIES) return
|
||||
val lower = f.name.lowercase(Locale.US)
|
||||
if (f.isDirectory) {
|
||||
if (SKIP_DIR_RE.matches(lower)) continue
|
||||
val isRedistDir = insideRedist || REDIST_DIR_RE.matches(lower)
|
||||
if (isRedistDir) consider(f, isDir = true, insideRedist = true)
|
||||
// Aggressive coverage: descend redist containers fully, and otherwise sweep the game
|
||||
// tree a few levels deep so runtime libraries the game ships (in bin/, etc.) are seen.
|
||||
if (isRedistDir || depth < 3) walk(f, depth + 1, isRedistDir)
|
||||
} else {
|
||||
// Classify installers + runtime libraries (.dll/.exe/.msi) anywhere in the scanned
|
||||
// tree; other files are ignored. Recommendations are advisory, so cast a wide net.
|
||||
val ext = lower.substringAfterLast('.', "")
|
||||
if (insideRedist || ext == "dll" || ext == "exe" || ext == "msi") consider(f, isDir = false, insideRedist = insideRedist)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return try {
|
||||
walk(gameDir, 0, false)
|
||||
resolveLooseVcredist(hits)
|
||||
hits.values.sortedBy { INSTALL_ORDER.indexOf(it.componentName).let { i -> if (i < 0) 999 else i } }
|
||||
} catch (_: Throwable) {
|
||||
emptyList()
|
||||
}
|
||||
}
|
||||
|
||||
/** A loose VC++ installer resolves to the latest 14.x only if no specific vcredistYYYY was found. */
|
||||
private fun resolveLooseVcredist(hits: LinkedHashMap<String, Recommendation>) {
|
||||
val loose = hits.remove(VCREDIST_LOOSE) ?: return
|
||||
val hasSpecific = hits.keys.any { it in YEAR_TO_VCREDIST.values }
|
||||
if (!hasSpecific) hits["vcredist2022"] = loose.copy(componentName = "vcredist2022", label = LABELS["vcredist2022"]!!)
|
||||
}
|
||||
|
||||
private fun relativeReason(gameDir: File, f: File): String {
|
||||
val g = gameDir.path.replace('\\', '/')
|
||||
val p = f.path.replace('\\', '/')
|
||||
return if (p.startsWith("$g/")) p.substring(g.length + 1) else f.name
|
||||
}
|
||||
|
||||
/**
|
||||
* Map a redist file/dir (its full lowercased [path], leaf [name], and whether it [isDir]) to
|
||||
* catalog component name(s). Empty for things we deliberately skip.
|
||||
*/
|
||||
private fun classify(path: String, name: String, isDir: Boolean): List<String> {
|
||||
// Hard skips first — DX12 is provided by DXVK/VKD3D; these aren't our components.
|
||||
if (path.contains("d3d12") || path.contains("agility") ||
|
||||
path.contains("battleye") || path.contains("anticheat") || path.contains("easyanticheat") ||
|
||||
name.contains("socialclub") || name.contains("social-club") ||
|
||||
name.contains("rockstar") || name == "setup.exe"
|
||||
) return emptyList()
|
||||
|
||||
// Visual C++ runtimes — most important. Year comes from the path context.
|
||||
if (path.contains("vcredist") || path.contains("vc_redist") || name.startsWith("vcredist") || name.startsWith("vc_redist")) {
|
||||
val year = YEAR_TO_VCREDIST.keys.firstOrNull { path.contains(it) }
|
||||
return when {
|
||||
year != null -> listOf(YEAR_TO_VCREDIST.getValue(year))
|
||||
isDir -> emptyList() // bare "vcredist" container — wait for the year subfolder / installer
|
||||
else -> listOf(VCREDIST_LOOSE) // loose installer, no year → resolved post-walk
|
||||
}
|
||||
}
|
||||
// VC++ runtime DLL the game ships (msvcp140.dll → 2015-2022, msvcp120.dll → 2013, …).
|
||||
VCRUNTIME_DLL.entries.firstOrNull { name.startsWith(it.key) }?.let { return listOf(it.value) }
|
||||
if (path.contains("openal") || name.startsWith("oalinst") || name == "openal32.dll" || name == "wrap_oal.dll") return listOf("oalinst")
|
||||
if (path.contains("physx") || name.startsWith("physx")) return listOf("physx")
|
||||
if (path.contains("xact") || name.startsWith("xactengine") || name.startsWith("x3daudio")) return listOf("xact", "xact_x64")
|
||||
// Games for Windows Live — the redist folder, OR a GFWL library the game ships (xlive.dll,
|
||||
// Codemasters' dbxLive32/64, gfwl*): GFWL titles need XLiveRedist to run even when they don't
|
||||
// bundle the redist itself.
|
||||
if (path.contains("xliveredist") || name.contains("xlive") || name.startsWith("gfwl") || name.startsWith("dbxlive")) {
|
||||
return listOf("XLiveRedist")
|
||||
}
|
||||
if (path.contains("xna")) return listOf(if (path.contains("3.1") || path.contains("3_1") || path.contains("v31")) "xna31" else "xna40")
|
||||
// .NET — Framework and Core/Desktop runtimes.
|
||||
if (path.contains("dotnet") || path.contains(".net") || name.startsWith("ndp") || name.startsWith("dotnetfx") || name.contains("windowsdesktop-runtime")) {
|
||||
val comp = dotnetComponent("$path $name")
|
||||
return when {
|
||||
comp != null -> listOf(comp)
|
||||
isDir -> emptyList() // bare ".NET" container — wait for the versioned installer
|
||||
else -> listOf("dotnet48") // unlabeled .NET Framework installer file → sensible default
|
||||
}
|
||||
}
|
||||
// DirectX 11 helper DLLs the game ships (d3dx11_43.dll).
|
||||
if (D3DX11_RE.matches(name)) return listOf("d3dx11")
|
||||
// DirectX 9 helper DLLs / d3dcompiler / June-2010 DX redist (DXVK provides core d3d9 but NOT
|
||||
// these helper DLLs).
|
||||
if (name.startsWith("dxsetup") || name.startsWith("dxwebsetup") ||
|
||||
D3DX9_RE.matches(name) || D3DCOMPILER_RE.matches(name) ||
|
||||
(path.contains("directx") && name.endsWith(".exe"))
|
||||
) return listOf("d3dx9")
|
||||
return emptyList()
|
||||
}
|
||||
|
||||
/** Runtime DLL prefix → the VC++ redistributable that provides it (checked with startsWith). */
|
||||
private val VCRUNTIME_DLL = linkedMapOf(
|
||||
"vcruntime140" to "vcredist2022", "msvcp140" to "vcredist2022", "msvcr140" to "vcredist2022", "concrt140" to "vcredist2022",
|
||||
"msvcp120" to "vcredist2013", "msvcr120" to "vcredist2013",
|
||||
"msvcp110" to "vcredist2012", "msvcr110" to "vcredist2012",
|
||||
"msvcp100" to "vcredist2010", "msvcr100" to "vcredist2010",
|
||||
"msvcp90" to "vcredist2008", "msvcr90" to "vcredist2008",
|
||||
"msvcp80" to "vcredist2005", "msvcr80" to "vcredist2005",
|
||||
)
|
||||
private val D3DX9_RE = Regex("""d3dx9_\d+\.dll""")
|
||||
private val D3DX11_RE = Regex("""d3dx11_\d+\.dll""")
|
||||
private val D3DCOMPILER_RE = Regex("""d3dcompiler_\d+\.dll""")
|
||||
|
||||
/** Resolve a .NET component from installer/path text, or null when no version is discernible. */
|
||||
private fun dotnetComponent(s: String): String? = when {
|
||||
s.contains("desktop-runtime-8") || Regex("""\b8\.\d""").containsMatchIn(s) -> "dotnetcoredesktop8"
|
||||
s.contains("desktop-runtime-7") || Regex("""\b7\.\d""").containsMatchIn(s) -> "dotnetcoredesktop7"
|
||||
s.contains("desktop-runtime-6") || Regex("""\b6\.\d""").containsMatchIn(s) -> "dotnetcoredesktop6"
|
||||
s.contains("ndp48") || s.contains("fx48") || s.contains("4.8") -> "dotnet48"
|
||||
s.contains("ndp472") || s.contains("4.7.2") -> "dotnet472"
|
||||
s.contains("ndp46") || s.contains("4.6") -> "dotnet46"
|
||||
s.contains("ndp452") || s.contains("4.5.2") -> "dotnet452"
|
||||
s.contains("dotnetfx45") || s.contains("ndp45") || s.contains("4.5") -> "dotnet45"
|
||||
s.contains("dotnetfx40") || s.contains("ndp40") || s.contains("4.0") -> "dotnet40"
|
||||
s.contains("dotnetfx35") || s.contains("3.5") -> "dotnet35"
|
||||
else -> null // no version signal (e.g. a bare "DotNet" container dir)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package com.droiddeck.launcher.frontend
|
||||
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* Which catalog components a game's prefix already has from elsewhere - a real installer, the game,
|
||||
* the user - so the list can say so instead of recommending them again. Bannerlator's detector,
|
||||
* on DroidDeck's compatdata/<id>: only markers absent from a fresh Proton prefix count (OpenAL32,
|
||||
* Mono, PhysX, Games for Windows Live); msvcp140, d3dx9 and the like ship with Proton and cannot
|
||||
* tell. Files DroidDeck put there itself (droiddeck-wincomponents' state) are not counted.
|
||||
* Pure filesystem reads; never throws.
|
||||
*/
|
||||
object PrefixInstalledDetector {
|
||||
private const val STATE = ".droiddeck-wincomponents.json"
|
||||
|
||||
/** Detector names (oalinst, mono, physx, XLiveRedist) present in [compat]/pfx. */
|
||||
fun detect(compat: File?): Set<String> = try {
|
||||
val pfx = compat?.let { File(it, "pfx") }
|
||||
if (pfx == null || !pfx.isDirectory) emptySet() else {
|
||||
val ours = ours(compat)
|
||||
val out = HashSet<String>()
|
||||
val openal = listOf("system32", "syswow64").map { "drive_c/windows/$it/openal32.dll" }
|
||||
if (openal.any { it !in ours && fileIgnoringCase(pfx, it) }) out += "oalinst"
|
||||
if (File(pfx, "drive_c/windows/mono").isDirectory) out += "mono"
|
||||
if (hasPhysX(pfx)) out += "physx"
|
||||
if (registryContains(pfx, "Games for Windows")) out += "XLiveRedist"
|
||||
out
|
||||
}
|
||||
} catch (_: Throwable) {
|
||||
emptySet()
|
||||
}
|
||||
|
||||
private fun ours(compat: File): Set<String> = try {
|
||||
val files = JSONObject(File(compat, STATE).readText()).optJSONObject("files")
|
||||
files?.keys()?.asSequence()?.map { it.lowercase() }?.toSet().orEmpty()
|
||||
} catch (_: Exception) {
|
||||
emptySet()
|
||||
}
|
||||
|
||||
/** Windows names ignore case; the prefix's folder may spell them either way. */
|
||||
private fun fileIgnoringCase(pfx: File, rel: String): Boolean {
|
||||
val target = File(pfx, rel)
|
||||
return target.parentFile?.listFiles()?.any { it.isFile && it.name.equals(target.name, ignoreCase = true) } == true
|
||||
}
|
||||
|
||||
private fun hasPhysX(pfx: File): Boolean {
|
||||
for (pf in arrayOf("drive_c/Program Files", "drive_c/Program Files (x86)")) {
|
||||
val base = File(pfx, pf)
|
||||
if (File(base, "NVIDIA Corporation/PhysX").isDirectory) return true
|
||||
if (base.listFiles()?.any { it.isDirectory && it.name.contains("PhysX", ignoreCase = true) } == true) return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
private fun registryContains(pfx: File, needle: String): Boolean =
|
||||
arrayOf("system.reg", "user.reg").any { name ->
|
||||
val f = File(pfx, name)
|
||||
try {
|
||||
f.isFile && f.length() < 32L * 1024 * 1024 &&
|
||||
f.bufferedReader().use { r -> r.lineSequence().any { it.contains(needle, ignoreCase = true) } }
|
||||
} catch (_: Throwable) {
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package com.droiddeck.launcher.frontend
|
||||
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* What Steam itself installs alongside a game: the Steamworks Shared redistributables (app 228980)
|
||||
* listed under "SharedDepots" in the game's appmanifest. Those live in Steamworks Shared rather than
|
||||
* the game's folder, so the folder scan ([DependencyDetector]) cannot see them; this reads Steam's
|
||||
* list instead. Depots are matched to Bannerlator's catalog names; unknown ones are left out.
|
||||
*/
|
||||
object SteamRedists {
|
||||
/** Steamworks Shared depot -> (catalog component, what Steam calls it). 2015-2019 runtimes are one family. */
|
||||
val DEPOTS = linkedMapOf(
|
||||
"228981" to ("vcredist2005_dll" to "VC++ 2005"),
|
||||
"228982" to ("vcredist2008_dll" to "VC++ 2008"),
|
||||
"228983" to ("vcredist2010_dll" to "VC++ 2010"),
|
||||
"228984" to ("vcredist2012_dll" to "VC++ 2012"),
|
||||
"228985" to ("vcredist2013_dll" to "VC++ 2013"),
|
||||
"228986" to ("vcredist2015_dll" to "VC++ 2015"),
|
||||
"228987" to ("vcredist2019_dll" to "VC++ 2017"),
|
||||
"228988" to ("vcredist2019_dll" to "VC++ 2019"),
|
||||
"228989" to ("vcredist2022_dll" to "VC++ 2022"),
|
||||
"228990" to ("d3dx9" to "DirectX (June 2010)"),
|
||||
)
|
||||
private val BLOCK = Regex("\"SharedDepots\"\\s*\\{([^}]*)\\}", RegexOption.IGNORE_CASE)
|
||||
private val ENTRY = Regex("\"(\\d+)\"\\s+\"\\d+\"")
|
||||
|
||||
/** The game's appmanifest beside its install folder (steamapps/common/<dir> -> steamapps/). */
|
||||
fun manifest(gameDir: File?, appId: Int): File? {
|
||||
val steamapps = gameDir?.parentFile?.parentFile ?: return null
|
||||
return File(steamapps, "appmanifest_$appId.acf").takeIf { it.isFile }
|
||||
}
|
||||
|
||||
fun detect(gameDir: File?, appId: Int): List<DependencyDetector.Recommendation> {
|
||||
val text = try {
|
||||
manifest(gameDir, appId)?.takeIf { it.length() < 1L shl 20 }?.readText() ?: return emptyList()
|
||||
} catch (_: Exception) {
|
||||
return emptyList()
|
||||
}
|
||||
val block = BLOCK.find(text)?.groupValues?.get(1) ?: return emptyList()
|
||||
return ENTRY.findAll(block).mapNotNull { DEPOTS[it.groupValues[1]] }
|
||||
.distinctBy { it.first }
|
||||
.map { (component, label) -> DependencyDetector.Recommendation(component, label, label, DependencyDetector.Kind.STEAM) }
|
||||
.toList()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
package com.droiddeck.launcher.gpu
|
||||
|
||||
import android.app.ActivityManager
|
||||
import android.content.Context
|
||||
import android.content.pm.PackageManager
|
||||
import android.os.Build
|
||||
import com.droiddeck.launcher.core.FileUtils
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import java.io.File
|
||||
import java.util.Locale
|
||||
|
||||
/**
|
||||
* Everything the device info window shows about the phone's chip: SoC, GPU, CPU, memory, system,
|
||||
* the phone's own Vulkan driver and the drivers DroidDeck uses. Reads files and asks Vulkan once
|
||||
* ([VulkanInfo]), so [collect] belongs off the main thread. Values the phone does not give are
|
||||
* left out rather than guessed.
|
||||
*/
|
||||
object DeviceInfo {
|
||||
class Section(val title: String, val rows: List<Pair<String, String>>)
|
||||
|
||||
fun collect(context: Context): List<Section> {
|
||||
val vk = VulkanInfo.query()
|
||||
// After Vulkan has been asked, detection can use its name too.
|
||||
val gpu = GpuInfo.detect()
|
||||
return listOf(
|
||||
chip(), gpu(gpu), cpu(), memory(context), system(), vulkan(context, vk), drivers(context, gpu),
|
||||
).filter { it.rows.isNotEmpty() }
|
||||
}
|
||||
|
||||
/** The whole window as plain text, for a bug report. */
|
||||
fun text(sections: List<Section>): String = buildString {
|
||||
append("DroidDeck device info\n")
|
||||
for (s in sections) {
|
||||
append('\n').append(s.title).append('\n')
|
||||
for ((k, v) in s.rows) append(" ").append(k).append(": ").append(v).append('\n')
|
||||
}
|
||||
}
|
||||
|
||||
private fun MutableList<Pair<String, String>>.add(key: String, value: String?) {
|
||||
if (!value.isNullOrBlank() && value != Build.UNKNOWN) add(key to value.trim())
|
||||
}
|
||||
|
||||
private fun read(path: String): String? = FileUtils.readString(File(path))?.trim()?.ifEmpty { null }
|
||||
|
||||
private fun prop(name: String): String = GpuInfo.systemProperty(name)
|
||||
|
||||
private fun chip() = Section("Chip (SoC)", buildList<Pair<String, String>> {
|
||||
val model = SocNames.model()
|
||||
val platform = prop("ro.board.platform")
|
||||
add("Name", SocNames.name(model, platform))
|
||||
add("Model", model)
|
||||
if (Build.VERSION.SDK_INT >= 31) add("Maker", Build.SOC_MANUFACTURER)
|
||||
add("Platform", platform)
|
||||
add("Hardware", Build.HARDWARE)
|
||||
add("Board", Build.BOARD)
|
||||
val id = read("/sys/devices/soc0/soc_id")
|
||||
val machine = read("/sys/devices/soc0/machine")
|
||||
add("SoC id", listOfNotNull(id, machine).joinToString(" · "))
|
||||
add("Family", read("/sys/devices/soc0/family"))
|
||||
})
|
||||
|
||||
private fun gpu(gpu: GpuInfo) = Section("GPU", buildList<Pair<String, String>> {
|
||||
add("GPU", gpu.name)
|
||||
add("Family", gpu.family.label)
|
||||
add("Model found from", when (gpu.modelSource) {
|
||||
"kernel" -> "the kernel's GPU name"
|
||||
"vulkan" -> "the Vulkan driver (the kernel's name has no model)"
|
||||
"platform" -> "the platform (the kernel's name has no model)"
|
||||
else -> "unknown"
|
||||
})
|
||||
add("Kernel name", gpu.kgslName)
|
||||
val kgsl = "/sys/class/kgsl/kgsl-3d0"
|
||||
add("Clock range", gpuRange())
|
||||
add("Load", read("$kgsl/gpu_busy_percentage")?.let { if (it.endsWith("%")) it else "$it %" })
|
||||
add("Temperature", read("$kgsl/temp")?.toLongOrNull()?.let { if (it > 1000) "${it / 1000} °C" else "$it °C" })
|
||||
add("Support", gpu.supportText)
|
||||
})
|
||||
|
||||
private fun cpu() = Section("CPU", buildList<Pair<String, String>> {
|
||||
add("Cores", Runtime.getRuntime().availableProcessors().toString())
|
||||
// Each cpufreq policy is one cluster: the cores it covers and their speed range.
|
||||
val policies = File("/sys/devices/system/cpu/cpufreq").listFiles { f -> f.name.matches(Regex("policy\\d+")) }
|
||||
?.sortedBy { it.name.removePrefix("policy").toInt() }.orEmpty()
|
||||
for (p in policies) {
|
||||
val cpus = (read("${p.path}/related_cpus") ?: read("${p.path}/affected_cpus"))?.split(Regex("\\s+"))?.filter { it.isNotEmpty() }.orEmpty()
|
||||
val min = read("${p.path}/cpuinfo_min_freq")?.toLongOrNull()
|
||||
val max = read("${p.path}/cpuinfo_max_freq")?.toLongOrNull() ?: continue
|
||||
val cores = if (cpus.size > 1) "cores ${cpus.first()}-${cpus.last()}" else "core ${cpus.firstOrNull() ?: p.name.removePrefix("policy")}"
|
||||
add("Cluster ${p.name.removePrefix("policy")}", "${cpus.size.coerceAtLeast(1)} × $cores · " +
|
||||
(if (min != null) ghz(min) + "–" else "") + ghz(max))
|
||||
}
|
||||
add("ABI", Build.SUPPORTED_ABIS.joinToString(", "))
|
||||
})
|
||||
|
||||
private fun ghz(khz: Long) = String.format(Locale.US, "%.2f GHz", khz / 1e6)
|
||||
|
||||
/** The GPU's slowest and fastest step: KGSL's list, else a devfreq GPU node (Mali and others). */
|
||||
private fun gpuRange(): String? {
|
||||
fun mhz(hz: Long) = "${hz / 1_000_000} MHz"
|
||||
val kgsl = read("/sys/class/kgsl/kgsl-3d0/gpu_available_frequencies")
|
||||
?.split(Regex("\\s+"))?.mapNotNull { it.toLongOrNull() }?.filter { it > 0 }.orEmpty()
|
||||
if (kgsl.isNotEmpty()) return "${mhz(kgsl.min())}–${mhz(kgsl.max())} (${kgsl.size} steps)"
|
||||
read("/sys/class/kgsl/kgsl-3d0/max_gpuclk")?.toLongOrNull()?.let { return "up to ${mhz(it)}" }
|
||||
val node = File("/sys/class/devfreq").listFiles()?.firstOrNull { f ->
|
||||
val n = f.name.lowercase()
|
||||
(n.contains("gpu") || n.contains("mali") || n.contains("kgsl-3d")) && listOf("bus", "bw", "memlat").none { n.contains(it) }
|
||||
} ?: return null
|
||||
val steps = read("${node.path}/available_frequencies")?.split(Regex("\\s+"))?.mapNotNull { it.toLongOrNull() }?.filter { it > 0 }.orEmpty()
|
||||
if (steps.isNotEmpty()) return "${mhz(steps.min())}–${mhz(steps.max())} (${steps.size} steps)"
|
||||
val min = read("${node.path}/min_freq")?.toLongOrNull()
|
||||
val max = read("${node.path}/max_freq")?.toLongOrNull() ?: return null
|
||||
return (if (min != null) "${mhz(min)}–" else "up to ") + mhz(max)
|
||||
}
|
||||
|
||||
private fun memory(context: Context) = Section("Memory", buildList<Pair<String, String>> {
|
||||
val am = context.getSystemService(ActivityManager::class.java) ?: return@buildList
|
||||
val mi = ActivityManager.MemoryInfo().also(am::getMemoryInfo)
|
||||
add("Total", FileUtils.sizeToString(mi.totalMem))
|
||||
add("Available now", FileUtils.sizeToString(mi.availMem))
|
||||
})
|
||||
|
||||
private fun system() = Section("System", buildList<Pair<String, String>> {
|
||||
add("Device", "${Build.MANUFACTURER} ${Build.MODEL}")
|
||||
add("Android", "${Build.VERSION.RELEASE} (API ${Build.VERSION.SDK_INT})")
|
||||
add("Security patch", Build.VERSION.SECURITY_PATCH)
|
||||
add("Kernel", System.getProperty("os.version"))
|
||||
add("Build", Build.DISPLAY)
|
||||
})
|
||||
|
||||
private fun vulkan(context: Context, vk: Map<String, String>) = Section("Vulkan (the phone's own driver)", buildList<Pair<String, String>> {
|
||||
vk["error"]?.let { add("Error", it) }
|
||||
add("Device", vk["device"])
|
||||
add("Type", vk["type"])
|
||||
add("API version", vk["api"])
|
||||
add("Loader version", vk["loader"])
|
||||
add("Driver", listOfNotNull(vk["driver_name"], vk["driver_version"]).joinToString(" "))
|
||||
// Qualcomm's build string starts with its own label ("Driver Build: 43c70540de, ...").
|
||||
add("Driver build", vk["driver_info"]?.replace(Regex("(?i)^driver build:\\s*"), ""))
|
||||
add("Conformance", vk["conformance"])
|
||||
add("Vendor / device id", listOfNotNull(vk["vendor_id"], vk["device_id"]).joinToString(" / "))
|
||||
add("Max texture size", vk["max_image_2d"])
|
||||
add("GPU memory heap", vk["device_heap_mb"]?.let { "$it MB" })
|
||||
add("Extensions", vk["extension_count"])
|
||||
val features = listOf("geometry_shader" to "Geometry shaders", "tessellation_shader" to "Tessellation", "texture_bc" to "BC textures")
|
||||
for ((key, label) in features) add(label, vk[key])
|
||||
for ((key, value) in vk) if (key.startsWith("ext.")) add(key.removePrefix("ext."), value)
|
||||
// What Android certifies the phone for.
|
||||
val pm = context.packageManager
|
||||
val hw = pm.systemAvailableFeatures.associate { it.name to it.version }
|
||||
hw[PackageManager.FEATURE_VULKAN_HARDWARE_VERSION]?.let {
|
||||
add("Android-certified version", "${it shr 22}.${(it shr 12) and 0x3ff}.${it and 0xfff}")
|
||||
}
|
||||
hw[PackageManager.FEATURE_VULKAN_HARDWARE_LEVEL]?.let { add("Android hardware level", it.toString()) }
|
||||
})
|
||||
|
||||
private fun drivers(context: Context, gpu: GpuInfo) = Section("Drivers DroidDeck uses", buildList<Pair<String, String>> {
|
||||
add("Driver mode", SessionPrefs.gpuDriverMode(context))
|
||||
val turnip = TurnipDriver(context)
|
||||
val choice = SessionPrefs.androidDriver(context).ifEmpty { turnip.autoId() }
|
||||
add("Display driver", "${turnip.displayName(choice)} ${turnip.driverVersion(choice)}".trim())
|
||||
val linux = LinuxVulkanDriverManager(context)
|
||||
val id = SessionPrefs.linuxDriver(context)
|
||||
add("Game driver", if (id.isEmpty()) "the runtime's own Turnip" else "${linux.getDriverName(id)} ${linux.getDriverVersion(id)}".trim())
|
||||
if (gpu.oneUi8Gen2) add("Note", "One UI on an 8 Gen 2: needs the OneUI Turnip build")
|
||||
})
|
||||
}
|
||||
@@ -16,10 +16,14 @@ data class GpuInfo(
|
||||
/** The three-digit Adreno model (740, 825), or 0 when KGSL does not say. */
|
||||
val model: Int,
|
||||
val family: Family,
|
||||
/** The SoC as the device reports it ("SM8550", "QCS8550"), or "" when it does not. */
|
||||
/** The SoC as a person would say it ("Snapdragon 8 Gen 2 (QCS8550)"), or "" when the phone does not say. */
|
||||
val soc: String,
|
||||
/** Samsung's One UI on an 8 Gen 2: its Turnip needs the OneUI build, or frames tear and flicker. */
|
||||
val oneUi8Gen2: Boolean,
|
||||
/** KGSL's own name for the GPU, as the kernel spells it ("Adreno740v2", "Adreno33v2"). */
|
||||
val kgslName: String = "",
|
||||
/** Where [model] came from: "kernel", "vulkan" or "platform", "" when unknown. */
|
||||
val modelSource: String = "",
|
||||
) {
|
||||
enum class Family(val label: String) {
|
||||
A8XX("Adreno 8xx"),
|
||||
@@ -56,17 +60,49 @@ data class GpuInfo(
|
||||
val adreno = File("/sys/class/kgsl/kgsl-3d0").exists() || File("/vendor/lib64/hw/vulkan.adreno.so").exists()
|
||||
val raw = listOf("/sys/class/kgsl/kgsl-3d0/gpu_model", "/sys/class/kgsl/kgsl-3d0/gpu_chipid")
|
||||
.firstNotNullOfOrNull { FileUtils.readString(File(it))?.trim()?.takeIf(String::isNotEmpty) }
|
||||
val soc = if (Build.VERSION.SDK_INT >= 31) Build.SOC_MODEL.takeIf { it.isNotBlank() && it != Build.UNKNOWN }.orEmpty() else ""
|
||||
val model = raw?.let { Regex("""(\d{3})""").find(it)?.groupValues?.get(1)?.toIntOrNull() } ?: 0
|
||||
// Where vendors put the chip's model, named when it is known: "Snapdragon 8 Gen 2 (QCS8550)".
|
||||
val soc = if (adreno) SocNames.label() else ""
|
||||
val fromKernel = raw?.let { threeDigits(it) } ?: 0
|
||||
// Some kernels name the GPU without its model (AYANEO's Pocket FIT: "Adreno33v2"). The
|
||||
// Vulkan driver's own name, when this process has asked it, then the platform's code
|
||||
// name stand in - the GPU is the same on every phone of a platform.
|
||||
val fromVulkan = if (fromKernel > 0 || !adreno) 0 else VulkanInfo.cachedOrNull()?.get("device")?.let { threeDigits(it) } ?: 0
|
||||
val fromPlatform = if (fromKernel > 0 || fromVulkan > 0 || !adreno) 0 else platformModel()
|
||||
val model = maxOf(fromKernel, fromVulkan, fromPlatform)
|
||||
val source = when {
|
||||
fromKernel > 0 -> "kernel"
|
||||
fromVulkan > 0 -> "vulkan"
|
||||
fromPlatform > 0 -> "platform"
|
||||
else -> ""
|
||||
}
|
||||
val family = familyOf(adreno, model)
|
||||
val samsung = Build.MANUFACTURER.equals("samsung", ignoreCase = true)
|
||||
return GpuInfo(
|
||||
name = if (!adreno) Build.HARDWARE.ifBlank { "this GPU" } else if (model > 0) "Adreno $model" else "Adreno",
|
||||
model = model, family = family, soc = soc,
|
||||
oneUi8Gen2 = samsung && model == 740,
|
||||
kgslName = raw.orEmpty(), modelSource = source,
|
||||
)
|
||||
}
|
||||
|
||||
private fun threeDigits(text: String): Int = Regex("""(\d{3})""").find(text)?.groupValues?.get(1)?.toIntOrNull() ?: 0
|
||||
|
||||
/** Qualcomm platform code names whose GPU is known for certain. */
|
||||
private val PLATFORMS = mapOf(
|
||||
"msmnile" to 640, "kona" to 650, "lahaina" to 660, "taro" to 730, "cape" to 730,
|
||||
"kalama" to 740, "pineapple" to 750, "sun" to 830,
|
||||
)
|
||||
|
||||
internal fun platformModel(platform: String = systemProperty("ro.board.platform")): Int =
|
||||
PLATFORMS[platform.lowercase()] ?: PLATFORMS[systemProperty("ro.vendor.qti.soc_name").lowercase()] ?: 0
|
||||
|
||||
/** android.os.SystemProperties.get, which apps may read but not call directly. */
|
||||
fun systemProperty(name: String): String = try {
|
||||
Class.forName("android.os.SystemProperties").getMethod("get", String::class.java).invoke(null, name) as? String ?: ""
|
||||
} catch (_: Exception) {
|
||||
""
|
||||
}
|
||||
|
||||
internal fun familyOf(adreno: Boolean, model: Int): Family = when {
|
||||
!adreno -> Family.NOT_ADRENO
|
||||
model == 0 -> Family.ADRENO_UNKNOWN
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
package com.droiddeck.launcher.gpu
|
||||
|
||||
import android.os.Build
|
||||
|
||||
/**
|
||||
* Which chip this is, as a person would say it. Handhelds often leave Android's SoC model blank
|
||||
* (the AYANEO Pocket FIT does), so the model is looked for where vendors put it, the same order
|
||||
* ClusterTune uses; then it is named from a table of models we are sure of, or from the platform
|
||||
* code name as a family ("Snapdragon 8 Gen 3 family") when the model itself is a vendor variant.
|
||||
*/
|
||||
object SocNames {
|
||||
/** Model codes whose product name is certain. */
|
||||
private val MODELS = mapOf(
|
||||
"SM8150" to "Snapdragon 855", "SM8250" to "Snapdragon 865", "SM8250-AC" to "Snapdragon 870",
|
||||
"SM8350" to "Snapdragon 888", "SM8450" to "Snapdragon 8 Gen 1", "SM8475" to "Snapdragon 8+ Gen 1",
|
||||
"SM8550" to "Snapdragon 8 Gen 2", "QCS8550" to "Snapdragon 8 Gen 2", "SM8650" to "Snapdragon 8 Gen 3",
|
||||
"SM8750" to "Snapdragon 8 Elite", "SM8850" to "Snapdragon 8 Elite Gen 5",
|
||||
"SM7325" to "Snapdragon 778G", "SM7450" to "Snapdragon 7 Gen 1", "SM7550" to "Snapdragon 7 Gen 3",
|
||||
"SM6375" to "Snapdragon 695",
|
||||
)
|
||||
|
||||
/** Platform code names: every chip of one platform shares its CPU and GPU design. */
|
||||
private val PLATFORMS = mapOf(
|
||||
"msmnile" to "Snapdragon 855/860", "kona" to "Snapdragon 865/870", "lahaina" to "Snapdragon 888",
|
||||
"taro" to "Snapdragon 8 Gen 1", "cape" to "Snapdragon 8+ Gen 1", "kalama" to "Snapdragon 8 Gen 2",
|
||||
"pineapple" to "Snapdragon 8 Gen 3", "sun" to "Snapdragon 8 Elite",
|
||||
)
|
||||
|
||||
/** The chip's model code ("QCS8550", "SG8350P"), or "" when the phone does not say. */
|
||||
fun model(prop: (String) -> String = GpuInfo::systemProperty): String {
|
||||
val sdk = if (Build.VERSION.SDK_INT >= 31) Build.SOC_MODEL.takeIf { it != Build.UNKNOWN }.orEmpty() else ""
|
||||
return listOf(prop("ro.soc.model"), prop("ro.vendor.qti.soc_model"), sdk, prop("ro.fota.platform"))
|
||||
.map { it.trim() }
|
||||
// ro.fota.platform is often a branch name ("MSM_13.0"), not a chip.
|
||||
.firstOrNull { it.isNotEmpty() && !Regex("(?i)^msm_\\d").containsMatchIn(it) }.orEmpty()
|
||||
}
|
||||
|
||||
/** "Snapdragon 8 Gen 2", "Snapdragon 8 Gen 3 family", or null when neither the model nor the platform is known. */
|
||||
fun name(model: String, platform: String = GpuInfo.systemProperty("ro.board.platform")): String? =
|
||||
MODELS[model.uppercase()] ?: PLATFORMS[platform.lowercase()]?.let { "$it family" }
|
||||
|
||||
/** For the GPU card: "Snapdragon 8 Gen 2 (QCS8550)", the bare model, or "". */
|
||||
fun label(model: String = model(), platform: String = GpuInfo.systemProperty("ro.board.platform")): String {
|
||||
val name = name(model, platform)
|
||||
return when {
|
||||
name != null && model.isNotEmpty() -> "$name ($model)"
|
||||
name != null -> name
|
||||
else -> model
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package com.droiddeck.launcher.gpu
|
||||
|
||||
import android.util.Log
|
||||
|
||||
/**
|
||||
* The phone's own Vulkan driver, as it describes itself (native/deviceinfo): device name, API and
|
||||
* driver versions, a few limits and the extensions DXVK/VKD3D lean on. Asked once per process and
|
||||
* kept; the first [query] creates a Vulkan instance, so it belongs off the main thread.
|
||||
*/
|
||||
object VulkanInfo {
|
||||
@Volatile private var cached: Map<String, String>? = null
|
||||
|
||||
@JvmStatic private external fun nativeQuery(): String
|
||||
|
||||
/** Blocking on first use. Empty-ish map with an "error" key when Vulkan cannot be asked. */
|
||||
@Synchronized
|
||||
fun query(): Map<String, String> {
|
||||
cached?.let { return it }
|
||||
val text = try {
|
||||
System.loadLibrary("deviceinfo")
|
||||
nativeQuery()
|
||||
} catch (t: Throwable) {
|
||||
Log.w("VulkanInfo", "query failed", t)
|
||||
"error=" + (t.message ?: t.javaClass.simpleName)
|
||||
}
|
||||
val map = text.lineSequence().mapNotNull { line ->
|
||||
val eq = line.indexOf('=')
|
||||
if (eq <= 0) null else line.substring(0, eq) to line.substring(eq + 1)
|
||||
}.toMap(LinkedHashMap())
|
||||
cached = map
|
||||
return map
|
||||
}
|
||||
|
||||
/** What [query] found, if it has run in this process; never blocks. */
|
||||
fun cachedOrNull(): Map<String, String>? = cached
|
||||
}
|
||||
@@ -21,13 +21,15 @@ import java.security.MessageDigest
|
||||
*/
|
||||
object ProotFastPath {
|
||||
const val LIBRARY = "/usr/local/lib/libblfastpath.so"
|
||||
/** MAX_BINDS in fastpath.c: past it the library turns itself off, so the session keeps it off. */
|
||||
const val MAX_BINDS = 256
|
||||
|
||||
fun enabled(context: Context): Boolean =
|
||||
SessionPrefs.prootFastPath(context) && !SessionPrefs.prootNoSeccomp(context)
|
||||
|
||||
/** The key for this rootfs and these binds, or null when the library cannot be told them. */
|
||||
fun key(root: File, binds: List<String>): String? {
|
||||
if (binds.any { it.contains('|') } || root.path.contains('|')) return null
|
||||
if (binds.size > MAX_BINDS || binds.any { it.contains('|') } || root.path.contains('|')) return null
|
||||
val digest = MessageDigest.getInstance("SHA-256")
|
||||
.digest((root.path + "\n" + binds.joinToString("\n")).toByteArray())
|
||||
return digest.take(12).joinToString("") { "%02x".format(it) }
|
||||
|
||||
@@ -5,6 +5,7 @@ import android.content.Context
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.core.Downloader
|
||||
import com.droiddeck.launcher.core.FileUtils
|
||||
import com.droiddeck.launcher.gpu.GpuInfo
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import com.github.luben.zstd.ZstdInputStream
|
||||
import com.github.luben.zstd.ZstdOutputStream
|
||||
@@ -660,6 +661,107 @@ object ComponentsManager {
|
||||
return Catalog(items, o.optLong("fetchedAt"))
|
||||
}
|
||||
|
||||
/**
|
||||
* A package Proton does not ship, required on the GPUs listed here. An empty [models] set
|
||||
* means every model in [families]. A row the user already chose in Components is left alone;
|
||||
* a Steam update that puts the Proton's own files back is replaced on the next session.
|
||||
*/
|
||||
internal data class ForcedPackage(
|
||||
val families: Set<GpuInfo.Family>,
|
||||
val comp: String,
|
||||
val file: String,
|
||||
val release: String,
|
||||
val models: Set<Int> = emptySet(),
|
||||
) {
|
||||
fun matches(gpu: GpuInfo) = gpu.family in families && (models.isEmpty() || gpu.model in models)
|
||||
}
|
||||
|
||||
internal val FORCED_PACKAGES = listOf(
|
||||
// DXVK 3 refuses to start unless the device exposes storageBuffer8BitAccess. Turnip on
|
||||
// Adreno 6xx does not. 2.7.1 is the last DXVK 2 package on the Dxvk-Linux tag.
|
||||
ForcedPackage(setOf(GpuInfo.Family.A6XX), "dxvk", "dxvk-2.7.1-linux.wcp", "Dxvk-Linux"),
|
||||
)
|
||||
|
||||
/**
|
||||
* True when this Proton should receive the forced package. No active swap means the Proton's
|
||||
* own copy. A record for a different Proton build means a Steam update put that copy back,
|
||||
* whichever package was recorded. A record for this build is a Components choice and stays.
|
||||
*/
|
||||
internal fun forcedPackageWanted(activeFile: String?, protonVersionMatches: Boolean): Boolean =
|
||||
activeFile.isNullOrEmpty() || !protonVersionMatches
|
||||
|
||||
/** The catalog row for this file and release, or null. */
|
||||
internal fun catalogMatch(items: List<CatalogItem>, file: String, release: String): CatalogItem? =
|
||||
items.firstOrNull { it.file == file && it.release == release }
|
||||
|
||||
/**
|
||||
* Install every [FORCED_PACKAGES] row this GPU matches into each Proton that
|
||||
* [forcedPackageWanted] selects. Returns a line for the log, or null when this GPU or these
|
||||
* Protons need nothing. A failed fetch throws and the session logs it without stopping.
|
||||
*/
|
||||
fun ensureForcedPackages(context: Context): String? = ensureForcedPackages(
|
||||
context, GpuInfo.detect(),
|
||||
{ file, release -> catalogItem(context, file, release) },
|
||||
{ download(context, it) {} },
|
||||
{ id, file -> swap(context, id, file) },
|
||||
)
|
||||
|
||||
internal fun ensureForcedPackages(
|
||||
context: Context,
|
||||
gpu: GpuInfo,
|
||||
lookup: (file: String, release: String) -> CatalogItem?,
|
||||
fetch: (CatalogItem) -> Unit,
|
||||
apply: (protonId: String, file: String) -> String,
|
||||
): String? {
|
||||
val rules = FORCED_PACKAGES.filter { it.matches(gpu) }
|
||||
if (rules.isEmpty()) return null
|
||||
val installed = protons(context)
|
||||
val lines = mutableListOf<String>()
|
||||
for (rule in rules) {
|
||||
val state = loadState(context)
|
||||
val targets = installed.filter { p ->
|
||||
val active = state.optJSONObject("active")?.optJSONObject(p.id)?.optJSONObject(rule.comp)
|
||||
forcedPackageWanted(active?.optString("file"), active?.optString("protonVersion") == p.version)
|
||||
}
|
||||
if (targets.isEmpty()) continue
|
||||
val missing = missingPackage(context, rule, lookup, fetch)
|
||||
if (missing != null) {
|
||||
lines.add(missing)
|
||||
continue
|
||||
}
|
||||
lines.add(targets.joinToString("; ") { apply(it.id, rule.file) })
|
||||
}
|
||||
return lines.joinToString("; ").ifEmpty { null }
|
||||
}
|
||||
|
||||
/** Null when [rule]'s package is stored and readable. Otherwise the log line, after a fetch. */
|
||||
private fun missingPackage(
|
||||
context: Context,
|
||||
rule: ForcedPackage,
|
||||
lookup: (file: String, release: String) -> CatalogItem?,
|
||||
fetch: (CatalogItem) -> Unit,
|
||||
): String? {
|
||||
val wcp = File(packagesDir(context), safeName(rule.file))
|
||||
if (wcp.isFile && runCatching { packageInfo(wcp) }.isSuccess) return null
|
||||
wcp.delete()
|
||||
val item = lookup(rule.file, rule.release)
|
||||
?: return "${rule.file} is not in the Nightlies listing; ${LABEL.getValue(rule.comp)} stays on the Proton's copy"
|
||||
fetch(item)
|
||||
return null
|
||||
}
|
||||
|
||||
/** The cached Nightlies row for this file, fetching the listing when the cache does not have it. */
|
||||
internal fun catalogItem(context: Context, file: String, release: String): CatalogItem? =
|
||||
resolveCatalogItem(file, release, { catalog(context, false).items }, { catalog(context, true).items })
|
||||
|
||||
/** [cached] when it has the row, otherwise [refresh]. [refresh] is not called on a hit. */
|
||||
internal fun resolveCatalogItem(
|
||||
file: String,
|
||||
release: String,
|
||||
cached: () -> List<CatalogItem>,
|
||||
refresh: () -> List<CatalogItem>,
|
||||
): CatalogItem? = catalogMatch(cached(), file, release) ?: catalogMatch(refresh(), file, release)
|
||||
|
||||
/** Downloads a catalog item into storage, verifying the release's sha256 and the package type. */
|
||||
fun download(context: Context, item: CatalogItem, progress: (Int) -> Unit): Package {
|
||||
require(item.url.startsWith("https://github.com/$NIGHTLIES/releases/download/")) { "Downloads come only from the Nightlies releases" }
|
||||
|
||||
@@ -59,7 +59,7 @@ object GameEnvironmentStore {
|
||||
|
||||
@Synchronized
|
||||
fun publish(context: Context, config: GameEnvironment.Config = read(context)) {
|
||||
val resolved = config.copy(shared = GameEnvironment.defaults(SessionPrefs.fexPreset(context)) + config.shared)
|
||||
val resolved = config.copy(shared = GameEnvironment.defaults(SessionPrefs.fexPreset(context), SessionPrefs.forceSsbs(context)) + config.shared)
|
||||
val json = encode(resolved)
|
||||
// The Display page's texture filtering, as DXVK options the launcher appends to
|
||||
// DXVK_CONFIG after the profiles - a user's own DXVK_CONFIG entry keeps its options.
|
||||
|
||||
@@ -34,6 +34,16 @@ object SessionArtifacts {
|
||||
/** Every file in the folder has been through the redactor, own addresses and accounts included (-2: accounts added). */
|
||||
private const val SCRUBBED_MARKER = ".scrubbed-2"
|
||||
|
||||
/**
|
||||
* Written by a session's own ending, and only when every file in the folder, subfolders
|
||||
* included (whatever the session script copied into steam/ and droiddeck-esync/ as well as what
|
||||
* the app wrote), went through the redactor without a failure. It lists each of those files
|
||||
* with its size and modification time, under the redactor's rules version: a share copies a
|
||||
* file as it is only when all three still match ([scrubbedFiles]), and scrubs anything else -
|
||||
* a file added or changed since, a hidden one, or every file of a folder without it.
|
||||
*/
|
||||
const val SCRUBBED_TREE_MARKER = ".scrubbed-tree"
|
||||
|
||||
/** Everything the end of a session gathers, into [dir]. Safe to call for a dead session. */
|
||||
fun collect(context: Context, dir: File, reason: String) {
|
||||
try {
|
||||
@@ -44,11 +54,11 @@ object SessionArtifacts {
|
||||
}
|
||||
}
|
||||
LogRedactor.learnFromRuntime(LinuxRuntime.rootDir(context))
|
||||
copySteamLogs(context, dir)
|
||||
val record = Record(dir)
|
||||
copySteamLogs(context, dir, record)
|
||||
// A session the system killed leaves its trace here and nowhere else.
|
||||
SessionLogCapture.dumpCrashBuffer(File(dir, "crash.log"))
|
||||
scrubFolder(dir)
|
||||
try { File(dir, SCRUBBED_MARKER).writeText("scrubbed ${now()}\n") } catch (e: Exception) {}
|
||||
markScrubbed(scrubTree(record))
|
||||
SessionEvents.record("session.artifacts_collected", mapOf("reason" to reason), dir)
|
||||
File(dir, COMPLETE_MARKER).writeText("collected: $reason at ${now()}\n")
|
||||
} catch (e: Exception) {
|
||||
@@ -71,8 +81,7 @@ object SessionArtifacts {
|
||||
if (dirs.isEmpty()) return
|
||||
LogRedactor.learnFromRuntime(LinuxRuntime.rootDir(context))
|
||||
dirs.forEach { dir ->
|
||||
scrubFolder(dir)
|
||||
File(dir, "steam").takeIf { it.isDirectory }?.let { scrubFolder(it) }
|
||||
Record(dir).let { r -> scrubFolder(dir, r); File(dir, "steam").takeIf { it.isDirectory }?.let { scrubFolder(it, r) } }
|
||||
try { File(dir, SCRUBBED_MARKER).writeText("scrubbed ${now()}\n") } catch (e: Exception) {}
|
||||
}
|
||||
Log.i(TAG, "scrubbed ${dirs.size} older session folder(s)")
|
||||
@@ -84,29 +93,121 @@ object SessionArtifacts {
|
||||
* through the redactor before the folder can be shared. A file is rewritten only if a line
|
||||
* changed. steam/ was scrubbed on the way in.
|
||||
*/
|
||||
private fun scrubFolder(dir: File) {
|
||||
dir.listFiles { f -> f.isFile && !f.name.startsWith(".") }?.forEach { f ->
|
||||
/** A file's size and modification time as they stood right after it was scrubbed. */
|
||||
private class Scrubbed(val length: Long, val modified: Long)
|
||||
|
||||
/** Files of a folder as they stood right after scrubbing, filled by [scrubTree] and [copySteamLogs]. */
|
||||
private class Record(val dir: File) {
|
||||
val files = HashMap<File, Scrubbed>()
|
||||
var failed = false
|
||||
}
|
||||
|
||||
private fun scrubFolder(dir: File, record: Record) {
|
||||
dir.listFiles { f -> f.isFile && !f.name.startsWith(".") && f !in record.files }?.forEach { f ->
|
||||
if (!LogRedactor.isText(f)) return@forEach
|
||||
try {
|
||||
val tmp = File(dir, ".${f.name}.scrub")
|
||||
tmp.bufferedWriter().use { w -> LogRedactor.scrubTo(f, w) }
|
||||
if (tmp.length() != f.length() || tmp.readBytes().contentEquals(f.readBytes()).not()) tmp.renameTo(f) else tmp.delete()
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "could not scrub ${f.name}", e)
|
||||
}
|
||||
val done = scrubFile(dir, f)
|
||||
if (done == null) record.failed = true else record.files[f] = done
|
||||
}
|
||||
}
|
||||
|
||||
/** Steam's logs: redacted into steam/, never copied verbatim. */
|
||||
private fun copySteamLogs(context: Context, dir: File) {
|
||||
/**
|
||||
* Puts [f] through the redactor in place. Returns its size and modification time as it then
|
||||
* stands, or null if it could not, and [f] may still hold the original. A writer still
|
||||
* appending to [f] (the app's own log capture) changes its size afterwards, and a share then
|
||||
* scrubs it again.
|
||||
*/
|
||||
private fun scrubFile(dir: File, f: File): Scrubbed? {
|
||||
val tmp = File(dir, ".${f.name}.scrub")
|
||||
return try {
|
||||
val before = Scrubbed(f.length(), f.lastModified())
|
||||
tmp.bufferedWriter().use { w -> LogRedactor.scrubTo(f, w) }
|
||||
val scrubbed = tmp.readBytes()
|
||||
if (scrubbed.contentEquals(f.readBytes())) {
|
||||
tmp.delete()
|
||||
// Unchanged by the redactor, and by anything else while it read.
|
||||
before.takeIf { f.length() == it.length && f.lastModified() == it.modified }
|
||||
} else {
|
||||
// Shared storage can refuse a rename; then the scrubbed bytes are written over the
|
||||
// original instead, so it never stays behind unscrubbed.
|
||||
if (!tmp.renameTo(f)) { f.writeBytes(scrubbed); tmp.delete() }
|
||||
Scrubbed(scrubbed.size.toLong(), f.lastModified()).takeIf { f.length() == it.length }
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "could not scrub ${f.name}", e)
|
||||
tmp.delete()
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Records [record]'s folder as scrubbed - every file went through without a failure - or
|
||||
* leaves it unmarked, so the next share and the pass over older folders scrub it again.
|
||||
*/
|
||||
private fun markScrubbed(record: Record) {
|
||||
val dir = record.dir
|
||||
val tree = File(dir, SCRUBBED_TREE_MARKER)
|
||||
if (record.failed) {
|
||||
tree.delete()
|
||||
Log.w(TAG, "$dir is not fully scrubbed; it is scrubbed again when shared")
|
||||
return
|
||||
}
|
||||
try {
|
||||
File(dir, SCRUBBED_MARKER).writeText("scrubbed ${now()}\n")
|
||||
val lines = StringBuilder("rules ${LogRedactor.RULES_VERSION}\n")
|
||||
record.files.forEach { (f, s) ->
|
||||
lines.append(s.length).append('\t').append(s.modified).append('\t')
|
||||
.append(f.relativeTo(dir).path).append('\n')
|
||||
}
|
||||
tree.writeText(lines.toString())
|
||||
} catch (e: Exception) {
|
||||
tree.delete()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The files of [dir] that its own ending scrubbed and that are unchanged since (same size and
|
||||
* modification time), by path relative to [dir]. Empty when the folder has no such record, or
|
||||
* one made under other redactor rules.
|
||||
*/
|
||||
fun scrubbedFiles(dir: File): Set<String> {
|
||||
val lines = try { File(dir, SCRUBBED_TREE_MARKER).takeIf { it.isFile }?.readLines() } catch (e: Exception) { null }
|
||||
?: return emptySet()
|
||||
if (lines.firstOrNull() != "rules ${LogRedactor.RULES_VERSION}") return emptySet()
|
||||
return lines.drop(1).mapNotNull { line ->
|
||||
val parts = line.split('\t', limit = 3)
|
||||
if (parts.size != 3) return@mapNotNull null
|
||||
val f = File(dir, parts[2])
|
||||
parts[2].takeIf { f.isFile && f.length().toString() == parts[0] && f.lastModified().toString() == parts[1] }
|
||||
}.toSet()
|
||||
}
|
||||
|
||||
/** The end-of-session scrub of [dir] on its own (steam/ already in place), for tests. */
|
||||
@androidx.annotation.VisibleForTesting
|
||||
internal fun scrubAndMark(dir: File) = markScrubbed(scrubTree(Record(dir)))
|
||||
|
||||
/**
|
||||
* [record]'s folder and every folder under it (steam/, droiddeck-esync/): the session script
|
||||
* copied files there verbatim, and a Steam log the app did not copy over again (gone from the
|
||||
* runtime, or past its size limit) stayed as the script left it. Files [copySteamLogs] already
|
||||
* redacted on the way in are in [record] and left alone.
|
||||
*/
|
||||
private fun scrubTree(record: Record): Record {
|
||||
record.dir.walkTopDown().filter { it.isDirectory }.forEach { scrubFolder(it, record) }
|
||||
return record
|
||||
}
|
||||
|
||||
/** Steam's logs: redacted into steam/, never copied verbatim. What it wrote goes in [record]. */
|
||||
private fun copySteamLogs(context: Context, dir: File, record: Record) {
|
||||
val logs = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/logs")
|
||||
if (!logs.isDirectory) return
|
||||
val out = File(dir, "steam").apply { mkdirs() }
|
||||
logs.listFiles { f -> f.isFile && f.length() < 8L * 1024 * 1024 }?.forEach { src ->
|
||||
try {
|
||||
File(out, src.name).bufferedWriter().use { w ->
|
||||
val dst = File(out, src.name)
|
||||
dst.bufferedWriter().use { w ->
|
||||
src.forEachLine { line -> w.write(LogRedactor.redact(line)); w.newLine() }
|
||||
}
|
||||
record.files[dst] = Scrubbed(dst.length(), dst.lastModified())
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "could not scrub ${src.name}", e)
|
||||
}
|
||||
@@ -143,12 +244,11 @@ object SessionArtifacts {
|
||||
"crash.log holds Android's crash buffer as of the next app start - if this\n" +
|
||||
"session died of a crash, the entry is in there unless the device rebooted.\n"
|
||||
)
|
||||
if (newest) {
|
||||
copySteamLogs(context, dir)
|
||||
}
|
||||
val record = Record(dir)
|
||||
if (newest) copySteamLogs(context, dir, record)
|
||||
SessionLogCapture.dumpCrashBuffer(File(dir, "crash.log"))
|
||||
SessionEvents.record("session.artifacts_recovered", mapOf("newest" to newest), dir)
|
||||
scrubFolder(dir)
|
||||
markScrubbed(scrubTree(record))
|
||||
File(dir, COMPLETE_MARKER).writeText("collected: late, at next app start, ${now()}\n")
|
||||
Log.i(TAG, "finished the abandoned session folder $dir")
|
||||
} catch (e: Exception) {
|
||||
|
||||
@@ -6,23 +6,40 @@ import android.view.WindowManager
|
||||
/** The virtual display advertised to the guest, before it is fitted onto the Android panel. */
|
||||
object SessionDisplay {
|
||||
const val MATCH_SCREEN = "screen"
|
||||
const val DEFAULT_RESOLUTION = "1280x720"
|
||||
|
||||
/**
|
||||
* Presets are heights, not sizes: "720p" is the panel's own shape at 720 lines, never narrower
|
||||
* than 16:9 and never taller than the panel (SHAPE_AUTO). The client treats the output as the
|
||||
* games' native resolution, so the height is what bounds a game's default size on a 1440p
|
||||
* phone; the shape is what keeps the client's interface edge to edge on a 20:9 one (1600x720)
|
||||
* and keeps games at 16:9 or wider on a foldable's near-square panel.
|
||||
*/
|
||||
const val DEFAULT_RESOLUTION = "720p"
|
||||
private val PRESET_HEIGHTS = listOf(720, 900, 1080)
|
||||
|
||||
/** The height of a preset choice ("900p"), or null for Match screen and fixed sizes. */
|
||||
fun presetHeight(choice: String): Int? =
|
||||
if (choice.endsWith("p")) choice.dropLast(1).toIntOrNull()?.takeIf { it > 0 } else null
|
||||
|
||||
fun screenSize(panel: Pair<Int, Int>): Pair<Int, Int> =
|
||||
(maxOf(panel.first, panel.second) and 1.inv()) to (minOf(panel.first, panel.second) and 1.inv())
|
||||
|
||||
fun resolveChoice(panel: Pair<Int, Int>, choice: String): Pair<Int, Int> =
|
||||
if (choice == MATCH_SCREEN) screenSize(panel) else {
|
||||
// Legacy displays may exceed the custom dialog's size limit. Keep their exact size.
|
||||
val parts = choice.split('x').map { it.toIntOrNull() }
|
||||
if (parts.size == 2 && parts.all { it != null && it > 0 }) parts[0]!! to parts[1]!!
|
||||
else 1280 to 720
|
||||
}
|
||||
fun resolveChoice(panel: Pair<Int, Int>, choice: String): Pair<Int, Int> {
|
||||
if (choice == MATCH_SCREEN) return screenSize(panel)
|
||||
presetHeight(choice)?.let { return resolve(panel, it, SessionPrefs.SHAPE_AUTO) }
|
||||
// Fixed sizes (custom, or a preset saved before presets were heights) keep their exact size,
|
||||
// including legacy ones past the custom dialog's limit.
|
||||
val parts = choice.split('x').map { it.toIntOrNull() }
|
||||
return if (parts.size == 2 && parts.all { it != null && it > 0 }) parts[0]!! to parts[1]!!
|
||||
else resolve(panel, 720, SessionPrefs.SHAPE_AUTO)
|
||||
}
|
||||
|
||||
/** Fixed dimensions and the current panel, with no duplicate panel-size preset. */
|
||||
fun resolutionOptions(panel: Pair<Int, Int>): List<String> =
|
||||
listOf(DEFAULT_RESOLUTION, "1600x900", "1920x1080")
|
||||
/** The height presets the panel is tall enough for, then the panel itself, with no duplicate sizes. */
|
||||
fun resolutionOptions(panel: Pair<Int, Int>): List<String> {
|
||||
val panelHeight = minOf(panel.first, panel.second)
|
||||
return PRESET_HEIGHTS.filter { it <= panelHeight }.map { "${it}p" }
|
||||
.filter { resolveChoice(panel, it) != screenSize(panel) } + MATCH_SCREEN
|
||||
}
|
||||
|
||||
fun panelSize(context: Context): Pair<Int, Int> {
|
||||
val manager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
|
||||
|
||||
@@ -28,14 +28,18 @@ object SessionFiles {
|
||||
*/
|
||||
fun stage(context: Context, root: File) {
|
||||
GameEnvironmentStore.publish(context)
|
||||
WinComponents.publish(context)
|
||||
val files = arrayOf(
|
||||
"usr/local/bin/droiddeck-game-env" to "usr/local/bin/droiddeck-game-env",
|
||||
"usr/local/bin/droiddeck-wincomponents" to "usr/local/bin/droiddeck-wincomponents",
|
||||
"usr/local/bin/droiddeck-msi-install" to "usr/local/bin/droiddeck-msi-install",
|
||||
"usr/local/bin/droiddeck-esync" to "usr/local/bin/droiddeck-esync",
|
||||
"usr/local/bin/droiddeck-steam-compat" to "usr/local/bin/droiddeck-steam-compat",
|
||||
"usr/local/bin/droiddeck-fex" to "usr/local/bin/droiddeck-fex",
|
||||
"libblsession.so" to "usr/local/lib/libblsession.so",
|
||||
"libfakeinput.so" to "usr/local/lib/libfakeinput.so",
|
||||
"libblfastpath.so" to "usr/local/lib/libblfastpath.so",
|
||||
"libssbs.so" to "usr/local/lib/libssbs.so",
|
||||
"usr/local/bin/droiddeck-session" to "usr/local/bin/droiddeck-session",
|
||||
"usr/local/bin/steam-compatibility" to "usr/local/bin/steam-compatibility",
|
||||
"usr/local/bin/droiddeck-clipboard" to "usr/local/bin/droiddeck-clipboard",
|
||||
@@ -103,6 +107,10 @@ object SessionFiles {
|
||||
"usr/local/lib/mangoapp/libtraceevent.so.1",
|
||||
"usr/local/lib/mangoapp/libtracefs.so.1",
|
||||
).map { it to it }
|
||||
// What the Windows components installer reads .msi packages with (tools/msitools).
|
||||
val msitools = listOf("msiinfo", "cabextract", "libmsi-1.0.so.0", "libgsf-1.so.114", "libgcab-1.0.so.0")
|
||||
.map { "usr/local/lib/droiddeck-msitools/$it" } +
|
||||
listOf("NOTICE", "GPL-2", "GPL-3", "LGPL-2.1").map { "usr/local/share/licenses/droiddeck-msitools/$it" }
|
||||
// The patched wlroots (tools/wlroots) the desktop loads for its vulkan / gles2 renderers.
|
||||
val wlroots = if (File(root, "usr/bin/labwc").isFile) {
|
||||
arrayOf("usr/local/lib/droiddeck-wlroots/libwlroots-0.20.so" to "usr/local/lib/droiddeck-wlroots/libwlroots-0.20.so")
|
||||
@@ -114,7 +122,7 @@ object SessionFiles {
|
||||
"usr/local/bin/gamescope" to "usr/local/bin/gamescope",
|
||||
"usr/local/lib/droiddeck/uruntime" to "usr/local/lib/droiddeck/uruntime",
|
||||
"usr/local/share/licenses/uruntime/LICENSE" to "usr/local/share/licenses/uruntime/LICENSE",
|
||||
) + wlroots + mangoapp + fexPreloads).filter { (asset, _) ->
|
||||
) + wlroots + mangoapp + msitools.map { it to it } + fexPreloads).filter { (asset, _) ->
|
||||
val dir = asset.substringBeforeLast('/')
|
||||
runCatching { context.assets.list("linuxfs/$dir")?.contains(asset.substringAfterLast('/')) == true }.getOrDefault(false)
|
||||
}
|
||||
|
||||
@@ -3,6 +3,12 @@ package com.droiddeck.launcher.session
|
||||
import android.content.ClipData
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.util.Log
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.core.content.FileProvider
|
||||
import com.droiddeck.launcher.core.LogRedactor
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
@@ -16,32 +22,74 @@ import java.util.zip.ZipOutputStream
|
||||
* it) and landed in the app's private files instead, which a user cannot otherwise reach.
|
||||
*/
|
||||
object SessionLogShare {
|
||||
private val main = Handler(Looper.getMainLooper())
|
||||
|
||||
/**
|
||||
* How far the zip for a share has got, 0..1, or null when none is being made. The Share logs
|
||||
* buttons show it in place of their label, so a tap is answered at once.
|
||||
*/
|
||||
var progress by mutableStateOf<Float?>(null)
|
||||
private set
|
||||
|
||||
/**
|
||||
* Zips [folder] on a worker thread with [progress] following along, then hands the zip (null
|
||||
* if there was nothing to zip or it failed) to [done] on the main thread. Call on the main
|
||||
* thread; a tap while a zip is being made is ignored.
|
||||
*/
|
||||
fun prepare(context: Context, folder: () -> File?, done: (File?) -> Unit) {
|
||||
if (progress != null) return
|
||||
progress = 0f
|
||||
Thread({
|
||||
val zip = runCatching { folder()?.let { dir -> zipFolder(context, dir) { p -> main.post { if (progress != null) progress = p } } } }
|
||||
.onFailure { Log.w("SessionLogShare", "could not package session logs", it) }
|
||||
.getOrNull()
|
||||
main.post { progress = null; done(zip) }
|
||||
}, "share-logs").start()
|
||||
}
|
||||
|
||||
/** The newest session folder in either place logs are written, or null if there is none. */
|
||||
fun latest(context: Context): File? = SessionPaths.sessionFolders(context).lastOrNull()
|
||||
|
||||
/** Builds the zip (blocking). Returns null when there is no session to share. */
|
||||
fun zipLatest(context: Context): File? = latest(context)?.let { zipFolder(context, it) }
|
||||
|
||||
/** Builds a zip for one specific session folder (blocking). */
|
||||
fun zipFolder(context: Context, folder: File): File? {
|
||||
fun zipFolder(context: Context, folder: File, onProgress: ((Float) -> Unit)? = null): File? {
|
||||
if (!folder.isDirectory) return null
|
||||
val files = folder.walkTopDown().filter { it.isFile }.toList()
|
||||
// The client's logs past STEAM_LOG_MAX_BYTES stay out, as they do from the app's own copy: a
|
||||
// CEF debug log or an old *.previous.txt reached 17 MB, every share scrubbed them line by
|
||||
// line, and the share sheet took ten seconds to appear.
|
||||
val files = folder.walkTopDown().filter { it.isFile }
|
||||
.filterNot { it.parentFile?.name == "steam" && it.length() > STEAM_LOG_MAX_BYTES }.toList()
|
||||
if (files.isEmpty()) return null
|
||||
val out = File(context.cacheDir, "shared-logs").apply { deleteRecursively(); mkdirs() }
|
||||
val zip = File(out, "DroidDeck-${folder.name}.zip")
|
||||
// Scrubbed on the way into the zip: a session shared while it runs has not had its end-of-
|
||||
// session pass yet, and the redactor changes nothing in a line that is already clean.
|
||||
LogRedactor.learnFromRuntime(LinuxRuntime.rootDir(context))
|
||||
// A finished folder was scrubbed whole when it ended. A file its record lists, unchanged
|
||||
// since, goes in as it is; anything else (added or changed since, hidden, or any file of a
|
||||
// session still running) is scrubbed again. Scrubbing tens of MB of the client's logs on
|
||||
// every share kept the share sheet from appearing for ten seconds or more.
|
||||
val scrubbed = SessionArtifacts.scrubbedFiles(folder)
|
||||
val live = liveSteamLogs(context, folder)
|
||||
val total = (files + live).sumOf { it.length() }.coerceAtLeast(1L)
|
||||
var done = 0L
|
||||
var shown = -1
|
||||
fun advance(f: File) {
|
||||
done += f.length()
|
||||
val percent = (done * 100 / total).toInt()
|
||||
if (percent != shown) { shown = percent; onProgress?.invoke(percent / 100f) }
|
||||
}
|
||||
ZipOutputStream(zip.outputStream().buffered()).use { z ->
|
||||
files.forEach { f -> addEntry(z, folder.name + "/" + f.relativeTo(folder).path, f) }
|
||||
liveSteamLogs(context, folder).forEach { f -> addEntry(z, folder.name + "/steam/" + f.name, f) }
|
||||
files.forEach { f -> addEntry(z, folder.name + "/" + f.relativeTo(folder).path, f, f.relativeTo(folder).path in scrubbed); advance(f) }
|
||||
live.forEach { f -> addEntry(z, folder.name + "/steam/" + f.name, f, false); advance(f) }
|
||||
}
|
||||
return zip
|
||||
}
|
||||
|
||||
private fun addEntry(z: ZipOutputStream, name: String, f: File) {
|
||||
private fun addEntry(z: ZipOutputStream, name: String, f: File, scrubbed: Boolean) {
|
||||
z.putNextEntry(ZipEntry(name))
|
||||
if (LogRedactor.isText(f)) {
|
||||
if (!scrubbed && LogRedactor.isText(f)) {
|
||||
val w = z.bufferedWriter()
|
||||
LogRedactor.scrubTo(f, w)
|
||||
w.flush()
|
||||
|
||||
@@ -165,40 +165,12 @@ object SessionPrefs {
|
||||
prefs(context).edit().putBoolean("clientDirectAudio", on).apply()
|
||||
}
|
||||
|
||||
/**
|
||||
* Steam only: gamescope makes every game window the size of the screen. A game that resizes
|
||||
* its own window when it loses focus (FlatOut) otherwise comes back smaller, drawn in a
|
||||
* corner; a game that sets its own resolution and never looks at its window again (Quake 3)
|
||||
* instead draws small in the bottom-left of the stretched one. A game whose resolution differs
|
||||
* from the screen's (DiRT 3 at 1280x720) fights it: it rebuilds its swapchain on every forced
|
||||
* resize and the picture flickers between its own size and the screen's, often from the first
|
||||
* menu, before the player can reach its resolution setting. Off unless turned on.
|
||||
*/
|
||||
fun forceFullscreen(context: Context): Boolean = prefs(context).getBoolean("forceFullscreen", false)
|
||||
|
||||
fun setForceFullscreen(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("forceFullscreen", on).apply()
|
||||
writeForceFullscreenFlag(context)
|
||||
}
|
||||
|
||||
fun stretch16x9(context: Context): Boolean = prefs(context).getBoolean("stretch16x9", false)
|
||||
|
||||
fun setStretch16x9(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("stretch16x9", on).apply()
|
||||
}
|
||||
|
||||
/**
|
||||
* The same choice as a file the running session watches, so the drawer can change it live:
|
||||
* the session hands every change to gamescope, which reads GAMESCOPE_FORCE_WINDOWS_FULLSCREEN
|
||||
* off its root window whenever it changes. Written again at every session start so a file left
|
||||
* by an earlier session never disagrees with the setting.
|
||||
*/
|
||||
fun writeForceFullscreenFlag(context: Context) {
|
||||
runCatching {
|
||||
java.io.File(com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(context), "root/.droiddeck-fill")
|
||||
.writeText(if (forceFullscreen(context)) "1\n" else "0\n")
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* DirectAudio for games: their Wine audio driver talks to the relay helper on this side. On
|
||||
@@ -495,6 +467,14 @@ object SessionPrefs {
|
||||
prefs(context).edit().putBoolean("storageDiagnostics", on).apply()
|
||||
}
|
||||
|
||||
/** Experimental: Steam's space reservation on the second library reports success untouched. */
|
||||
fun skipLibraryPreallocation(context: Context): Boolean =
|
||||
prefs(context).getBoolean("skipLibraryPreallocation", false)
|
||||
|
||||
fun setSkipLibraryPreallocation(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("skipLibraryPreallocation", on).apply()
|
||||
}
|
||||
|
||||
// ── Per-mode display ────────────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
@@ -516,7 +496,7 @@ object SessionPrefs {
|
||||
fun resolutionChoice(context: Context, mode: String, panel: Pair<Int, Int>): String {
|
||||
val saved = prefs(context)
|
||||
saved.getString("displayResolution.$mode", null)?.let { value ->
|
||||
if (value == SessionDisplay.MATCH_SCREEN) return value
|
||||
if (value == SessionDisplay.MATCH_SCREEN || SessionDisplay.presetHeight(value) != null) return value
|
||||
parseResolution(value)?.let { return "${it.first}x${it.second}" }
|
||||
}
|
||||
if (!resolutionChosen(context, mode) && !saved.contains("shape")) return SessionDisplay.DEFAULT_RESOLUTION
|
||||
@@ -526,7 +506,7 @@ object SessionPrefs {
|
||||
}
|
||||
|
||||
fun setResolutionChoice(context: Context, mode: String, choice: String) {
|
||||
val value = if (choice == SessionDisplay.MATCH_SCREEN) choice else {
|
||||
val value = if (choice == SessionDisplay.MATCH_SCREEN || SessionDisplay.presetHeight(choice) != null) choice else {
|
||||
val size = requireNotNull(parseResolution(choice)) { "Invalid resolution" }
|
||||
"${size.first}x${size.second}"
|
||||
}
|
||||
@@ -543,6 +523,22 @@ object SessionPrefs {
|
||||
|
||||
private const val DEFAULT_FEX_PRESET = "PERFORMANCE_TSO"
|
||||
|
||||
/**
|
||||
* Force SSBS for Proton games: Wine resumes threads from a Windows CONTEXT that never carries
|
||||
* PSTATE.SSBS, so they run with speculative store bypass disabled; libssbs.so keeps it set
|
||||
* (on DiRT 3 / GE-Proton: from ~99% of a game's threads running without it to none). The
|
||||
* speed-up is reported on Oryon cores (Snapdragon 8 Elite) and was not measurable on an
|
||||
* 8 Gen 3, so it is off unless turned on. A game's own environment can still say
|
||||
* DROIDDECK_FORCE_SSBS=0.
|
||||
*/
|
||||
fun forceSsbs(context: Context): Boolean = prefs(context).getBoolean("forceSsbs", false)
|
||||
|
||||
fun setForceSsbs(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("forceSsbs", on).apply()
|
||||
runCatching { GameEnvironmentStore.publish(context) }
|
||||
.onFailure { android.util.Log.e("GameEnvironment", "Could not update game environment", it) }
|
||||
}
|
||||
|
||||
fun setFexPreset(context: Context, id: String) {
|
||||
prefs(context).edit().putString("fexPreset", id).apply()
|
||||
runCatching { GameEnvironmentStore.publish(context) }
|
||||
|
||||
@@ -309,6 +309,14 @@ class SessionService : Service() {
|
||||
// The desktop's Steam launchers start the client there (droiddeck-steam-launch), through the
|
||||
// same set-up as a Steam session: it gets what the client and its games are started with.
|
||||
val steamHere = SessionState.mode == MODE_STEAM || SessionState.mode == MODE_DESKTOP
|
||||
// Some GPUs need a component Proton does not ship. Apply those before the guest, so the
|
||||
// next game launch copies them into the prefix. A download failure is logged and the
|
||||
// session still starts; the next session tries again.
|
||||
if (steamHere) {
|
||||
runCatching { ComponentsManager.ensureForcedPackages(this) }
|
||||
.onSuccess { if (it != null) Log.i(TAG, it) }
|
||||
.onFailure { Log.w(TAG, "forced components", it) }
|
||||
}
|
||||
addClientEnvironment(guest, steamHere)
|
||||
// Where the fast path's description of proot's view goes, once the binds are known.
|
||||
val fastPathAt = guest.size
|
||||
@@ -408,6 +416,9 @@ class SessionService : Service() {
|
||||
guest.addAll(fastPathAt, env)
|
||||
shellGuest.addAll(fastPathAt, env)
|
||||
Log.i(TAG, "proot: fast path on (${prootBinds.size} binds)")
|
||||
} ?: run {
|
||||
Log.w(TAG, "proot: fast path off - ${prootBinds.size} binds (it holds ${ProotFastPath.MAX_BINDS}) or a path it cannot be told")
|
||||
null
|
||||
}
|
||||
} else null
|
||||
|
||||
@@ -596,9 +607,7 @@ class SessionService : Service() {
|
||||
if (SessionState.mode == MODE_STEAM) guest.add("BL_MANGOAPP=" + (if (SessionPrefs.mangoapp(this)) "1" else "0"))
|
||||
if (steamHere) guest.add("BL_STEAM_CHANNEL=" + SessionPrefs.steamChannel(this))
|
||||
if (SessionState.mode == MODE_STEAM) {
|
||||
guest.add("BL_GAMESCOPE_FORCE_FULLSCREEN=" + (if (SessionPrefs.forceFullscreen(this)) "1" else "0"))
|
||||
guest.add("BL_GAMESCOPE_STRETCH_16X9=" + (if (SessionPrefs.stretch16x9(this)) "1" else "0"))
|
||||
SessionPrefs.writeForceFullscreenFlag(this)
|
||||
}
|
||||
// Proton's own gate for its xalia helper (its `proton` script reads this, and sets
|
||||
// XALIA_SUPPORTED_ONLY itself otherwise). Skipped by default: under FEX it costs every game
|
||||
@@ -817,6 +826,20 @@ class SessionService : Service() {
|
||||
} else {
|
||||
Log.i(TAG, "game storage: internal only")
|
||||
}
|
||||
// guest already has the session command at this point. These go with the `env -i`
|
||||
// assignments so they reach the Steam process instead of becoming script args.
|
||||
val storageEnv = ArrayList<String>()
|
||||
val skipLibrary = storageDiagnosticLibrary
|
||||
if (SessionState.mode == MODE_STEAM && skipLibrary != null && SessionPrefs.skipLibraryPreallocation(this)) {
|
||||
val device = runCatching { android.system.Os.stat(skipLibrary.absolutePath).st_dev }.getOrNull()
|
||||
if (device != null) {
|
||||
storageEnv.add("BL_STORAGE_DEVICE=$device")
|
||||
storageEnv.add("BL_STORAGE_PREALLOCATE_SKIP=1")
|
||||
Log.i(TAG, "game storage: Steam's space reservation on the second library is skipped")
|
||||
} else {
|
||||
Log.w(TAG, "game storage: library could not be identified; space reservation not skipped")
|
||||
}
|
||||
}
|
||||
if (SessionState.mode == MODE_STEAM && SessionPrefs.storageDiagnosticsEnabled(this)) {
|
||||
val target = storageDiagnosticLibrary ?: File(LinuxRuntime.rootDir(this), "root/.local/share/Steam")
|
||||
val device = StorageDiagnostics.writeSnapshot(
|
||||
@@ -827,16 +850,18 @@ class SessionService : Service() {
|
||||
} ?: false,
|
||||
)
|
||||
if (device != null) {
|
||||
// guest already has the session command at this point. Put these with the `env -i`
|
||||
// assignments so they reach the Steam process instead of becoming script args.
|
||||
val envAt = guest.indexOf(LinuxRuntime.SESSION_SCRIPT).takeIf { it >= 0 } ?: guest.size
|
||||
guest.add(envAt, "BL_STORAGE_DIAGNOSTICS=1")
|
||||
guest.add(envAt + 1, "BL_STORAGE_DEVICE=$device")
|
||||
guest.add(envAt + 2, "BL_STORAGE_LOG=${File(sessionDir, "storage.log").absolutePath}")
|
||||
// Both observe the same library, so a device the skip already set is the same one.
|
||||
if (storageEnv.none { it.startsWith("BL_STORAGE_DEVICE=") }) storageEnv.add("BL_STORAGE_DEVICE=$device")
|
||||
storageEnv.add("BL_STORAGE_DIAGNOSTICS=1")
|
||||
storageEnv.add("BL_STORAGE_LOG=${File(sessionDir, "storage.log").absolutePath}")
|
||||
} else {
|
||||
Log.w(TAG, "storage diagnostics: selected library could not be identified; metadata snapshot only")
|
||||
}
|
||||
}
|
||||
if (storageEnv.isNotEmpty()) {
|
||||
val envAt = guest.indexOf(LinuxRuntime.SESSION_SCRIPT).takeIf { it >= 0 } ?: guest.size
|
||||
guest.addAll(envAt, storageEnv)
|
||||
}
|
||||
// The user's own games folder (the Steam cog's "Added games"), bound at a fixed place so
|
||||
// the shortcuts the app writes point somewhere whatever storage the folder is on.
|
||||
for (root in com.droiddeck.launcher.frontend.AddedGames.roots(this)) {
|
||||
@@ -1278,7 +1303,7 @@ class SessionService : Service() {
|
||||
}
|
||||
nativeSleepTimeout = timeout
|
||||
// A missing or stalled guest helper must not keep the device awake indefinitely.
|
||||
mainHandler.postDelayed(timeout, 10000L)
|
||||
mainHandler.postDelayed(timeout, 4000L)
|
||||
}
|
||||
|
||||
private fun completeNativeSleep() {
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
/**
|
||||
* What to call a catalog component on screen. Bannerlator's catalog keys (vcredist2010_dll,
|
||||
* oalinst_dll, d3dcompiler_47...) have no display name, and some descriptions do not fit the entry,
|
||||
* so names come from here: families by pattern, the rest from a table, the key itself otherwise.
|
||||
* The "_dll" twin of an installer (the direct DLL copy) shares the installer's name.
|
||||
*/
|
||||
object WinComponentNames {
|
||||
private val TABLE = mapOf(
|
||||
"oalinst" to "OpenAL", "XLiveRedist" to "Games for Windows Live", "gfw" to "Games for Windows Live",
|
||||
"physx" to "NVIDIA PhysX", "xact" to "DirectX XACT audio", "xact_x64" to "DirectX XACT audio (64-bit)",
|
||||
"xinput" to "XInput", "xna31" to "XNA Framework 3.1", "xna40" to "XNA Framework 4.0",
|
||||
"d3dx9" to "DirectX 9 (d3dx9)", "d3dx11" to "DirectX 11 (d3dx11)",
|
||||
"directmusic" to "DirectMusic", "directplay" to "DirectPlay", "directshow" to "DirectShow",
|
||||
"dsound" to "DirectSound", "dx8vb" to "DirectX 8 for Visual Basic", "mediafoundation" to "Media Foundation",
|
||||
"quartz" to "DirectShow (quartz)", "amstream" to "DirectShow streams (amstream)", "devenum" to "DirectShow devices (devenum)",
|
||||
"cnc-ddraw" to "cnc-ddraw (DirectDraw)", "gdiplus" to "GDI+", "gecko" to "Wine Gecko", "mono" to "Wine Mono",
|
||||
"vcredist6" to "Visual C++ 6", "vcredist6sp6" to "Visual C++ 6 SP6",
|
||||
"vcredist2015" to "Visual C++ 2015", "vcredist2019" to "Visual C++ 2015-2019", "vcredist2022" to "Visual C++ 2015-2022",
|
||||
"vbrun6" to "Visual Basic 6 runtime", "mfc40" to "MFC 4.0", "mfc42" to "MFC 4.2",
|
||||
"dotnetcore3" to ".NET Core 3", "dotnetcoredesktop3" to ".NET Desktop 3", "dotnetcoredesktop6" to ".NET Desktop 6",
|
||||
"dotnetcoredesktop7" to ".NET Desktop 7", "dotnetcoredesktop8" to ".NET Desktop 8", "dotnet50" to ".NET 5",
|
||||
"webview2" to "Microsoft WebView2", "powershell" to "PowerShell", "powershell_core" to "PowerShell Core",
|
||||
"K-Lite" to "K-Lite Codec Pack", "VulkanRT" to "Vulkan Runtime", "ffdshow" to "ffdshow codecs",
|
||||
"lavfilters702" to "LAV Filters 0.70.2", "lavfilters741" to "LAV Filters 0.74.1", "quicktime72" to "QuickTime 7.2",
|
||||
"cjkfonts" to "CJK fonts", "jet40" to "Jet 4.0 database", "mdac28" to "MDAC 2.8", "wsh57" to "Windows Script Host 5.7",
|
||||
"riched20" to "RichEdit 2.0", "msftedit" to "RichEdit 4.1 (msftedit)", "sqlite3" to "SQLite 3",
|
||||
"win7" to "Windows 7 mode", "winXP" to "Windows XP mode", "gmdls" to "General MIDI sounds (gm.dls)",
|
||||
)
|
||||
private val VCREDIST = Regex("vcredist(\\d{4})")
|
||||
private val DOTNET = Regex("dotnet(\\d)(\\d)(\\d?)(sp\\d)?")
|
||||
private val D3DCOMPILER = Regex("d3dcompiler_(\\d+)")
|
||||
private val MSXML = Regex("msxml(\\d)")
|
||||
private val MONO = Regex("mono-([\\d.]+)")
|
||||
private val XAUDIO = Regex("xaudio([\\d.]+)")
|
||||
|
||||
fun of(id: String): String {
|
||||
val base = id.removeSuffix("_dll")
|
||||
TABLE[base]?.let { return it }
|
||||
VCREDIST.matchEntire(base)?.let { return "Visual C++ " + it.groupValues[1] }
|
||||
DOTNET.matchEntire(base)?.let { m ->
|
||||
val (major, minor, patch, sp) = m.destructured
|
||||
return ".NET Framework $major.$minor" + (if (patch.isNotEmpty()) ".$patch" else "") +
|
||||
(if (sp.isNotEmpty()) " " + sp.uppercase() else "")
|
||||
}
|
||||
D3DCOMPILER.matchEntire(base)?.let { return "D3DCompiler " + it.groupValues[1] }
|
||||
MSXML.matchEntire(base)?.let { return "MSXML " + it.groupValues[1] }
|
||||
MONO.matchEntire(base)?.let { return "Wine Mono " + it.groupValues[1] }
|
||||
XAUDIO.matchEntire(base)?.let { return "XAudio " + it.groupValues[1] }
|
||||
if (base.startsWith("dm") || base == "dswave" || base == "dsdmo") return "DirectMusic ($base)"
|
||||
return id
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,399 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.content.Context
|
||||
import android.util.AtomicFile
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.core.ArchivePaths
|
||||
import com.droiddeck.launcher.core.Downloader
|
||||
import com.droiddeck.launcher.core.FileUtils
|
||||
import com.droiddeck.launcher.runtime.GuestCommand
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream
|
||||
import org.apache.commons.compress.compressors.xz.XZCompressorInputStream
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.io.BufferedInputStream
|
||||
import java.io.File
|
||||
import java.io.FileInputStream
|
||||
import java.io.FileOutputStream
|
||||
import java.security.MessageDigest
|
||||
import java.util.zip.ZipInputStream
|
||||
|
||||
/**
|
||||
* Windows components (OpenAL, d3dx9, XAudio, VC++ DLLs...) for a game's Proton prefix, picked per
|
||||
* game, from Bannerlator's catalog (components.json on winlator-contents, Bottles' manifest format).
|
||||
*
|
||||
* Installing one runs its steps once, into the runtime: the archives it names are downloaded and
|
||||
* its DLLs copied to /opt/droiddeck/wincomponents/<name>/{system32,syswow64}, with component.json
|
||||
* holding its DLL overrides and the components it bundles. The picks go to the runtime as
|
||||
* ~/.config/droiddeck/wincomponents.json, and droiddeck-wincomponents copies the picked components
|
||||
* into the game's prefix at every launch (see that script for why every launch).
|
||||
*
|
||||
* A component whose installer is a Windows Installer package (.msi: XNA, PhysX, Games for Windows
|
||||
* Live, MSXML...) installs here too, without running it: droiddeck-msi-install reads the package's
|
||||
* tables in the runtime and lays out its files (Program Files, the .NET GAC, winsxs) and registry
|
||||
* values the way Wine's msiexec would, under the same store folder. One that runs any other
|
||||
* installer (.exe), unpacks a cabinet or edits the prefix's registry by itself is listed with the
|
||||
* reason it cannot be installed yet.
|
||||
*/
|
||||
object WinComponents {
|
||||
private const val TAG = "WinComponents"
|
||||
const val CATALOG_URL = "https://raw.githubusercontent.com/The412Banner/winlator-contents/main/components.json"
|
||||
private const val SELECTION = "wincomponents.json"
|
||||
private const val GUEST_SELECTION = "root/.config/droiddeck/wincomponents.json"
|
||||
private const val STORE = "opt/droiddeck/wincomponents"
|
||||
private val ID = Regex("[A-Za-z0-9][A-Za-z0-9._-]{0,63}")
|
||||
// register_dll is left out on purpose: the DLLs it names are ones Wine ships and has registered
|
||||
// at the same path, so the native file at that path is the one the registration loads.
|
||||
private val FILE_STEPS = setOf("download_archive", "archive_extract", "copy_dll", "copy_file", "override_dll", "register_dll")
|
||||
private val INSTALLER_STEPS = setOf("install_exe", "install_msi")
|
||||
private const val MSI_INSTALL = "/usr/local/bin/droiddeck-msi-install"
|
||||
/** Where a downloaded .msi waits for the installer, inside the runtime so it can read it. */
|
||||
private const val MSI_CACHE = "$STORE/.packages"
|
||||
/** Catalog entries Proton already provides newer copies of, which an install would only shadow. */
|
||||
private val PROTON_PROVIDES = setOf("gecko")
|
||||
|
||||
fun validId(id: String): Boolean = ID.matches(id) && ".." !in id
|
||||
|
||||
class Step(val action: String, val json: JSONObject) {
|
||||
fun str(key: String): String = json.optString(key, "")
|
||||
}
|
||||
|
||||
class Component(
|
||||
val name: String, val description: String, val provider: String, val status: String,
|
||||
val dependencies: List<String>, val steps: List<Step>,
|
||||
)
|
||||
|
||||
enum class Support { READY, NEEDS_INSTALLER, UNSUPPORTED }
|
||||
|
||||
/** A step that installs a Windows Installer package, which droiddeck-msi-install does here. */
|
||||
private fun isMsi(step: Step): Boolean = step.action in INSTALLER_STEPS && step.str("url").startsWith("https://") &&
|
||||
(step.action == "install_msi" || listOf(step.str("file_name"), step.str("url").substringBefore('?'))
|
||||
.any { it.endsWith(".msi", ignoreCase = true) })
|
||||
|
||||
fun fetch(): List<Component>? {
|
||||
val body = Downloader.downloadString(CATALOG_URL) ?: return null
|
||||
return try {
|
||||
val arr = JSONObject(body).getJSONArray("components")
|
||||
(0 until arr.length()).mapNotNull { i ->
|
||||
val o = arr.getJSONObject(i)
|
||||
val name = o.optString("name")
|
||||
if (!validId(name)) return@mapNotNull null
|
||||
val steps = o.optJSONArray("steps") ?: JSONArray()
|
||||
val deps = o.optJSONArray("dependencies") ?: JSONArray()
|
||||
Component(
|
||||
name, o.optString("description"), o.optString("provider"), o.optString("status"),
|
||||
(0 until deps.length()).map { deps.getString(it) }.filter { validId(it) },
|
||||
(0 until steps.length()).map { steps.getJSONObject(it).let { s -> Step(s.optString("action"), s) } },
|
||||
)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "catalog: $e"); null
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether [c] can be installed here, its bundled components included. */
|
||||
fun support(c: Component, all: Map<String, Component>, depth: Int = 0): Support {
|
||||
if (c.status != "ready" || depth > 8 || c.name in PROTON_PROVIDES) return Support.UNSUPPORTED
|
||||
val installers = c.steps.filter { it.action in INSTALLER_STEPS }
|
||||
val own = when {
|
||||
installers.isNotEmpty() && installers.all { isMsi(it) } &&
|
||||
c.steps.all { it in installers || it.action == "delete_dlls" || it.action in FILE_STEPS && fileStepOk(it) } -> Support.READY
|
||||
installers.isNotEmpty() -> Support.NEEDS_INSTALLER
|
||||
c.steps.all { it.action in FILE_STEPS && fileStepOk(it) } -> Support.READY
|
||||
else -> Support.UNSUPPORTED
|
||||
}
|
||||
if (own != Support.READY) return own
|
||||
return c.dependencies.map { all[it]?.let { d -> support(d, all, depth + 1) } ?: Support.UNSUPPORTED }
|
||||
.maxOrNull() ?: Support.READY
|
||||
}
|
||||
|
||||
private fun fileStepOk(step: Step): Boolean = when (step.action) {
|
||||
"download_archive", "archive_extract" -> step.str("url").let { url ->
|
||||
!url.startsWith("http") || url.startsWith("https://github.com/") &&
|
||||
url.substringBefore('?').let { it.endsWith(".tar.xz") || it.endsWith(".zip") }
|
||||
}
|
||||
"copy_dll", "copy_file" -> ".." !in step.str("dest")
|
||||
else -> true
|
||||
}
|
||||
|
||||
/** The installed version of a component, or null. */
|
||||
fun installed(context: Context, id: String): String? = runCatching {
|
||||
JSONObject(File(LinuxRuntime.rootDir(context), "$STORE/$id/component.json").readText()).optString("version", "?")
|
||||
}.getOrNull()
|
||||
|
||||
/** Every component in the runtime, by id. */
|
||||
fun installedIds(context: Context): List<String> =
|
||||
File(LinuxRuntime.rootDir(context), STORE).listFiles { f -> f.isDirectory && validId(f.name) }
|
||||
.orEmpty().map { it.name }.filter { installed(context, it) != null }.sorted()
|
||||
|
||||
/**
|
||||
* Installs [c] and the components it bundles that are not installed yet. [onProgress] gets a
|
||||
* line for the step and 0..100 (or -1). Returns null on success, else a message.
|
||||
*/
|
||||
fun install(context: Context, c: Component, all: Map<String, Component>, onProgress: (String, Int) -> Unit): String? {
|
||||
if (support(c, all) != Support.READY) return "${c.name} cannot be installed here yet"
|
||||
val order = ArrayList<Component>()
|
||||
fun visit(x: Component, depth: Int) {
|
||||
if (depth > 8 || order.any { it.name == x.name }) return
|
||||
x.dependencies.mapNotNull { all[it] }.forEach { visit(it, depth + 1) }
|
||||
if (x.name == c.name || installed(context, x.name) == null) order.add(x)
|
||||
}
|
||||
visit(c, 0)
|
||||
// One download per archive however many components copy out of it (DirectMusic's eleven
|
||||
// parts all come from dxnt, 100 MB).
|
||||
val work = File(context.cacheDir, "wincomponents").apply { FileUtils.delete(this); mkdirs() }
|
||||
val archives = HashMap<String, File>()
|
||||
return try {
|
||||
for (x in order) {
|
||||
onProgress(x.name, -1)
|
||||
installOne(context, x, work, archives, onProgress)?.let { return "${x.name}: $it" }
|
||||
}
|
||||
null
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "install ${c.name}", e)
|
||||
e.message ?: "Install failed"
|
||||
} finally {
|
||||
FileUtils.delete(work)
|
||||
}
|
||||
}
|
||||
|
||||
private fun installOne(context: Context, c: Component, work: File, archives: HashMap<String, File>, onProgress: (String, Int) -> Unit): String? {
|
||||
val root = LinuxRuntime.rootDir(context)
|
||||
if (!root.isDirectory) return "The Linux runtime is not installed"
|
||||
val staging = File(root, "$STORE/.${c.name}.new").apply { FileUtils.delete(this); mkdirs() }
|
||||
val overrides = ArrayList<String>()
|
||||
var source: File? = null
|
||||
var msi: JSONObject? = null
|
||||
for (step in c.steps) when (step.action) {
|
||||
// A component may have several packages (PowerShell's 32- and 64-bit): each adds to the
|
||||
// same folder, the first one names the component.
|
||||
"install_msi", "install_exe" -> {
|
||||
val (result, problem) = installMsi(context, c, step, staging, onProgress)
|
||||
if (result == null) return problem
|
||||
msi = msi?.apply {
|
||||
val notes = optJSONArray("notes") ?: JSONArray().also { put("notes", it) }
|
||||
result.optJSONArray("notes")?.let { for (i in 0 until it.length()) notes.put(it.get(i)) }
|
||||
} ?: result
|
||||
}
|
||||
// A catalog step that makes room for the installer's own copy; ours is copied anyway.
|
||||
"delete_dlls" -> Unit
|
||||
"download_archive", "archive_extract" -> {
|
||||
val url = step.str("url")
|
||||
if (!url.startsWith("http")) continue
|
||||
source = archives[url] ?: run {
|
||||
val name = url.substringBefore('?').substringAfterLast('/')
|
||||
val file = File(work, "${archives.size}-$name")
|
||||
val ok = Downloader.downloadFile(url, file, false) { f -> onProgress("${c.name}: $name", if (f < 0) -1 else Math.round(f * 100f)) }
|
||||
if (!ok) return "download failed: $name"
|
||||
step.str("file_checksum").takeIf { it.length == 32 }?.let { md5 ->
|
||||
if (!digest(file, "MD5").equals(md5, ignoreCase = true)) return "checksum mismatch: $name"
|
||||
}
|
||||
onProgress("${c.name}: unpacking $name", -1)
|
||||
val dir = File(work, "${archives.size}-x").apply { mkdirs() }
|
||||
if (!extract(file, dir)) return "could not unpack $name"
|
||||
file.delete()
|
||||
dir.also { archives[url] = it }
|
||||
}
|
||||
}
|
||||
"copy_dll", "copy_file" -> {
|
||||
val from = source ?: return "a copy step before any archive"
|
||||
val dest = step.str("dest")
|
||||
val (arch, base) = when (dest.substringBefore('/').lowercase()) {
|
||||
"win64", "system32" -> "win64" to "system32"
|
||||
"win32", "syswow64" -> "win32" to "syswow64"
|
||||
else -> null to "system32"
|
||||
}
|
||||
val sub = dest.substringAfter('/', "")
|
||||
copyMatching(from, step.str("file_name"), File(staging, if (sub.isEmpty()) base else "$base/$sub"), arch)
|
||||
}
|
||||
"override_dll" -> {
|
||||
fun add(dll: String, type: String) {
|
||||
if (dll.isEmpty()) return
|
||||
overrides += when (type.ifEmpty { "native,builtin" }) {
|
||||
"native,builtin" -> dll
|
||||
"native" -> "$dll=n"
|
||||
"builtin" -> "$dll=b"
|
||||
"builtin,native" -> "$dll=b,n"
|
||||
else -> dll
|
||||
}
|
||||
}
|
||||
add(step.str("dll"), step.str("type"))
|
||||
step.json.optJSONArray("bundle")?.let { b ->
|
||||
for (i in 0 until b.length()) b.getJSONObject(i).let { add(it.optString("value"), it.optString("data")) }
|
||||
}
|
||||
}
|
||||
"register_dll" -> Unit
|
||||
else -> return "unsupported step ${step.action}"
|
||||
}
|
||||
val version = msi?.optString("version")?.takeIf { it.isNotEmpty() }
|
||||
?: Regex("""\b(\d+\.\d+(\.\d+)*)\b""").find(c.description)?.value ?: "catalog"
|
||||
val meta = JSONObject()
|
||||
.put("id", c.name).put("version", version)
|
||||
.put("overrides", JSONArray(overrides.distinct()))
|
||||
.put("requires", JSONArray(c.dependencies))
|
||||
msi?.let { meta.put("kind", "msi").put("product", it.optString("product")).put("notes", it.optJSONArray("notes") ?: JSONArray()) }
|
||||
FileUtils.writeString(File(staging, "component.json"), meta.toString(1))
|
||||
val target = File(root, "$STORE/${c.name}")
|
||||
FileUtils.delete(target)
|
||||
if (!staging.renameTo(target)) return "could not place the files"
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* Downloads the component's .msi into the runtime and has droiddeck-msi-install lay it out in
|
||||
* [staging]. Returns the installer's result (product, version, counts, notes), or null and why.
|
||||
* Everything the installer prints also goes to Download/DroidDeck/tools.
|
||||
*/
|
||||
private fun installMsi(context: Context, c: Component, step: Step, staging: File, onProgress: (String, Int) -> Unit): Pair<JSONObject?, String> {
|
||||
val root = LinuxRuntime.rootDir(context)
|
||||
val url = step.str("url")
|
||||
val name = url.substringBefore('?').substringAfterLast('/')
|
||||
val cache = File(root, MSI_CACHE).apply { mkdirs() }
|
||||
val file = File(cache, "${c.name}.msi")
|
||||
try {
|
||||
if (!Downloader.downloadFile(url, file, false) { f -> onProgress("${c.name}: $name", if (f < 0) -1 else Math.round(f * 100f)) }) {
|
||||
return null to "download failed: $name"
|
||||
}
|
||||
step.str("file_checksum").takeIf { it.length == 32 }?.let { md5 ->
|
||||
if (!digest(file, "MD5").equals(md5, ignoreCase = true)) return null to "checksum mismatch: $name"
|
||||
}
|
||||
onProgress("${c.name}: installing", -1)
|
||||
var result: JSONObject? = null
|
||||
var problem: String? = null
|
||||
val status = GuestCommand.run(context, listOf(MSI_INSTALL, "/$MSI_CACHE/${file.name}", "/$STORE/${staging.name}"),
|
||||
logName = "wincomponents-${c.name}") { line ->
|
||||
when {
|
||||
line.startsWith("progress ") -> onProgress("${c.name}: ${line.removePrefix("progress ")}", -1)
|
||||
line.startsWith("result ") -> result = runCatching { JSONObject(line.removePrefix("result ")) }.getOrNull()
|
||||
line.startsWith("error ") -> problem = line.removePrefix("error ")
|
||||
}
|
||||
}
|
||||
val done = result
|
||||
if (status != 0 || done == null) return null to (problem ?: "the installer stopped (status $status)")
|
||||
return done to ""
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "msi ${c.name}", e)
|
||||
return null to (e.message ?: "the installer failed")
|
||||
} finally {
|
||||
file.delete()
|
||||
}
|
||||
}
|
||||
|
||||
private fun digest(file: File, algorithm: String): String {
|
||||
val md = MessageDigest.getInstance(algorithm)
|
||||
FileInputStream(file).use { input ->
|
||||
val buffer = ByteArray(1 shl 16)
|
||||
while (true) { val n = input.read(buffer); if (n < 0) break; md.update(buffer, 0, n) }
|
||||
}
|
||||
return md.digest().joinToString("") { "%02x".format(it) }
|
||||
}
|
||||
|
||||
private fun extract(archive: File, dest: File): Boolean = try {
|
||||
if (archive.name.endsWith(".zip", ignoreCase = true)) ZipInputStream(BufferedInputStream(FileInputStream(archive))).use { zip ->
|
||||
var entry = zip.nextEntry
|
||||
while (entry != null) {
|
||||
val out = ArchivePaths.inside(dest, entry.name)
|
||||
if (out != null && !entry.isDirectory) {
|
||||
out.parentFile?.mkdirs()
|
||||
FileOutputStream(out).use { FileUtils.copy(zip, it) }
|
||||
}
|
||||
entry = zip.nextEntry
|
||||
}
|
||||
} else TarArchiveInputStream(XZCompressorInputStream(BufferedInputStream(FileInputStream(archive), 1 shl 16))).use { tar ->
|
||||
var entry = tar.nextEntry
|
||||
while (entry != null) {
|
||||
val out = ArchivePaths.inside(dest, entry.name)
|
||||
if (out != null && entry.isFile) {
|
||||
out.parentFile?.mkdirs()
|
||||
FileOutputStream(out).use { FileUtils.copy(tar, it) }
|
||||
}
|
||||
entry = tar.nextEntry
|
||||
}
|
||||
}
|
||||
true
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "extract ${archive.name}", e); false
|
||||
}
|
||||
|
||||
/**
|
||||
* Bannerlator's rule: the manifest's own temp paths are Bottles', so the files are found by name
|
||||
* anywhere in the unpacked tree, preferring the ones under the matching win32/win64 folder.
|
||||
*/
|
||||
private fun copyMatching(srcRoot: File, pattern: String, dest: File, arch: String?) {
|
||||
if (pattern.isEmpty()) return
|
||||
val rx = Regex("^" + pattern.split("*").joinToString(".*") { Regex.escape(it) } + "$", RegexOption.IGNORE_CASE)
|
||||
var matches = srcRoot.walkTopDown().filter { it.isFile && rx.matches(it.name) }.toList()
|
||||
if (arch != null) {
|
||||
val inArch = matches.filter { it.path.contains("/$arch/", true) }
|
||||
val other = if (arch == "win64") "win32" else "win64"
|
||||
matches = inArch.ifEmpty { matches.filterNot { it.path.contains("/$other/", true) } }
|
||||
}
|
||||
dest.mkdirs()
|
||||
matches.forEach { f -> f.copyTo(File(dest, f.name.lowercase()), overwrite = true) }
|
||||
}
|
||||
|
||||
/** Removes a component from the runtime and from every game's picks. */
|
||||
@Synchronized
|
||||
fun uninstall(context: Context, id: String) {
|
||||
require(validId(id))
|
||||
FileUtils.delete(File(LinuxRuntime.rootDir(context), "$STORE/$id"))
|
||||
save(context, read(context).mapValues { (_, ids) -> ids - id }.filterValues { it.isNotEmpty() })
|
||||
}
|
||||
|
||||
/** Each game's picks, by the appid its prefix is named after. */
|
||||
@Synchronized
|
||||
fun read(context: Context): Map<String, List<String>> = try {
|
||||
val json = JSONObject(AtomicFile(File(context.filesDir, SELECTION)).readFully().toString(Charsets.UTF_8))
|
||||
val games = json.optJSONObject("games") ?: JSONObject()
|
||||
games.keys().asSequence().associateWith { app ->
|
||||
val ids = games.getJSONArray(app)
|
||||
(0 until ids.length()).map { ids.getString(it) }.filter { validId(it) }
|
||||
}
|
||||
} catch (_: java.io.FileNotFoundException) {
|
||||
emptyMap()
|
||||
}
|
||||
|
||||
fun picks(context: Context, appKey: String): List<String> = read(context)[appKey].orEmpty()
|
||||
|
||||
@Synchronized
|
||||
fun setPicks(context: Context, appKey: String, ids: List<String>) {
|
||||
require(ids.all { validId(it) })
|
||||
val all = read(context).toMutableMap()
|
||||
if (ids.isEmpty()) all.remove(appKey) else all[appKey] = ids.distinct()
|
||||
save(context, all)
|
||||
}
|
||||
|
||||
private fun save(context: Context, games: Map<String, List<String>>) {
|
||||
val text = JSONObject().put("version", 1).put("games", JSONObject().apply {
|
||||
games.forEach { (app, ids) -> put(app, JSONArray(ids)) }
|
||||
}).toString()
|
||||
write(File(context.filesDir, SELECTION), text)
|
||||
publish(context, text)
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes the picks where the launch script reads them; SessionFiles calls this at every session
|
||||
* start too, so a runtime reinstalled since keeps them. An empty selection still writes a file,
|
||||
* which is how a component turned off for every game is taken out of their prefixes.
|
||||
*/
|
||||
@Synchronized
|
||||
fun publish(context: Context, text: String? = null) {
|
||||
val body = text ?: runCatching { AtomicFile(File(context.filesDir, SELECTION)).readFully().toString(Charsets.UTF_8) }.getOrNull() ?: return
|
||||
val root = LinuxRuntime.rootDir(context)
|
||||
if (root.isDirectory) write(File(root, GUEST_SELECTION), body)
|
||||
}
|
||||
|
||||
private fun write(file: File, text: String) {
|
||||
check(file.parentFile!!.isDirectory || file.parentFile!!.mkdirs())
|
||||
val atomic = AtomicFile(file)
|
||||
val output = atomic.startWrite()
|
||||
try {
|
||||
output.write(text.toByteArray(Charsets.UTF_8))
|
||||
atomic.finishWrite(output)
|
||||
} catch (error: Exception) {
|
||||
atomic.failWrite(output)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -90,7 +90,7 @@ internal fun GamesPage(s: FrontEndState, a: FrontEndActions, selected: String, o
|
||||
}
|
||||
}
|
||||
Rise(1) { SectionTitle(stringResource(R.string.games_launch_settings), null) }
|
||||
Rise(2) { LaunchSettings(s, a, host) }
|
||||
Rise(2) { LaunchSettings(s, a, host, current) }
|
||||
Rise(3) { GameFileFolderActions(s, a) }
|
||||
}
|
||||
return
|
||||
@@ -109,7 +109,7 @@ internal fun GamesPage(s: FrontEndState, a: FrontEndActions, selected: String, o
|
||||
GameActions(current, s, a)
|
||||
}
|
||||
SectionTitle(stringResource(R.string.games_launch_settings), null)
|
||||
LaunchSettings(s, a, host)
|
||||
LaunchSettings(s, a, host, current)
|
||||
GameFileFolderActions(s, a)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -300,7 +300,8 @@ internal fun SetupPanel(
|
||||
}
|
||||
}
|
||||
ToggleRow(host, "logs", stringResource(R.string.setup_logs), stringResource(R.string.setup_logs_hint), s.logsEnabled) { a.onLogs() }
|
||||
ActionRow(stringResource(R.string.setup_latest_logs), stringResource(R.string.drawer_logs_hint), stringResource(R.string.drawer_share_logs), a.onShareLogs)
|
||||
ActionRow(stringResource(R.string.setup_latest_logs), stringResource(R.string.drawer_logs_hint), stringResource(R.string.drawer_share_logs), a.onShareLogs,
|
||||
progress = com.droiddeck.launcher.session.SessionLogShare.progress)
|
||||
ActionRow(stringResource(R.string.setup_saved_logs), stringResource(R.string.setup_saved_logs_hint, com.droiddeck.launcher.session.SessionPaths.KEEP_SESSIONS), stringResource(R.string.setup_clear_logs), a.onClearLogs)
|
||||
ToggleRow(
|
||||
host, "offline", stringResource(R.string.setup_offline),
|
||||
@@ -421,10 +422,20 @@ private fun FrameGenMenu(s: FrontEndState, a: FrontEndActions, host: MenuHost) {
|
||||
* app-wide settings - each card opens the same page or menu Setup does.
|
||||
*/
|
||||
@Composable
|
||||
internal fun LaunchSettings(s: FrontEndState, a: FrontEndActions, host: MenuHost) {
|
||||
internal fun LaunchSettings(s: FrontEndState, a: FrontEndActions, host: MenuHost, game: com.droiddeck.launcher.frontend.Library.SteamGame? = null) {
|
||||
// Three across, two on a narrow page; each row's cards share one height.
|
||||
val columns = if (LocalNarrowPane.current) 2 else 3
|
||||
val controller = a.controller
|
||||
val context = androidx.compose.ui.platform.LocalContext.current
|
||||
val inputMode = androidx.compose.ui.platform.LocalInputModeManager.current
|
||||
// The game's prefix is compatdata/<id>, as droiddeck-game-env reads it: a Steam title's appid, an
|
||||
// added game's shortcut appid (unsigned). Recommended scans the game's own folder either way.
|
||||
val wincompKey = game?.let {
|
||||
if (it.library == com.droiddeck.launcher.frontend.Library.ADDED) Integer.toUnsignedString(it.appId)
|
||||
else it.appId.takeIf { id -> id > 0 }?.toString()
|
||||
}
|
||||
var wincompOpen by remember(wincompKey) { mutableStateOf<Boolean?>(null) }
|
||||
val wincompPicks = remember(wincompKey, wincompOpen) { wincompKey?.let { com.droiddeck.launcher.session.WinComponents.picks(context, it) }.orEmpty() }
|
||||
val cards = buildList<@Composable (Modifier) -> Unit> {
|
||||
add { m -> SettingCard(stringResource(R.string.setup_card_components), stringResource(R.string.setup_card_components_hint), "card:components", m) { a.onComponents(true) } }
|
||||
add { m ->
|
||||
@@ -436,7 +447,19 @@ internal fun LaunchSettings(s: FrontEndState, a: FrontEndActions, host: MenuHost
|
||||
}
|
||||
}
|
||||
if (controller != null) add { m -> SettingCard(stringResource(R.string.setup_card_controls), stringResource(R.string.setup_card_controls_hint), "card:controls", m, controller.onMapping) }
|
||||
if (wincompKey != null) add { m ->
|
||||
SettingCard(
|
||||
stringResource(R.string.wincomp_title),
|
||||
if (wincompPicks.isEmpty()) stringResource(R.string.wincomp_card_none) else wincompPicks.joinToString(", ") { com.droiddeck.launcher.session.WinComponentNames.of(it) },
|
||||
"card:wincomp", m,
|
||||
) { wincompOpen = inputMode.inputMode == androidx.compose.ui.input.InputMode.Keyboard }
|
||||
}
|
||||
}
|
||||
val opened = wincompOpen
|
||||
if (opened != null && wincompKey != null && game != null) WinComponentsDialog(
|
||||
wincompKey, game.name, game.gameFiles, opened, compat = game.protonPrefix,
|
||||
steamAppId = game.appId.takeIf { game.library != com.droiddeck.launcher.frontend.Library.ADDED },
|
||||
) { wincompOpen = null }
|
||||
Column(verticalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.fillMaxWidth().padding(bottom = 16.dp)) {
|
||||
for (row in cards.chunked(columns)) {
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.fillMaxWidth().height(IntrinsicSize.Min)) {
|
||||
|
||||
@@ -36,6 +36,7 @@ import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Settings
|
||||
import androidx.compose.material.icons.filled.ChevronLeft
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
@@ -206,8 +207,27 @@ internal fun PrimaryButton(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* [label] while idle; while [progress] is set, a spinner and how far along it is in its place.
|
||||
* The label stays laid out underneath, invisible, so the button keeps its width. The spinner
|
||||
* turns until there is a first figure to show.
|
||||
*/
|
||||
@Composable
|
||||
internal fun SecondaryButton(text: String, enabled: Boolean = true, compact: Boolean = false, modifier: Modifier = Modifier, onClick: () -> Unit) {
|
||||
internal fun ProgressLabel(label: @Composable (Modifier) -> Unit, progress: Float?, fontSize: androidx.compose.ui.unit.TextUnit = 15.sp) {
|
||||
val pal = LocalPalette.current
|
||||
Box(contentAlignment = Alignment.Center) {
|
||||
label(Modifier.alpha(if (progress == null) 1f else 0f))
|
||||
if (progress != null) Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
if (progress > 0f) CircularProgressIndicator(progress = { progress }, strokeWidth = 2.dp, color = pal.signal, trackColor = pal.signal.copy(alpha = 0.22f), modifier = Modifier.size(16.dp))
|
||||
else CircularProgressIndicator(strokeWidth = 2.dp, color = pal.signal, modifier = Modifier.size(16.dp))
|
||||
Text("${(progress * 100).toInt()}%", fontSize = fontSize, fontWeight = FontWeight.SemiBold, maxLines = 1,
|
||||
color = MaterialTheme.colorScheme.onBackground)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun SecondaryButton(text: String, enabled: Boolean = true, compact: Boolean = false, modifier: Modifier = Modifier, progress: Float? = null, onClick: () -> Unit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val src = remember { MutableInteractionSource() }
|
||||
val hot = rememberHot(src) && enabled
|
||||
@@ -222,7 +242,10 @@ internal fun SecondaryButton(text: String, enabled: Boolean = true, compact: Boo
|
||||
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, enabled = enabled, onClick = onClick)
|
||||
.controllerConfirm(enabled = enabled, onClick = onClick)
|
||||
.padding(horizontal = if (compact) 10.dp else 16.dp, vertical = if (compact) 7.dp else 11.dp),
|
||||
) { Text(text, fontSize = if (compact) 12.sp else 15.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 0.5.sp, color = colors.onBackground, maxLines = 1) }
|
||||
) {
|
||||
ProgressLabel({ m -> Text(text, fontSize = if (compact) 12.sp else 15.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 0.5.sp, color = colors.onBackground, maxLines = 1, modifier = m) },
|
||||
progress, fontSize = if (compact) 12.sp else 15.sp)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
|
||||
@@ -70,7 +70,7 @@ fun GameEnvironmentRow(modifier: Modifier = Modifier, showHint: Boolean = true)
|
||||
/** With a pad driving, focus [target] once the dialog is laid out, and keep the dialog in pad mode. */
|
||||
@OptIn(androidx.compose.ui.ExperimentalComposeUiApi::class)
|
||||
@Composable
|
||||
private fun PadFocus(byPad: Boolean, target: FocusRequester) {
|
||||
internal fun PadFocus(byPad: Boolean, target: FocusRequester) {
|
||||
val inputMode = LocalInputModeManager.current
|
||||
LaunchedEffect(Unit) {
|
||||
if (!byPad) return@LaunchedEffect
|
||||
@@ -95,6 +95,7 @@ private fun GameEnvironmentEditor(byPad: Boolean, onClose: () -> Unit) {
|
||||
var error by remember { mutableStateOf(false) }
|
||||
var editing by remember { mutableStateOf<Pair<String, String>?>(null) }
|
||||
val preset = SessionPrefs.fexPreset(context)
|
||||
val forceSsbs = SessionPrefs.forceSsbs(context)
|
||||
val firstFocus = remember { FocusRequester() }
|
||||
var editByPad by remember { mutableStateOf(false) }
|
||||
val dialogInput = LocalInputModeManager.current
|
||||
@@ -159,7 +160,7 @@ private fun GameEnvironmentEditor(byPad: Boolean, onClose: () -> Unit) {
|
||||
if (current == null && !error) Small(stringResource(R.string.game_env_loading))
|
||||
if (current != null) {
|
||||
val own = current.entries(scope)
|
||||
val entries = GameEnvironment.effective(current, preset, scope).toSortedMap()
|
||||
val entries = GameEnvironment.effective(current, preset, scope, forceSsbs).toSortedMap()
|
||||
if (entries.isEmpty()) Small(stringResource(R.string.game_env_empty))
|
||||
else Panel {
|
||||
entries.entries.forEachIndexed { i, (name, value) ->
|
||||
|
||||
@@ -1,6 +1,17 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import com.droiddeck.launcher.R
|
||||
import androidx.compose.animation.AnimatedVisibility
|
||||
import androidx.compose.foundation.focusable
|
||||
import androidx.compose.material.icons.outlined.ExpandLess
|
||||
import androidx.compose.material.icons.outlined.ExpandMore
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.ui.platform.LocalClipboardManager
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.text.AnnotatedString
|
||||
import com.droiddeck.launcher.gpu.DeviceInfo
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
@@ -180,29 +191,104 @@ private fun DriverDropdown(rows: List<DriverRow>, selected: String, fallback: St
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This GPU and how far it is supported. A tap (or A) opens the card onto everything about the chip -
|
||||
* SoC, GPU, CPU, memory, system, the phone's own Vulkan driver, the drivers in use - gathered once,
|
||||
* off the main thread, with a button that copies it for a bug report.
|
||||
*/
|
||||
@Composable
|
||||
private fun DeviceCard(s: GpuDriversState) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val context = LocalContext.current
|
||||
val clipboard = LocalClipboardManager.current
|
||||
val tint = when {
|
||||
s.unsupported -> pal.error
|
||||
s.supported -> pal.good
|
||||
else -> AttentionAmber
|
||||
}
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(14.dp),
|
||||
modifier = Modifier.fillMaxWidth().clip(Shape14).background(colors.surface).border(1.dp, pal.line, Shape14).padding(14.dp),
|
||||
var open by rememberSaveable { mutableStateOf(false) }
|
||||
var details by remember { mutableStateOf<List<DeviceInfo.Section>?>(null) }
|
||||
var copied by remember { mutableStateOf(false) }
|
||||
LaunchedEffect(open) {
|
||||
if (open && details == null) details = withContext(Dispatchers.IO) { DeviceInfo.collect(context) }
|
||||
}
|
||||
val src = remember { MutableInteractionSource() }
|
||||
val hot = rememberHot(src)
|
||||
val toggle = { open = !open; copied = false }
|
||||
Column(
|
||||
Modifier.fillMaxWidth().clip(Shape14).background(colors.surface)
|
||||
.background(if (hot) pal.signal.copy(alpha = 0.10f) else Color.Transparent)
|
||||
.glideBorder(hot, Shape14, pal.signal, pal.line),
|
||||
) {
|
||||
Box(contentAlignment = Alignment.Center, modifier = Modifier.size(44.dp).clip(Shape12).background(tint.copy(alpha = 0.14f))) {
|
||||
Icon(Icons.Outlined.Memory, contentDescription = null, tint = tint, modifier = Modifier.size(24.dp))
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(14.dp),
|
||||
modifier = Modifier.fillMaxWidth().paneItem("gpu-device")
|
||||
.hoverable(src).clickable(interactionSource = src, indication = null, role = Role.Button, onClick = toggle)
|
||||
.controllerConfirm(onClick = toggle)
|
||||
.padding(14.dp),
|
||||
) {
|
||||
Box(contentAlignment = Alignment.Center, modifier = Modifier.size(44.dp).clip(Shape12).background(tint.copy(alpha = 0.14f))) {
|
||||
Icon(Icons.Outlined.Memory, contentDescription = null, tint = tint, modifier = Modifier.size(24.dp))
|
||||
}
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(s.gpuName, fontSize = 18.sp, fontWeight = FontWeight.Bold, color = colors.onBackground)
|
||||
Text(listOf(s.soc, s.gpuFamily).filter { it.isNotEmpty() }.joinToString(" · "), fontSize = 13.sp, color = colors.onSurfaceVariant)
|
||||
}
|
||||
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
Box(Modifier.size(7.dp).clip(CircleShape).background(tint))
|
||||
Text(s.supportText, fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = tint, maxLines = 2)
|
||||
}
|
||||
Icon(
|
||||
if (open) Icons.Outlined.ExpandLess else Icons.Outlined.ExpandMore,
|
||||
contentDescription = stringResource(if (open) R.string.device_info_hide else R.string.device_info_show),
|
||||
tint = colors.onSurfaceVariant, modifier = Modifier.size(24.dp),
|
||||
)
|
||||
}
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(s.gpuName, fontSize = 18.sp, fontWeight = FontWeight.Bold, color = colors.onBackground)
|
||||
Text(listOf(s.soc, s.gpuFamily).filter { it.isNotEmpty() }.joinToString(" · "), fontSize = 13.sp, color = colors.onSurfaceVariant)
|
||||
AnimatedVisibility(open) {
|
||||
Column(verticalArrangement = Arrangement.spacedBy(12.dp), modifier = Modifier.fillMaxWidth().padding(start = 14.dp, end = 14.dp, bottom = 14.dp)) {
|
||||
HorizontalDivider(color = pal.line)
|
||||
val sections = details
|
||||
if (sections == null) {
|
||||
Text(stringResource(R.string.device_info_loading), fontSize = 13.sp, color = colors.onSurfaceVariant)
|
||||
LinearProgressIndicator(Modifier.fillMaxWidth())
|
||||
} else {
|
||||
for (section in sections) DeviceInfoSection(section)
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(
|
||||
stringResource(if (copied) R.string.device_info_copied else R.string.device_info_copy_hint),
|
||||
fontSize = 12.sp, color = colors.onSurfaceVariant, modifier = Modifier.weight(1f),
|
||||
)
|
||||
SecondaryButton(stringResource(R.string.device_info_copy), compact = true) {
|
||||
clipboard.setText(AnnotatedString(DeviceInfo.text(sections)))
|
||||
copied = true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
Box(Modifier.size(7.dp).clip(CircleShape).background(tint))
|
||||
Text(s.supportText, fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = tint, maxLines = 2)
|
||||
}
|
||||
}
|
||||
|
||||
/** One part of the device details: its title, then label/value rows. Focusable, so the d-pad walks the list. */
|
||||
@Composable
|
||||
private fun DeviceInfoSection(section: DeviceInfo.Section) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val src = remember { MutableInteractionSource() }
|
||||
val hot = rememberHot(src)
|
||||
Column(
|
||||
verticalArrangement = Arrangement.spacedBy(3.dp),
|
||||
modifier = Modifier.fillMaxWidth().clip(Shape12)
|
||||
.glideBorder(hot, Shape12, pal.signal)
|
||||
.focusable(interactionSource = src).padding(horizontal = 8.dp, vertical = 6.dp),
|
||||
) {
|
||||
Text(section.title.uppercase(), fontSize = 11.5.sp, fontWeight = FontWeight.Bold, letterSpacing = 1.2.sp, color = colors.onSurfaceVariant)
|
||||
for ((label, value) in section.rows) {
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
Text(label, fontSize = 13.sp, color = colors.onSurfaceVariant, modifier = Modifier.width(190.dp))
|
||||
Text(value, fontSize = 13.sp, fontWeight = FontWeight.Medium, color = colors.onBackground, modifier = Modifier.weight(1f))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -143,8 +143,12 @@ internal fun LaunchFlood(
|
||||
val start = fromColors ?: (colors.primary to pal.primary2)
|
||||
VeilRing()
|
||||
// Left, top, right, bottom: 0 on the button, 1 on the page's edge. Springs overshoot past the
|
||||
// edge, off the page, so the wobble is felt in the pull and never seen as a shrink.
|
||||
// edge, off the page, so the wobble is felt in the pull. An underdamped spring then swings back
|
||||
// short of the edge (about 3% at this damping), so once an edge has reached the page's it holds
|
||||
// there, or the page would show through in a sliver while the next screen opens.
|
||||
val edges = remember { List(4) { Animatable(0f) } }
|
||||
val reached = remember { BooleanArray(4) }
|
||||
fun edge(i: Int) = edges[i].value.let { if (reached[i]) maxOf(it, 1f) else it }
|
||||
val covered by rememberUpdatedState(onCovered)
|
||||
val progress by rememberUpdatedState(onProgress)
|
||||
var page by remember { mutableStateOf(Size.Zero) }
|
||||
@@ -152,6 +156,7 @@ internal fun LaunchFlood(
|
||||
if (page == Size.Zero) return@LaunchedEffect
|
||||
if (Motion.scale == 0f) {
|
||||
edges.forEach { it.snapTo(1f) }
|
||||
reached.fill(true)
|
||||
progress(1f)
|
||||
covered()
|
||||
return@LaunchedEffect
|
||||
@@ -164,18 +169,19 @@ internal fun LaunchFlood(
|
||||
launch {
|
||||
delay(Motion.ms((180 * (1f - lead)).toInt()).toLong())
|
||||
edge.animateTo(1f, spring(dampingRatio = 0.48f, stiffness = lerp(110f, 190f, lead))) {
|
||||
progress(edges.sumOf { it.value.coerceIn(0f, 1f).toDouble() }.toFloat() / 4f)
|
||||
if (value >= 1f) reached[i] = true
|
||||
progress((0 until 4).sumOf { edge(it).coerceIn(0f, 1f).toDouble() }.toFloat() / 4f)
|
||||
}
|
||||
}
|
||||
}
|
||||
// Covered once every edge has reached the page's, the first time round.
|
||||
snapshotFlow { edges.all { it.value >= 0.995f } }.first { it }
|
||||
// Covered once every edge has reached the page's.
|
||||
snapshotFlow { (0 until 4).all { edge(it) >= 1f } }.first { it }
|
||||
covered()
|
||||
runs.forEach { it.join() }
|
||||
}
|
||||
}
|
||||
Canvas(Modifier.fillMaxSize().onSizeChanged { page = Size(it.width.toFloat(), it.height.toFloat()) }.pointerInput(Unit) { awaitEachGesture { while (true) awaitPointerEvent().changes.forEach { it.consume() } } }) {
|
||||
drawFlood(from, edges.map { it.value }, start, pal.signal, cornerAtRest.toPx())
|
||||
drawFlood(from, List(4) { edge(it) }, start, pal.signal, cornerAtRest.toPx())
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -69,11 +69,13 @@ class ModeSettings(
|
||||
val storageOptions: List<Pair<String, String>> = emptyList(),
|
||||
/** Steam only: record allocation and sampled storage timings in the next session's Share logs. */
|
||||
val storageDiagnostics: Boolean = false,
|
||||
/** Steam only: report Steam's space reservation on the second library as done (experimental). */
|
||||
val skipPreallocation: Boolean = false,
|
||||
val fexPreset: String? = null,
|
||||
/** Steam only: Force SSBS for Proton games (SessionPrefs.forceSsbs). */
|
||||
val forceSsbs: Boolean = false,
|
||||
/** Steam only: SessionPrefs.SYNC_* chosen for Proton games; null outside Steam. */
|
||||
val syncBackend: String? = null,
|
||||
/** Steam only: forces game windows fullscreen (null = not a Steam page). */
|
||||
val forceFullscreen: Boolean? = null,
|
||||
val stretch16x9: Boolean? = null,
|
||||
/** Steam only: the client branch forced on the command line. */
|
||||
val steamChannel: String? = null,
|
||||
@@ -130,9 +132,10 @@ class ModeSettingsActions(
|
||||
val onGameStorage: (path: String, label: String) -> Unit = { _, _ -> },
|
||||
val onPickGameStorageFolder: () -> Unit = {},
|
||||
val onStorageDiagnostics: (Boolean) -> Unit = {},
|
||||
val onSkipPreallocation: (Boolean) -> Unit = {},
|
||||
val onFexPreset: (String) -> Unit = {},
|
||||
val onForceSsbs: (Boolean) -> Unit = {},
|
||||
val onSyncBackend: (String) -> Unit = {},
|
||||
val onForceFullscreen: (Boolean) -> Unit = {},
|
||||
val onStretch16x9: (Boolean) -> Unit = {},
|
||||
val onSteamChannel: (String) -> Unit = {},
|
||||
val onSteamRepair: () -> Unit = {},
|
||||
@@ -410,10 +413,6 @@ fun ModeSettingsPage(s: ModeSettings, a: ModeSettingsActions) {
|
||||
}
|
||||
}
|
||||
}
|
||||
if ((tab == ModeSettingsTab.GAMES || (!steam && tab == ModeSettingsTab.DISPLAY)) && s.forceFullscreen != null) SettingsGroup(stringResource(R.string.display_window_compatibility)) {
|
||||
ToggleRow(host, "fill", stringResource(R.string.display_force_fullscreen),
|
||||
stringResource(R.string.display_force_fullscreen_hint), s.forceFullscreen, onChange = a.onForceFullscreen)
|
||||
}
|
||||
if (steam && tab == ModeSettingsTab.GAMES && s.addedGamesDirs != null) SettingsGroup(stringResource(R.string.mode_added_games)) {
|
||||
for (dir in s.addedGamesDirs) {
|
||||
val n = s.addedGames.count { it.folderPath.startsWith("$dir/") }
|
||||
@@ -432,12 +431,14 @@ fun ModeSettingsPage(s: ModeSettings, a: ModeSettingsActions) {
|
||||
stringResource(R.string.mode_added_art_hint),
|
||||
s.addedGamesArt, onChange = a.onAddedGamesArt,
|
||||
)
|
||||
for (g in s.addedGames) ChoiceRow(
|
||||
host, "added:" + g.folderPath, g.folderName, if (s.addedGamesDirs.size > 1) stringResource(R.string.mode_added_launches_in, g.exeName, g.folderPath.substringBeforeLast('/').substringAfterLast('/')) else stringResource(R.string.mode_added_launches, g.exeName),
|
||||
g.candidates + ("__pick__" to stringResource(R.string.mode_added_choose)), g.exePath,
|
||||
note = stringResource(R.string.mode_added_exe_note),
|
||||
onPick = { path -> if (path == "__pick__") a.onPickAddedGameExe(g.folderPath) else a.onAddedGameExe(g.folderPath, path) },
|
||||
)
|
||||
for (g in s.addedGames) {
|
||||
ChoiceRow(
|
||||
host, "added:" + g.folderPath, g.folderName, if (s.addedGamesDirs.size > 1) stringResource(R.string.mode_added_launches_in, g.exeName, g.folderPath.substringBeforeLast('/').substringAfterLast('/')) else stringResource(R.string.mode_added_launches, g.exeName),
|
||||
g.candidates + ("__pick__" to stringResource(R.string.mode_added_choose)), g.exePath,
|
||||
note = stringResource(R.string.mode_added_exe_note),
|
||||
onPick = { path -> if (path == "__pick__") a.onPickAddedGameExe(g.folderPath) else a.onAddedGameExe(g.folderPath, path) },
|
||||
)
|
||||
}
|
||||
}
|
||||
if (steam && tab == ModeSettingsTab.GAMES && s.fexPreset != null) SettingsGroup(stringResource(R.string.game_settings_title)) {
|
||||
if (s.syncBackend != null) SettingsRow(
|
||||
@@ -459,6 +460,7 @@ fun ModeSettingsPage(s: ModeSettings, a: ModeSettingsActions) {
|
||||
FexPreset.all.map { it.id to stringResource(it.label) }, s.fexPreset,
|
||||
note = stringResource(FexPreset.byId(s.fexPreset).detail), onPick = a.onFexPreset,
|
||||
)
|
||||
ToggleRow(host, "ssbs", stringResource(R.string.force_ssbs_title), stringResource(R.string.force_ssbs_hint), s.forceSsbs, onChange = a.onForceSsbs)
|
||||
GameEnvironmentRow()
|
||||
|
||||
}
|
||||
@@ -506,6 +508,11 @@ fun ModeSettingsPage(s: ModeSettings, a: ModeSettingsActions) {
|
||||
stringResource(R.string.mode_storage_diagnostics_hint), s.storageDiagnostics,
|
||||
onChange = a.onStorageDiagnostics,
|
||||
)
|
||||
ToggleRow(
|
||||
host, "skipPreallocation", stringResource(R.string.mode_skip_preallocation),
|
||||
stringResource(R.string.mode_skip_preallocation_hint), s.skipPreallocation,
|
||||
onChange = a.onSkipPreallocation,
|
||||
)
|
||||
}
|
||||
if (!steam && tab == ModeSettingsTab.DISPLAY && s.renderer != null) SettingsGroup(stringResource(R.string.mode_renderer)) {
|
||||
ChoiceRow(
|
||||
|
||||
@@ -229,7 +229,8 @@ private fun EndedActions(onRetry: (() -> Unit)?, onShareLogs: (() -> Unit)?, onC
|
||||
var firstUsed = false
|
||||
fun claim(): Modifier = if (firstUsed) Modifier else { firstUsed = true; Modifier.focusRequester(first) }
|
||||
if (onRetry != null) PrimaryButton(stringResource(R.string.store_try_again), modifier = claim(), onClick = onRetry)
|
||||
if (onShareLogs != null) SecondaryButton(stringResource(R.string.drawer_share_logs), modifier = claim(), onClick = onShareLogs)
|
||||
if (onShareLogs != null) SecondaryButton(stringResource(R.string.drawer_share_logs), modifier = claim(),
|
||||
progress = com.droiddeck.launcher.session.SessionLogShare.progress, onClick = onShareLogs)
|
||||
if (onClose != null) SecondaryButton(stringResource(R.string.mode_back), modifier = claim(), onClick = onClose)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -195,8 +195,6 @@ class DrawerActions(
|
||||
val touchMode: String,
|
||||
val touchAuto: String,
|
||||
val fexPreset: String,
|
||||
/** Steam only: forces game windows fullscreen, changed live (null = not Steam). */
|
||||
val fillScreen: Boolean? = null,
|
||||
val upscaler: Int = 0,
|
||||
val upscaleSharpness: Int = 75,
|
||||
/** The compositor's post chain (gpu/ScreenEffects), changed live. */
|
||||
@@ -226,7 +224,6 @@ class DrawerActions(
|
||||
val onBackActionsInverted: (Boolean) -> Unit,
|
||||
val onTouch: (String) -> Unit,
|
||||
val onFexPreset: (String) -> Unit,
|
||||
val onFillScreen: (Boolean) -> Unit = {},
|
||||
val onUpscaler: (Int) -> Unit = {},
|
||||
val onUpscaleSharpness: (Int) -> Unit = {},
|
||||
val onEffects: (ScreenEffects) -> Unit = {},
|
||||
@@ -407,11 +404,6 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
|
||||
stringResource(R.string.display_sharpness), null, a.upscaleSharpness, 0..100, step = 5,
|
||||
format = { "$it%" }, modifier = focus.track(page, "upscale-sharpness"), onChange = a.onUpscaleSharpness)
|
||||
}
|
||||
if (a.fillScreen != null) SettingsGroup(stringResource(R.string.display_window_compatibility)) {
|
||||
ToggleRow(host, "fill", stringResource(R.string.display_force_fullscreen),
|
||||
stringResource(R.string.display_force_fullscreen_live), a.fillScreen,
|
||||
chipModifier = focus.track(page, "fill"), onChange = a.onFillScreen)
|
||||
}
|
||||
}
|
||||
SessionDrawerPage.EFFECTS -> {
|
||||
ScreenEffectsGroup(host, a, advancedEffectsExpanded,
|
||||
@@ -516,7 +508,8 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
|
||||
}
|
||||
SettingsGroup(stringResource(R.string.drawer_support)) {
|
||||
SettingsRow(stringResource(R.string.drawer_logs), stringResource(R.string.drawer_logs_hint)) {
|
||||
DrawerOutlineButton(stringResource(R.string.drawer_share_logs), modifier = focus.track(page, "share-logs")) {
|
||||
DrawerOutlineButton(stringResource(R.string.drawer_share_logs), modifier = focus.track(page, "share-logs"),
|
||||
progress = com.droiddeck.launcher.session.SessionLogShare.progress) {
|
||||
host.open = null
|
||||
a.onShareLogs()
|
||||
}
|
||||
@@ -592,7 +585,7 @@ private fun DrawerActionButton(text: String, icon: androidx.compose.ui.graphics.
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun DrawerOutlineButton(text: String, modifier: Modifier = Modifier, onClick: () -> Unit) {
|
||||
private fun DrawerOutlineButton(text: String, modifier: Modifier = Modifier, progress: Float? = null, onClick: () -> Unit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val source = remember { MutableInteractionSource() }
|
||||
@@ -605,7 +598,7 @@ private fun DrawerOutlineButton(text: String, modifier: Modifier = Modifier, onC
|
||||
contentPadding = PaddingValues(horizontal = 12.dp),
|
||||
border = BorderStroke(if (hot) 2.dp else 1.dp, if (hot) pal.signal else colors.outline),
|
||||
colors = ButtonDefaults.outlinedButtonColors(containerColor = if (hot) pal.signal.copy(alpha = 0.16f) else Color.Transparent),
|
||||
) { Text(text, fontSize = 13.sp, fontWeight = FontWeight.SemiBold, maxLines = 1) }
|
||||
) { ProgressLabel({ m -> Text(text, fontSize = 13.sp, fontWeight = FontWeight.SemiBold, maxLines = 1, modifier = m) }, progress, fontSize = 13.sp) }
|
||||
}
|
||||
|
||||
@Composable
|
||||
|
||||
@@ -591,8 +591,8 @@ fun MultiRow(
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun ActionRow(label: String, hint: String?, button: String, onClick: () -> Unit) {
|
||||
SettingsRow(label, hint) { SecondaryButton(button, onClick = onClick) }
|
||||
fun ActionRow(label: String, hint: String?, button: String, onClick: () -> Unit, progress: Float? = null) {
|
||||
SettingsRow(label, hint) { SecondaryButton(button, progress = progress, onClick = onClick) }
|
||||
}
|
||||
|
||||
@Composable
|
||||
|
||||
@@ -0,0 +1,280 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.material3.LinearProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.alpha
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.focus.FocusRequester
|
||||
import androidx.compose.ui.focus.focusRequester
|
||||
import androidx.compose.ui.focus.onFocusChanged
|
||||
import androidx.compose.ui.input.InputMode
|
||||
import androidx.compose.ui.platform.LocalInputModeManager
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.frontend.DependencyDetector
|
||||
import com.droiddeck.launcher.frontend.PrefixInstalledDetector
|
||||
import com.droiddeck.launcher.frontend.SteamRedists
|
||||
import com.droiddeck.launcher.session.WinComponentNames
|
||||
import com.droiddeck.launcher.session.WinComponents
|
||||
import com.droiddeck.launcher.session.WinComponents.Support
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.launch
|
||||
import androidx.compose.runtime.withFrameNanos
|
||||
import kotlinx.coroutines.withContext
|
||||
import java.io.File
|
||||
|
||||
// Windows components for one added game, Bannerlator's list: what the game's folder suggests first,
|
||||
// then everything that installs here, then the ones that need a Windows installer (not yet). Each
|
||||
// one is a switch, downloaded the first time it is turned on for any game; the launch puts the
|
||||
// picked ones into the game's prefix (droiddeck-wincomponents).
|
||||
|
||||
/** Bannerlator's detector names installers; here the DLL-copy twin is the one that installs. */
|
||||
private fun installable(name: String, all: Map<String, WinComponents.Component>): String {
|
||||
val dll = when (name) {
|
||||
"oalinst" -> "oalinst_dll"
|
||||
else -> "${name}_dll"
|
||||
}
|
||||
val twin = all[dll]
|
||||
return if (twin != null && WinComponents.support(twin, all) == Support.READY) dll else name
|
||||
}
|
||||
|
||||
@OptIn(androidx.compose.ui.ExperimentalComposeUiApi::class)
|
||||
@Composable
|
||||
internal fun WinComponentsDialog(
|
||||
appKey: String, gameName: String, gameDir: File?, byPad: Boolean,
|
||||
/** compatdata/<id>: what the prefix already has. [steamAppId]: a Steam title, whose appmanifest lists Steam's own redists. */
|
||||
compat: File? = null, steamAppId: Int? = null,
|
||||
onClose: () -> Unit,
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
val coroutine = rememberCoroutineScope()
|
||||
val shown = rememberShown(onClose)
|
||||
val close = { shown.targetState = false }
|
||||
// null while the catalog loads; empty when it could not be had.
|
||||
var catalog by remember { mutableStateOf<Map<String, WinComponents.Component>?>(null) }
|
||||
var offline by remember { mutableStateOf(false) }
|
||||
var recommended by remember { mutableStateOf(emptyList<DependencyDetector.Recommendation>()) }
|
||||
var installed by remember { mutableStateOf(emptySet<String>()) }
|
||||
// Detector names (oalinst, physx...) already in the prefix from elsewhere.
|
||||
var present by remember { mutableStateOf(emptySet<String>()) }
|
||||
var picks by remember { mutableStateOf(WinComponents.picks(context, appKey)) }
|
||||
var progress by remember { mutableStateOf<Pair<String, Int>?>(null) }
|
||||
var error by remember { mutableStateOf<String?>(null) }
|
||||
// The component the error is about, so it shows on its own row and not only at the bottom.
|
||||
var failed by remember { mutableStateOf<String?>(null) }
|
||||
var showWaiting by remember { mutableStateOf(false) }
|
||||
// Done holds focus while the list loads, then the top switch takes it - opened by touch or by
|
||||
// pad, so the d-pad always has somewhere to start; LB and RB jump between the sections, since
|
||||
// the full list runs past sixty switches.
|
||||
val recFocus = remember { FocusRequester() }
|
||||
val allFocus = remember { FocusRequester() }
|
||||
val waitFocus = remember { FocusRequester() }
|
||||
val doneFocus = remember { FocusRequester() }
|
||||
val inputMode = LocalInputModeManager.current
|
||||
var switchFocused by remember { mutableStateOf(false) }
|
||||
|
||||
LaunchedEffect(Unit) {
|
||||
val (entries, found) = withContext(Dispatchers.IO) {
|
||||
// The folder's own installers first, then what Steam installs with the game.
|
||||
val own = gameDir?.let { DependencyDetector.detect(it) } ?: emptyList()
|
||||
val steam = steamAppId?.let { SteamRedists.detect(gameDir, it) } ?: emptyList()
|
||||
WinComponents.fetch() to (own + steam)
|
||||
}
|
||||
offline = entries == null
|
||||
catalog = entries.orEmpty().associateBy { it.name }
|
||||
recommended = found
|
||||
present = withContext(Dispatchers.IO) { PrefixInstalledDetector.detect(compat) }
|
||||
installed = withContext(Dispatchers.IO) { WinComponents.installedIds(context).toSet() }
|
||||
}
|
||||
fun setPicks(next: List<String>) {
|
||||
picks = next
|
||||
coroutine.launch(Dispatchers.IO) { WinComponents.setPicks(context, appKey, next) }
|
||||
}
|
||||
fun toggle(id: String, on: Boolean) {
|
||||
// Switches stay enabled during a download - a disabled one drops the pad's focus - so a press
|
||||
// then is ignored here.
|
||||
if (progress != null) return
|
||||
error = null
|
||||
failed = null
|
||||
if (!on) { setPicks(picks - id); return }
|
||||
val all = catalog.orEmpty()
|
||||
val c = all[id]
|
||||
if (id in installed || c == null) { setPicks(picks + id); return }
|
||||
progress = id to -1
|
||||
coroutine.launch {
|
||||
val problem = withContext(Dispatchers.IO) {
|
||||
WinComponents.install(context, c, all) { stage, percent -> progress = stage to percent }
|
||||
}
|
||||
progress = null
|
||||
installed = withContext(Dispatchers.IO) { WinComponents.installedIds(context).toSet() }
|
||||
if (problem != null) { error = problem; failed = id } else setPicks(picks + id)
|
||||
}
|
||||
}
|
||||
|
||||
val all = catalog
|
||||
val here = if (all == null) emptySet() else present.map { installable(it, all) }.toSet()
|
||||
fun supportOf(id: String): Support =
|
||||
all?.get(id)?.let { WinComponents.support(it, all) } ?: if (id in installed) Support.READY else Support.UNSUPPORTED
|
||||
val recIds = if (all == null) emptyList() else recommended.distinctBy { installable(it.componentName, all) }
|
||||
val ready = all.orEmpty().values.filter { WinComponents.support(it, all.orEmpty()) == Support.READY }.map { it.name }
|
||||
val extra = (installed + picks).filter { all?.containsKey(it) != true }
|
||||
val list = (ready + extra).distinct().sortedBy { WinComponentNames.of(it).lowercase() }
|
||||
val waiting = all.orEmpty().values.filter { WinComponents.support(it, all.orEmpty()) == Support.NEEDS_INSTALLER }
|
||||
.map { it.name }.sortedBy { WinComponentNames.of(it).lowercase() }
|
||||
val hasRec = all != null && recIds.any { supportOf(installable(it.componentName, all)) == Support.READY }
|
||||
val sections = listOfNotNull(recFocus.takeIf { hasRec }, allFocus.takeIf { list.isNotEmpty() },
|
||||
waitFocus.takeIf { waiting.isNotEmpty() }, doneFocus)
|
||||
var section by remember { mutableStateOf(0) }
|
||||
fun jump(step: Int) {
|
||||
section = (section + step + sections.size) % sections.size
|
||||
runCatching { sections[section].requestFocus() }
|
||||
}
|
||||
LaunchedEffect(all != null) {
|
||||
// The dialog's window starts in touch mode, where a switch cannot hold focus at all.
|
||||
inputMode.requestInputMode(InputMode.Keyboard)
|
||||
section = 0
|
||||
val target = if (all == null) doneFocus else sections.first()
|
||||
switchFocused = false
|
||||
// It animates in and the list composes over a few frames: ask until the switch has it.
|
||||
repeat(60) {
|
||||
withFrameNanos { }
|
||||
runCatching { target.requestFocus() }
|
||||
withFrameNanos { }
|
||||
if (switchFocused || (target !== recFocus && target !== allFocus)) return@LaunchedEffect
|
||||
}
|
||||
}
|
||||
|
||||
AppDialog(shown, close, "winComponents", wide = true, modifier = Modifier.bumpers({ jump(-1) }, { jump(1) })) {
|
||||
DialogHeader(gameName, stringResource(R.string.wincomp_title))
|
||||
Small(stringResource(R.string.wincomp_applies))
|
||||
if (byPad) Small(stringResource(R.string.wincomp_pad_hint))
|
||||
if (all == null) Small(stringResource(R.string.wincomp_loading))
|
||||
if (offline) Small(stringResource(R.string.wincomp_offline), error = true)
|
||||
@Composable
|
||||
fun Item(id: String, reason: String?, focus: FocusRequester?) {
|
||||
val c = all?.get(id)
|
||||
val support = supportOf(id)
|
||||
val status = when {
|
||||
id == failed && error != null -> stringResource(R.string.wincomp_failed, error.orEmpty())
|
||||
id in here && id !in picks -> stringResource(R.string.wincomp_already_here)
|
||||
id in installed -> stringResource(R.string.wincomp_downloaded)
|
||||
support == Support.NEEDS_INSTALLER -> stringResource(R.string.wincomp_needs_installer)
|
||||
support == Support.UNSUPPORTED -> stringResource(R.string.wincomp_unsupported)
|
||||
else -> null
|
||||
}
|
||||
// The catalog key stays in the detail: it is what a log or a bug report names.
|
||||
val detail = listOfNotNull(reason, c?.description?.takeIf { it.isNotEmpty() }, status, id).joinToString(" · ")
|
||||
val usable = support == Support.READY
|
||||
ComponentRow(
|
||||
WinComponentNames.of(id), detail, checked = id in picks, enabled = usable || id in picks,
|
||||
dim = !usable, modifier = (if (usable && focus != null) Modifier.focusRequester(focus) else Modifier)
|
||||
.onFocusChanged { if (it.isFocused) switchFocused = true },
|
||||
) { on -> toggle(id, on) }
|
||||
}
|
||||
/** The section's requester goes to its first switch that can take focus. */
|
||||
fun firstUsable(ids: List<String>, focus: FocusRequester): (String) -> FocusRequester? {
|
||||
val first = ids.firstOrNull { supportOf(it) == Support.READY }
|
||||
return { id -> focus.takeIf { id == first } }
|
||||
}
|
||||
|
||||
if (all != null && recIds.isNotEmpty()) {
|
||||
Section(stringResource(R.string.wincomp_recommended))
|
||||
val focusOf = firstUsable(recIds.map { installable(it.componentName, all) }, recFocus)
|
||||
Panel {
|
||||
recIds.forEachIndexed { i, rec ->
|
||||
if (i > 0) Divider()
|
||||
val reason = stringResource(
|
||||
when (rec.kind) {
|
||||
DependencyDetector.Kind.BUNDLED -> R.string.wincomp_found_bundled
|
||||
DependencyDetector.Kind.SHIPPED -> R.string.wincomp_found_shipped
|
||||
DependencyDetector.Kind.STEAM -> R.string.wincomp_found_steam
|
||||
}, rec.reason,
|
||||
)
|
||||
val id = installable(rec.componentName, all)
|
||||
Item(id, reason, focusOf(id))
|
||||
}
|
||||
}
|
||||
} else if (all != null && gameDir != null) Small(stringResource(R.string.wincomp_no_recommendation))
|
||||
|
||||
if (list.isNotEmpty()) {
|
||||
Section(stringResource(R.string.wincomp_all, list.size))
|
||||
val focusOf = firstUsable(list, allFocus)
|
||||
Panel { list.forEachIndexed { i, id -> if (i > 0) Divider(); Item(id, null, focusOf(id)) } }
|
||||
}
|
||||
if (waiting.isNotEmpty()) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Section(stringResource(R.string.wincomp_installers, waiting.size))
|
||||
Spacer(Modifier.weight(1f))
|
||||
SecondaryButton(
|
||||
stringResource(if (showWaiting) R.string.wincomp_hide else R.string.wincomp_show), compact = true,
|
||||
modifier = Modifier.focusRequester(waitFocus),
|
||||
) { showWaiting = !showWaiting }
|
||||
}
|
||||
Small(stringResource(R.string.wincomp_installers_note))
|
||||
if (showWaiting) Panel { waiting.forEachIndexed { i, id -> if (i > 0) Divider(); Item(id, null, null) } }
|
||||
}
|
||||
|
||||
progress?.let { (stage, percent) ->
|
||||
Small(if (percent >= 0) "$stage · $percent%" else stage)
|
||||
if (percent >= 0) LinearProgressIndicator(progress = { percent / 100f }, modifier = Modifier.fillMaxWidth())
|
||||
else LinearProgressIndicator(Modifier.fillMaxWidth())
|
||||
}
|
||||
error?.let { Small(it, error = true) }
|
||||
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(top = 4.dp)) {
|
||||
Small(stringResource(R.string.wincomp_next_launch))
|
||||
Spacer(Modifier.weight(1f))
|
||||
PrimaryButton(stringResource(R.string.game_env_done), enabled = progress == null, modifier = Modifier.focusRequester(doneFocus), onClick = close)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Section(title: String) =
|
||||
Text(title.uppercase(), fontSize = 12.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 1.5.sp, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
|
||||
@Composable
|
||||
private fun Panel(content: @Composable androidx.compose.foundation.layout.ColumnScope.() -> Unit) =
|
||||
Column(Modifier.fillMaxWidth().clip(Shape14).background(MaterialTheme.colorScheme.surface).border(1.dp, LocalPalette.current.line, Shape14), content = content)
|
||||
|
||||
@Composable
|
||||
private fun Divider() =
|
||||
Box(Modifier.fillMaxWidth().padding(horizontal = 14.dp).heightIn(min = 1.dp, max = 1.dp).background(LocalPalette.current.line))
|
||||
|
||||
@Composable
|
||||
private fun ComponentRow(name: String, detail: String, checked: Boolean, enabled: Boolean, dim: Boolean, modifier: Modifier, onChange: (Boolean) -> Unit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp),
|
||||
modifier = Modifier.fillMaxWidth().padding(horizontal = 14.dp, vertical = 10.dp).alpha(if (dim) 0.55f else 1f),
|
||||
) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(name, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground)
|
||||
if (detail.isNotEmpty()) Text(detail, fontSize = 12.sp, lineHeight = 16.sp, color = colors.onSurfaceVariant)
|
||||
}
|
||||
ToggleSwitch(checked, enabled, name, modifier, onChange)
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package com.droiddeck.launcher.wayland
|
||||
|
||||
import android.view.Choreographer
|
||||
import android.view.Surface
|
||||
import com.droiddeck.launcher.session.SessionState
|
||||
|
||||
/**
|
||||
* The compositor is a process-wide thing, not an activity's: it is started once, keeps running
|
||||
@@ -35,13 +36,17 @@ object CompositorHost {
|
||||
fpsLimit: Int,
|
||||
): Boolean {
|
||||
pace(refreshHz, fpsLimit)
|
||||
// The compositor outlives sessions, and the next one may be on the other screen of a dual-screen
|
||||
// device: gamescope reads the size from the toplevel configure and the wl_output mode when it
|
||||
// connects, and kept the first session's (the Thor's 1920x1080 top screen letterboxed the bottom
|
||||
// one's session to 16:9). A running session keeps the size it was started at.
|
||||
if (!SessionState.running) WaylandCompositor.nativeSetOutputSize(outputWidth, outputHeight)
|
||||
if (started) {
|
||||
attached = surface
|
||||
WaylandCompositor.nativeSetSurface(surface)
|
||||
resumeVsync()
|
||||
return false
|
||||
}
|
||||
WaylandCompositor.nativeSetOutputSize(outputWidth, outputHeight)
|
||||
WaylandCompositor.nativeSetOutputRefreshRate(refreshHz)
|
||||
WaylandCompositor.nativeStartWithSurface(
|
||||
surface, xdgRuntimeDir, driverPath, libraryName, nativeLibDir,
|
||||
|
||||
@@ -285,8 +285,6 @@
|
||||
<string name="mode_added_launches_in">Inicia %1$s · en %2$s</string>
|
||||
<string name="mode_added_choose">Elegir otro archivo…</string>
|
||||
<string name="mode_added_exe_note">Por defecto, el .exe con el nombre de la carpeta o, si no, el más grande.</string>
|
||||
<string name="mode_fill">Estirar juegos para llenar la pantalla</string>
|
||||
<string name="mode_fill_hint">Mantiene a pantalla completa los juegos que se redimensionan solos. Desactívalo si un juego se ve pequeño. Se aplica en la próxima sesión.</string>
|
||||
<string name="mode_stretch169">Estirar juegos 16:9</string>
|
||||
<string name="mode_stretch169_hint">En pantallas más cuadradas que 16:9, estira los juegos para llenar en lugar de mostrar barras. Se aplica en la próxima sesión.</string>
|
||||
<string name="mode_audio">Audio</string>
|
||||
@@ -444,7 +442,6 @@
|
||||
<string name="drawer_prev_page">Página anterior</string>
|
||||
<string name="drawer_next_page">Página siguiente</string>
|
||||
<string name="drawer_hud">HUD de rendimiento</string>
|
||||
<string name="drawer_fill">Estirar juegos para llenar</string>
|
||||
<string name="drawer_scaling">Modo de escalado</string>
|
||||
<string name="drawer_scaling_sharpness">Nitidez del escalado</string>
|
||||
<string name="drawer_effects">Efectos de pantalla</string>
|
||||
|
||||
@@ -279,8 +279,6 @@
|
||||
<string name="mode_added_launches_in">Lancer %1$s · dans %2$s</string>
|
||||
<string name="mode_added_choose">Choisir un autre fichier…</string>
|
||||
<string name="mode_added_exe_note">Utilise par défaut le .exe portant le même nom que le dossier, sinon le .exe le plus volumineux.</string>
|
||||
<string name="mode_fill">Étirer le jeu pour remplir l\'écran</string>
|
||||
<string name="mode_fill_hint">Maintient en plein écran les jeux capables de se redimensionner. Désactivez cette option si le jeu s\'affiche en petit. Prendra effet à la prochaine session.</string>
|
||||
<string name="mode_stretch169">Étirer les jeux 16:9</string>
|
||||
<string name="mode_stretch169_hint">Sur les écrans dont le rapport d\'aspect est inférieur à 16:9, étire le jeu pour remplir l\'écran au lieu d\'afficher des bandes noires. Prendra effet à la prochaine session.</string>
|
||||
<string name="mode_audio">Audio</string>
|
||||
@@ -442,7 +440,6 @@
|
||||
<string name="drawer_prev_page">Page précédente</string>
|
||||
<string name="drawer_next_page">Page suivante</string>
|
||||
<string name="drawer_hud">HUD de performance</string>
|
||||
<string name="drawer_fill">Étirer le jeu pour remplir l\'écran</string>
|
||||
<string name="drawer_touch_auto">Auto (%1$s)</string>
|
||||
<string name="drawer_keyboard">Clavier</string>
|
||||
<string name="drawer_pc_keyboard">Clavier PC</string>
|
||||
|
||||
@@ -279,8 +279,6 @@
|
||||
<string name="mode_added_launches_in">%1$sを起動 · %2$s内</string>
|
||||
<string name="mode_added_choose">別のファイルを選択…</string>
|
||||
<string name="mode_added_exe_note">デフォルトではフォルダと同じ名前の.exeを使用し、ない場合は最大の.exeを使用します。</string>
|
||||
<string name="mode_fill">ゲームを引き伸ばして画面を埋める</string>
|
||||
<string name="mode_fill_hint">自身でサイズ変更できるゲームを全画面に保ちます。ゲームが小さく表示される場合はこれをオフにしてください。次回のセッションで有効になります。</string>
|
||||
<string name="mode_stretch169">16:9ゲームを引き伸ばす</string>
|
||||
<string name="mode_stretch169_hint">アスペクト比が16:9未満の画面で、黒帯を表示する代わりにゲームを引き伸ばして画面を埋めます。次回のセッションで有効になります。</string>
|
||||
<string name="mode_audio">オーディオ</string>
|
||||
@@ -442,7 +440,6 @@
|
||||
<string name="drawer_prev_page">前のページ</string>
|
||||
<string name="drawer_next_page">次のページ</string>
|
||||
<string name="drawer_hud">パフォーマンスHUD</string>
|
||||
<string name="drawer_fill">ゲームを引き伸ばして画面を埋める</string>
|
||||
<string name="drawer_touch_auto">自動(%1$s)</string>
|
||||
<string name="drawer_keyboard">キーボード</string>
|
||||
<string name="drawer_pc_keyboard">PCキーボード</string>
|
||||
|
||||
@@ -279,8 +279,6 @@
|
||||
<string name="mode_added_launches_in">%1$s 실행 · %2$s에 위치</string>
|
||||
<string name="mode_added_choose">다른 파일 선택…</string>
|
||||
<string name="mode_added_exe_note">기본적으로 폴더와 이름이 같은 .exe를 사용하고, 없으면 가장 큰 .exe를 사용합니다.</string>
|
||||
<string name="mode_fill">게임을 늘려 화면 채우기</string>
|
||||
<string name="mode_fill_hint">자체적으로 크기를 조절하는 게임을 전체 화면으로 유지합니다. 게임이 작게 표시되면 이 옵션을 끄세요. 다음 세션에 적용됩니다.</string>
|
||||
<string name="mode_stretch169">16:9 게임 늘리기</string>
|
||||
<string name="mode_stretch169_hint">가로세로 비율이 16:9 미만인 화면에서 검은색 여백 대신 게임을 늘려 화면을 채웁니다. 다음 세션에 적용됩니다.</string>
|
||||
<string name="mode_audio">오디오</string>
|
||||
@@ -442,7 +440,6 @@
|
||||
<string name="drawer_prev_page">이전 페이지</string>
|
||||
<string name="drawer_next_page">다음 페이지</string>
|
||||
<string name="drawer_hud">성능 HUD</string>
|
||||
<string name="drawer_fill">게임을 늘려 화면 채우기</string>
|
||||
<string name="drawer_touch_auto">자동(%1$s)</string>
|
||||
<string name="drawer_keyboard">키보드</string>
|
||||
<string name="drawer_pc_keyboard">PC 키보드</string>
|
||||
|
||||
@@ -279,8 +279,6 @@
|
||||
<string name="mode_added_launches_in">Запустить %1$s · в %2$s</string>
|
||||
<string name="mode_added_choose">Выбрать другой файл…</string>
|
||||
<string name="mode_added_exe_note">По умолчанию используется .exe с именем папки, иначе самый большой .exe.</string>
|
||||
<string name="mode_fill">Растянуть игру на весь экран</string>
|
||||
<string name="mode_fill_hint">Сохраняет полноэкранный режим для игр, поддерживающих изменение размера. Отключите, если игра отображается мелко. Вступит в силу в следующей сессии.</string>
|
||||
<string name="mode_stretch169">Растянуть игры 16:9</string>
|
||||
<string name="mode_stretch169_hint">На экранах с соотношением сторон менее 16:9 растягивает игру на весь экран вместо черных полос. Вступит в силу в следующей сессии.</string>
|
||||
<string name="mode_audio">Аудио</string>
|
||||
@@ -444,7 +442,6 @@
|
||||
<string name="drawer_prev_page">Предыдущая страница</string>
|
||||
<string name="drawer_next_page">Следующая страница</string>
|
||||
<string name="drawer_hud">HUD производительности</string>
|
||||
<string name="drawer_fill">Растянуть игру на весь экран</string>
|
||||
<string name="drawer_touch_auto">Авто (%1$s)</string>
|
||||
<string name="drawer_keyboard">Клавиатура</string>
|
||||
<string name="drawer_pc_keyboard">Клавиатура ПК</string>
|
||||
|
||||
@@ -301,8 +301,6 @@
|
||||
<string name="mode_added_launches_in">启动 %1$s · 位于 %2$s</string>
|
||||
<string name="mode_added_choose">选择其他文件…</string>
|
||||
<string name="mode_added_exe_note">默认为与文件夹同名的 .exe,否则为最大的那个。</string>
|
||||
<string name="mode_fill">拉伸游戏以填满屏幕</string>
|
||||
<string name="mode_fill_hint">使会自行缩放的游戏保持全屏。若游戏显示过小,请关闭此项。将在下次会话生效。</string>
|
||||
<string name="mode_stretch169">拉伸 16:9 比例的游戏</string>
|
||||
<string name="mode_stretch169_hint">在比 16:9 更方的屏幕上,拉伸游戏填满屏幕而不是显示黑边。将在下次会话生效。</string>
|
||||
<string name="mode_audio">音频</string>
|
||||
@@ -479,7 +477,6 @@
|
||||
<string name="drawer_prev_page">上一页</string>
|
||||
<string name="drawer_next_page">下一页</string>
|
||||
<string name="drawer_hud">性能 HUD</string>
|
||||
<string name="drawer_fill">拉伸游戏填满屏幕</string>
|
||||
<string name="drawer_scaling">缩放模式</string>
|
||||
<string name="drawer_scaling_sharpness">缩放锐度</string>
|
||||
<string name="drawer_effects">屏幕效果</string>
|
||||
|
||||
@@ -279,8 +279,6 @@
|
||||
<string name="mode_added_launches_in">啟動 %1$s · 位於 %2$s</string>
|
||||
<string name="mode_added_choose">選擇其他檔案…</string>
|
||||
<string name="mode_added_exe_note">默認使用與文件夾同名的 .exe,否則使用最大的 .exe。</string>
|
||||
<string name="mode_fill">拉伸遊戲以填滿屏幕</string>
|
||||
<string name="mode_fill_hint">讓支持自行調整大小的遊戲保持全屏幕。如果遊戲顯示得很小,請關閉此項。下次會話生效。</string>
|
||||
<string name="mode_stretch169">拉伸 16:9 遊戲</string>
|
||||
<string name="mode_stretch169_hint">在寬高比小於 16:9 的屏幕上,將遊戲拉伸以填滿屏幕,而不是顯示黑邊。下次會話生效。</string>
|
||||
<string name="mode_audio">音頻</string>
|
||||
@@ -442,7 +440,6 @@
|
||||
<string name="drawer_prev_page">上一頁</string>
|
||||
<string name="drawer_next_page">下一頁</string>
|
||||
<string name="drawer_hud">性能 HUD</string>
|
||||
<string name="drawer_fill">拉伸遊戲以填滿屏幕</string>
|
||||
<string name="drawer_touch_auto">自動(%1$s)</string>
|
||||
<string name="drawer_keyboard">鍵盤</string>
|
||||
<string name="drawer_pc_keyboard">電腦鍵盤</string>
|
||||
|
||||
@@ -279,8 +279,6 @@
|
||||
<string name="mode_added_launches_in">啟動 %1$s · 位於 %2$s</string>
|
||||
<string name="mode_added_choose">選擇其他檔案…</string>
|
||||
<string name="mode_added_exe_note">預設使用與資料夾同名的 .exe,否則使用最大的 .exe。</string>
|
||||
<string name="mode_fill">拉伸遊戲以填滿螢幕</string>
|
||||
<string name="mode_fill_hint">讓支援自行調整大小的遊戲保持全螢幕。如果遊戲顯示得很小,請關閉此項。下次工作階段生效。</string>
|
||||
<string name="mode_stretch169">拉伸 16:9 遊戲</string>
|
||||
<string name="mode_stretch169_hint">在長寬比小於 16:9 的螢幕上,將遊戲拉伸以填滿螢幕,而不是顯示黑邊。下次工作階段生效。</string>
|
||||
<string name="mode_audio">音訊</string>
|
||||
@@ -442,7 +440,6 @@
|
||||
<string name="drawer_prev_page">上一頁</string>
|
||||
<string name="drawer_next_page">下一頁</string>
|
||||
<string name="drawer_hud">效能 HUD</string>
|
||||
<string name="drawer_fill">拉伸遊戲以填滿螢幕</string>
|
||||
<string name="drawer_touch_auto">自動(%1$s)</string>
|
||||
<string name="drawer_keyboard">鍵盤</string>
|
||||
<string name="drawer_pc_keyboard">電腦鍵盤</string>
|
||||
|
||||
@@ -307,8 +307,29 @@
|
||||
<string name="mode_added_launches_in">Launches %1$s · in %2$s</string>
|
||||
<string name="mode_added_choose">Choose another file…</string>
|
||||
<string name="mode_added_exe_note">Defaults to the .exe named after the folder, or else the largest.</string>
|
||||
<string name="mode_fill">Stretch games to fill the screen</string>
|
||||
<string name="mode_fill_hint">Keeps self-resizing games full screen. Turn off if a game shows up small. Applies next session.</string>
|
||||
<string name="wincomp_title">Windows components</string>
|
||||
<string name="wincomp_pad_hint">LB / RB jump between the sections.</string>
|
||||
<string name="wincomp_card_none">None</string>
|
||||
<string name="wincomp_applies">Windows DLLs Proton does not include, from Bannerlator\'s component list. Turn on the ones this game needs: they go into the game\'s own Windows folder, never its files, and stay whichever Proton it runs on.</string>
|
||||
<string name="wincomp_offline">Could not reach the component list. Components already downloaded can still be switched.</string>
|
||||
<string name="wincomp_recommended">Recommended for this game</string>
|
||||
<string name="wincomp_found_bundled">The game ships %1$s</string>
|
||||
<string name="wincomp_found_shipped">The game has %1$s (often works as is)</string>
|
||||
<string name="wincomp_found_steam">Steam installs %1$s with this game</string>
|
||||
<string name="wincomp_already_here">Already in this game</string>
|
||||
<string name="wincomp_no_recommendation">Nothing in the game\'s folder points at a component.</string>
|
||||
<string name="wincomp_all">All components (%1$d)</string>
|
||||
<string name="wincomp_installers">Need a Windows installer (%1$d)</string>
|
||||
<string name="wincomp_installers_note">These run a real installer inside the prefix (.NET, PhysX, XNA, the full Visual C++ installers…). DroidDeck cannot do that yet; it is coming next.</string>
|
||||
<string name="wincomp_show">Show</string>
|
||||
<string name="wincomp_hide">Hide</string>
|
||||
<string name="wincomp_needs_installer">Needs a Windows installer (coming)</string>
|
||||
<string name="wincomp_unsupported">Not supported here yet</string>
|
||||
<string name="wincomp_loading">Loading the components…</string>
|
||||
<string name="wincomp_failed">Could not install: %1$s</string>
|
||||
<string name="wincomp_downloaded">Downloaded</string>
|
||||
<string name="wincomp_download_size">%1$s download</string>
|
||||
<string name="wincomp_next_launch">Takes effect the next time the game starts.</string>
|
||||
<string name="mode_stretch169">Stretch 16:9 games</string>
|
||||
<string name="mode_stretch169_hint">On screens squarer than 16:9, stretches games to fill instead of showing bars. Applies next session.</string>
|
||||
<string name="mode_audio">Audio</string>
|
||||
@@ -337,6 +358,8 @@
|
||||
<string name="mode_second_library">Second library</string>
|
||||
<string name="mode_storage_note">Games that stream assets from SD or shared storage may stutter.</string>
|
||||
<string name="mode_storage_diagnostics">Storage diagnostics</string>
|
||||
<string name="mode_skip_preallocation">Skip space reservation (experimental)</string>
|
||||
<string name="mode_skip_preallocation_hint">Steam starts downloading to the game storage folder straight away instead of reserving every file\'s space first, which can take many minutes on an SD card. If the card fills up, the download stops with a disk write error. Applies next session.</string>
|
||||
<string name="mode_storage_diagnostics_hint">Record allocation results and sampled storage timings in Share logs. May slow installs while enabled. Applies next session.</string>
|
||||
<string name="mode_choose_folder">Choose a folder…</string>
|
||||
<string name="mode_renderer">Renderer</string>
|
||||
@@ -487,7 +510,6 @@
|
||||
<string name="drawer_prev_page">Previous page</string>
|
||||
<string name="drawer_next_page">Next page</string>
|
||||
<string name="drawer_hud">Performance HUD</string>
|
||||
<string name="drawer_fill">Stretch games to fill</string>
|
||||
<string name="drawer_scaling">Scaling mode</string>
|
||||
<string name="drawer_scaling_sharpness">Scaling sharpness</string>
|
||||
<string name="drawer_effects">Screen effects</string>
|
||||
@@ -1039,11 +1061,15 @@
|
||||
<string name="display_filter_note">FSR, GSR and NIS apply when enlarging the session image. Sharpen only also works without enlargement.</string>
|
||||
<string name="display_sharpness">Filter sharpness</string>
|
||||
<string name="display_frame_rate">Frame rate</string>
|
||||
<string name="display_window_compatibility">Game window compatibility</string>
|
||||
<string name="display_force_fullscreen">Force game windows fullscreen</string>
|
||||
<string name="display_force_fullscreen_hint">Makes every game window the size of the screen. Turn on if a game comes back small or in a corner after switching apps; leave off if a game flickers between sizes. Applies live during a session.</string>
|
||||
<string name="display_force_fullscreen_live">Turn on if a game comes back small after switching; off if it flickers. Applies live.</string>
|
||||
<string name="display_look_filter">%1$s Sets scaling to %2$s.</string>
|
||||
<string name="display_match_screen">Match screen (%1$d×%2$d)</string>
|
||||
<string name="mode_tab_steam">Steam</string>
|
||||
<string name="device_info_show">Show device details</string>
|
||||
<string name="device_info_hide">Hide device details</string>
|
||||
<string name="device_info_loading">Reading the device…</string>
|
||||
<string name="device_info_copy">Copy</string>
|
||||
<string name="device_info_copy_hint">Copy these details into a bug report.</string>
|
||||
<string name="device_info_copied">Copied.</string>
|
||||
<string name="force_ssbs_title">Force SSBS</string>
|
||||
<string name="force_ssbs_hint">Keeps a CPU speed setting on that Wine keeps turning off. Can make Windows games faster on Snapdragon 8 Elite; little change seen on older chips. Applies on the next game launch.</string>
|
||||
</resources>
|
||||
@@ -11,6 +11,14 @@ class GameEnvironmentTest {
|
||||
assertEquals("6_9", values["VKD3D_SHADER_MODEL"])
|
||||
}
|
||||
|
||||
@Test fun forceSsbsIsADefaultAGameCanTurnOff() {
|
||||
assertFalse(GameEnvironment.defaults("").containsKey(GameEnvironment.FORCE_SSBS))
|
||||
assertEquals("1", GameEnvironment.defaults("", forceSsbs = true)[GameEnvironment.FORCE_SSBS])
|
||||
val config = GameEnvironment.Config().withEntries("42", mapOf(GameEnvironment.FORCE_SSBS to "0"))
|
||||
assertEquals("0", GameEnvironment.effective(config, "", "42", forceSsbs = true)[GameEnvironment.FORCE_SSBS])
|
||||
assertEquals("1", GameEnvironment.effective(config, "", "43", forceSsbs = true)[GameEnvironment.FORCE_SSBS])
|
||||
}
|
||||
|
||||
@Test fun gameOverridesSharedAndPresetWithoutLeakingToOtherGames() {
|
||||
val config = GameEnvironment.Config(
|
||||
shared = mapOf("FEX_MULTIBLOCK" to "0", "VKD3D_FEATURE_LEVEL" to "12_2"),
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
package com.droiddeck.launcher.frontend
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
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.annotation.Config
|
||||
import java.io.File
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [33])
|
||||
class WinComponentDetectorsTest {
|
||||
@get:Rule val tmp = TemporaryFolder()
|
||||
|
||||
@Test fun steamsSharedDepotsBecomeRecommendations() {
|
||||
val steamapps = tmp.newFolder("steamapps")
|
||||
val game = File(steamapps, "common/BioShock Remastered").apply { mkdirs() }
|
||||
File(steamapps, "appmanifest_409710.acf").writeText(
|
||||
"""
|
||||
"AppState"
|
||||
{
|
||||
"appid" "409710"
|
||||
"SharedDepots"
|
||||
{
|
||||
"228983" "228980"
|
||||
"228984" "228980"
|
||||
"228988" "228980"
|
||||
"228987" "228980"
|
||||
"228990" "228980"
|
||||
"999999" "228980"
|
||||
}
|
||||
}
|
||||
""".trimIndent(),
|
||||
)
|
||||
val found = SteamRedists.detect(game, 409710)
|
||||
assertEquals(listOf("vcredist2010_dll", "vcredist2012_dll", "vcredist2019_dll", "d3dx9"), found.map { it.componentName })
|
||||
assertTrue(found.all { it.kind == DependencyDetector.Kind.STEAM })
|
||||
assertEquals("VC++ 2010", found.first().reason)
|
||||
assertEquals(emptyList<DependencyDetector.Recommendation>(), SteamRedists.detect(game, 1))
|
||||
}
|
||||
|
||||
@Test fun thePrefixCountsOnlyWhatDroidDeckDidNotPutThere() {
|
||||
val compat = tmp.newFolder("compatdata", "409710")
|
||||
val pfx = File(compat, "pfx")
|
||||
File(pfx, "drive_c/windows/syswow64").mkdirs()
|
||||
File(pfx, "drive_c/windows/syswow64/OpenAL32.dll").writeText("x")
|
||||
File(pfx, "system.reg").writeText("[Software\\\\Microsoft\\\\Games for Windows Live]\n")
|
||||
assertEquals(setOf("oalinst", "XLiveRedist"), PrefixInstalledDetector.detect(compat))
|
||||
File(compat, ".droiddeck-wincomponents.json").writeText("""{"files": {"drive_c/windows/syswow64/openal32.dll": "oalinst_dll"}}""")
|
||||
assertEquals(setOf("XLiveRedist"), PrefixInstalledDetector.detect(compat))
|
||||
assertEquals(emptySet<String>(), PrefixInstalledDetector.detect(File(tmp.root, "missing")))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.droiddeck.launcher.gpu
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
|
||||
class GpuModelFallbackTest {
|
||||
@Test fun aPlatformCodeNameGivesItsAdreno() {
|
||||
// AYANEO's Pocket FIT: KGSL says "Adreno33v2", the platform says pineapple.
|
||||
assertEquals(750, GpuInfo.platformModel("pineapple"))
|
||||
assertEquals(740, GpuInfo.platformModel("KALAMA"))
|
||||
assertEquals(830, GpuInfo.platformModel("sun"))
|
||||
assertEquals(0, GpuInfo.platformModel("somethingelse"))
|
||||
assertEquals(GpuInfo.Family.A7XX, GpuInfo.familyOf(true, GpuInfo.platformModel("pineapple")))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.droiddeck.launcher.gpu
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Test
|
||||
|
||||
class SocNamesTest {
|
||||
private fun props(vararg pairs: Pair<String, String>): (String) -> String = { pairs.toMap()[it].orEmpty() }
|
||||
|
||||
@Test fun theModelIsFoundWhereVendorsPutIt() {
|
||||
// AYANEO Pocket FIT: ro.soc.model blank, the vendor property set, ro.fota.platform a branch name.
|
||||
assertEquals("SG8350P", SocNames.model(props("ro.vendor.qti.soc_model" to "SG8350P", "ro.fota.platform" to "MSM_13.0")))
|
||||
assertEquals("QCS8550", SocNames.model(props("ro.soc.model" to "QCS8550", "ro.vendor.qti.soc_model" to "other")))
|
||||
assertEquals("", SocNames.model(props("ro.fota.platform" to "MSM_13.0")))
|
||||
}
|
||||
|
||||
@Test fun knownModelsAndPlatformsGetTheirNames() {
|
||||
assertEquals("Snapdragon 8 Gen 2", SocNames.name("QCS8550", ""))
|
||||
assertEquals("Snapdragon 8 Gen 3 family", SocNames.name("SG8350P", "pineapple"))
|
||||
assertNull(SocNames.name("XYZ123", "nowhere"))
|
||||
assertEquals("Snapdragon 8 Gen 2 (QCS8550)", SocNames.label("QCS8550", ""))
|
||||
assertEquals("Snapdragon 8 Gen 3 family (SG8350P)", SocNames.label("SG8350P", "pineapple"))
|
||||
assertEquals("XYZ123", SocNames.label("XYZ123", ""))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.droiddeck.launcher.runtime
|
||||
|
||||
import org.junit.Assert.assertNotNull
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Test
|
||||
import java.io.File
|
||||
|
||||
class ProotFastPathTest {
|
||||
private val root = File("/data/data/com.droiddeck.launcher/files/linuxfs")
|
||||
|
||||
@Test fun aSessionsUsualBindsGetAKey() {
|
||||
// 87 on a device with two Games folders: past the old limit of 64, which dropped them.
|
||||
val binds = (1..87).map { "/host/$it:/guest/$it" }
|
||||
assertNotNull(ProotFastPath.key(root, binds))
|
||||
}
|
||||
|
||||
@Test fun moreBindsThanTheLibraryHoldsLeaveItOff() {
|
||||
val binds = (1..ProotFastPath.MAX_BINDS + 1).map { "/host/$it:/guest/$it" }
|
||||
assertNull(ProotFastPath.key(root, binds))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,238 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.content.Context
|
||||
import com.droiddeck.launcher.gpu.GpuInfo
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.RuntimeEnvironment
|
||||
import org.robolectric.annotation.Config
|
||||
import java.io.File
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [28], manifest = Config.NONE)
|
||||
class ForcedPackageTest {
|
||||
private val dxvk2 = "dxvk-2.7.1-linux.wcp"
|
||||
private lateinit var context: Context
|
||||
|
||||
@Before fun setUp() {
|
||||
context = RuntimeEnvironment.getApplication()
|
||||
File(context.filesDir, "components").deleteRecursively()
|
||||
LinuxRuntime.rootDir(context).deleteRecursively()
|
||||
}
|
||||
|
||||
@Test fun adreno6xxForcesDxvk2AndNothingElseDoes() {
|
||||
val rule = ComponentsManager.FORCED_PACKAGES.single { GpuInfo.Family.A6XX in it.families }
|
||||
assertEquals("dxvk", rule.comp)
|
||||
assertEquals(dxvk2, rule.file)
|
||||
assertEquals("Dxvk-Linux", rule.release)
|
||||
assertTrue(rule.models.isEmpty())
|
||||
assertTrue(rule.matches(gpu(650, GpuInfo.Family.A6XX)))
|
||||
assertTrue(rule.matches(gpu(610, GpuInfo.Family.A6XX)))
|
||||
assertTrue(rule.matches(gpu(690, GpuInfo.Family.A6XX)))
|
||||
assertFalse(rule.matches(gpu(740, GpuInfo.Family.A7XX)))
|
||||
assertFalse(rule.matches(gpu(830, GpuInfo.Family.A8XX)))
|
||||
assertTrue(ComponentsManager.FORCED_PACKAGES.none { GpuInfo.Family.A7XX in it.families })
|
||||
}
|
||||
|
||||
@Test fun aModelListOnlyMatchesThoseChips() {
|
||||
val rule = ComponentsManager.ForcedPackage(
|
||||
setOf(GpuInfo.Family.A7XX_LOW), "dxvk", dxvk2, "Dxvk-Linux", setOf(710),
|
||||
)
|
||||
assertTrue(rule.matches(gpu(710, GpuInfo.Family.A7XX_LOW)))
|
||||
assertFalse(rule.matches(gpu(720, GpuInfo.Family.A7XX_LOW)))
|
||||
assertFalse(rule.matches(gpu(710, GpuInfo.Family.A6XX)))
|
||||
assertFalse(ComponentsManager.ForcedPackage(emptySet(), "dxvk", dxvk2, "Dxvk-Linux").matches(gpu(650, GpuInfo.Family.A6XX)))
|
||||
}
|
||||
|
||||
@Test fun aShippedComponentIsReplacedUntilTheUserChoosesOne() {
|
||||
assertTrue(ComponentsManager.forcedPackageWanted(null, false))
|
||||
assertTrue(ComponentsManager.forcedPackageWanted(null, true))
|
||||
assertTrue(ComponentsManager.forcedPackageWanted("", false))
|
||||
assertFalse(ComponentsManager.forcedPackageWanted(dxvk2, true))
|
||||
assertTrue(ComponentsManager.forcedPackageWanted(dxvk2, false))
|
||||
assertFalse(ComponentsManager.forcedPackageWanted("dxvk-3.1-linux.wcp", true))
|
||||
assertTrue(ComponentsManager.forcedPackageWanted("dxvk-3.1-linux.wcp", false))
|
||||
assertTrue(ComponentsManager.forcedPackageWanted("dxvk-gplasync-2.7.1-1-linux.wcp", false))
|
||||
}
|
||||
|
||||
@Test fun catalogMatchPicksTheReleaseAndIgnoresAnother() {
|
||||
val wanted = item(dxvk2, "Dxvk-Linux")
|
||||
val otherRelease = item(dxvk2, "Dxvk-gplasync-Linux")
|
||||
val otherFile = item("dxvk-3.1-linux.wcp", "Dxvk-Linux")
|
||||
assertEquals(wanted, ComponentsManager.catalogMatch(listOf(otherFile, otherRelease, wanted), dxvk2, "Dxvk-Linux"))
|
||||
assertNull(ComponentsManager.catalogMatch(listOf(otherFile, otherRelease), dxvk2, "Dxvk-Linux"))
|
||||
assertNull(ComponentsManager.catalogMatch(emptyList(), dxvk2, "Dxvk-Linux"))
|
||||
}
|
||||
|
||||
@Test fun thisMachineIsNotForced() {
|
||||
assertNull(ComponentsManager.ensureForcedPackages(context))
|
||||
}
|
||||
|
||||
@Test fun anotherGpuIsLeftAlone() {
|
||||
proton("proton-exp")
|
||||
assertNull(install(gpu(740, GpuInfo.Family.A7XX)))
|
||||
}
|
||||
|
||||
@Test fun noInstalledProtonNeedsNothing() {
|
||||
assertNull(install(gpu(650, GpuInfo.Family.A6XX)))
|
||||
}
|
||||
|
||||
@Test fun aChosenPackageIsNotReplaced() {
|
||||
proton("proton-exp")
|
||||
writeState("proton-exp", "dxvk-3.1-linux.wcp", "experimental-11")
|
||||
assertNull(install(gpu(650, GpuInfo.Family.A6XX)))
|
||||
}
|
||||
|
||||
@Test fun theSamePackageOnThisProtonBuildIsNotFetchedAgain() {
|
||||
proton("proton-exp")
|
||||
writeState("proton-exp", dxvk2, "experimental-11")
|
||||
assertNull(install(gpu(650, GpuInfo.Family.A6XX)))
|
||||
}
|
||||
|
||||
@Test fun aMissingListingLeavesTheShippedCopy() {
|
||||
proton("proton-exp")
|
||||
val result = install(gpu(650, GpuInfo.Family.A6XX), lookup = { _, _ -> null })
|
||||
assertEquals("$dxvk2 is not in the Nightlies listing; DXVK stays on the Proton's copy", result)
|
||||
}
|
||||
|
||||
@Test fun aShippedCopyAndAProtonUpdateAreBothSwapped() {
|
||||
proton("kept")
|
||||
proton("proton-exp", "experimental-12")
|
||||
proton("other", "experimental-12")
|
||||
writeState("kept", "dxvk-3.1-linux.wcp", "experimental-11")
|
||||
writeState("proton-exp", dxvk2, "experimental-11")
|
||||
writeState("other", "dxvk-3.1-linux.wcp", "experimental-11")
|
||||
val fetched = mutableListOf<String>()
|
||||
val applied = mutableListOf<String>()
|
||||
val result = install(
|
||||
gpu(650, GpuInfo.Family.A6XX),
|
||||
lookup = { file, release -> item(file, release) },
|
||||
fetch = { fetched += it.file },
|
||||
apply = { id, file -> applied += "$id $file"; "DXVK 2.7.1 is now in $id. It applies the next time a game starts." },
|
||||
)
|
||||
assertEquals(listOf(dxvk2), fetched)
|
||||
assertEquals(listOf("other $dxvk2", "proton-exp $dxvk2"), applied)
|
||||
assertEquals(
|
||||
"DXVK 2.7.1 is now in other. It applies the next time a game starts.; " +
|
||||
"DXVK 2.7.1 is now in proton-exp. It applies the next time a game starts.",
|
||||
result,
|
||||
)
|
||||
}
|
||||
|
||||
@Test fun everyProtonStillOnItsShippedCopyIsSwapped() {
|
||||
proton("one")
|
||||
proton("two")
|
||||
val applied = mutableListOf<String>()
|
||||
val result = install(
|
||||
gpu(650, GpuInfo.Family.A6XX),
|
||||
lookup = { file, release -> item(file, release) },
|
||||
fetch = {},
|
||||
apply = { id, _ -> applied += id; "DXVK 2.7.1 is now in $id. It applies the next time a game starts." },
|
||||
)
|
||||
assertEquals(listOf("one", "two"), applied)
|
||||
assertEquals(
|
||||
"DXVK 2.7.1 is now in one. It applies the next time a game starts.; " +
|
||||
"DXVK 2.7.1 is now in two. It applies the next time a game starts.",
|
||||
result,
|
||||
)
|
||||
}
|
||||
|
||||
@Test fun aBrokenStoredPackageIsFetchedAgain() {
|
||||
proton("proton-exp")
|
||||
File(context.filesDir, "components/packages/$dxvk2").apply { parentFile!!.mkdirs(); writeText("not a package") }
|
||||
val fetched = mutableListOf<String>()
|
||||
install(
|
||||
gpu(650, GpuInfo.Family.A6XX),
|
||||
lookup = { file, release -> item(file, release) },
|
||||
fetch = { fetched += it.file },
|
||||
apply = { _, _ -> "swapped" },
|
||||
)
|
||||
assertEquals(listOf(dxvk2), fetched)
|
||||
assertFalse(File(context.filesDir, "components/packages/$dxvk2").isFile)
|
||||
}
|
||||
|
||||
@Test fun aFailedFetchIsLeftForTheSessionToLog() {
|
||||
proton("proton-exp")
|
||||
val applied = mutableListOf<String>()
|
||||
val error = assertThrows(IllegalStateException::class.java) {
|
||||
install(
|
||||
gpu(650, GpuInfo.Family.A6XX),
|
||||
lookup = { file, release -> item(file, release) },
|
||||
fetch = { throw IllegalStateException("Download failed") },
|
||||
apply = { id, _ -> applied += id; "" },
|
||||
)
|
||||
}
|
||||
assertEquals("Download failed", error.message)
|
||||
assertTrue(applied.isEmpty())
|
||||
}
|
||||
|
||||
@Test fun theCachedListingIsUsedBeforeRefreshing() {
|
||||
writeCatalog()
|
||||
assertEquals(cachedUrl, ComponentsManager.catalogItem(context, dxvk2, "Dxvk-Linux")?.url)
|
||||
}
|
||||
|
||||
@Test fun aCacheMissReadsTheRefreshedListingOnce() {
|
||||
var refreshes = 0
|
||||
val refreshed = item(dxvk2, "Dxvk-Linux")
|
||||
val found = ComponentsManager.resolveCatalogItem(dxvk2, "Dxvk-Linux", { emptyList() }, { refreshes += 1; listOf(refreshed) })
|
||||
assertEquals(refreshed, found)
|
||||
assertEquals(1, refreshes)
|
||||
assertNull(ComponentsManager.resolveCatalogItem("missing.wcp", "Dxvk-Linux", { emptyList() }, { refreshes += 1; emptyList() }))
|
||||
assertEquals(2, refreshes)
|
||||
val cached = item(dxvk2, "Dxvk-Linux")
|
||||
assertEquals(cached, ComponentsManager.resolveCatalogItem(dxvk2, "Dxvk-Linux", { listOf(cached) }, { error("refresh") }))
|
||||
}
|
||||
|
||||
private fun gpu(model: Int, family: GpuInfo.Family) = GpuInfo("Adreno $model", model, family, "", false)
|
||||
|
||||
private fun install(
|
||||
gpu: GpuInfo,
|
||||
lookup: (String, String) -> ComponentsManager.CatalogItem? = ::refuseLookup,
|
||||
fetch: (ComponentsManager.CatalogItem) -> Unit = ::refuseFetch,
|
||||
apply: (String, String) -> String = ::refuseApply,
|
||||
) = ComponentsManager.ensureForcedPackages(context, gpu, lookup, fetch, apply)
|
||||
|
||||
private fun refuseLookup(file: String, release: String): ComponentsManager.CatalogItem? = error("catalog $file $release")
|
||||
|
||||
private fun refuseFetch(item: ComponentsManager.CatalogItem) { error("fetch ${item.file}") }
|
||||
|
||||
private fun refuseApply(protonId: String, file: String): String = error("apply $protonId $file")
|
||||
|
||||
private fun proton(name: String, version: String = "experimental-11") {
|
||||
val dir = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/steamapps/common/$name")
|
||||
File(dir, "files/lib/wine").mkdirs()
|
||||
File(dir, "proton").writeText("#!/bin/sh\n")
|
||||
File(dir, "version").writeText("1 $version\n")
|
||||
}
|
||||
|
||||
private fun writeState(protonId: String, file: String, protonVersion: String) {
|
||||
val state = File(context.filesDir, "components/state.json")
|
||||
state.parentFile!!.mkdirs()
|
||||
val active = if (state.isFile) JSONObject(state.readText()).getJSONObject("active") else JSONObject()
|
||||
active.put(protonId, JSONObject().put("dxvk", JSONObject().put("file", file).put("protonVersion", protonVersion)))
|
||||
state.writeText(JSONObject().put("active", active).put("queued", JSONObject()).toString())
|
||||
}
|
||||
|
||||
private val cachedUrl = "https://github.com/The412Banner/Nightlies/releases/download/Dxvk-Linux/$dxvk2?cached=1"
|
||||
|
||||
private fun writeCatalog() {
|
||||
val cache = File(context.filesDir, "components/catalog.json")
|
||||
cache.parentFile!!.mkdirs()
|
||||
cache.writeText(JSONObject()
|
||||
.put("fetchedAt", 1)
|
||||
.put("items", JSONArray().put(JSONObject()
|
||||
.put("file", dxvk2).put("comp", "dxvk").put("release", "Dxvk-Linux")
|
||||
.put("url", cachedUrl).put("size", 4).put("digest", "sha256:" + "ab".repeat(32))))
|
||||
.toString())
|
||||
}
|
||||
|
||||
private fun item(file: String, release: String) = ComponentsManager.CatalogItem(
|
||||
file, "dxvk", release, "https://github.com/The412Banner/Nightlies/releases/download/$release/$file", 4, "sha256:" + "ab".repeat(32),
|
||||
)
|
||||
}
|
||||
@@ -4,18 +4,34 @@ import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
|
||||
class SessionDisplayTest {
|
||||
@Test fun explicitPresetsAndMatchScreenResolveWithoutAnyAspectSetting() {
|
||||
@Test fun fixedSizesAndMatchScreenResolveWithoutAnyAspectSetting() {
|
||||
assertEquals(1280 to 720, SessionDisplay.resolveChoice(1440 to 1080, "1280x720"))
|
||||
assertEquals(1600 to 900, SessionDisplay.resolveChoice(1280 to 720, "1600x900"))
|
||||
assertEquals(1440 to 1080, SessionDisplay.resolveChoice(1080 to 1440, SessionDisplay.MATCH_SCREEN))
|
||||
assertEquals(2400 to 1080, SessionDisplay.resolveChoice(1080 to 2400, SessionDisplay.MATCH_SCREEN))
|
||||
}
|
||||
|
||||
@Test fun panelOptionReplacesTheIdenticalPresetAndTracksPanelChanges() {
|
||||
@Test fun heightPresetsKeepThePanelShapeWithASixteenByNineFloor() {
|
||||
// 20:9 phone: edge to edge, no bars for the client's interface.
|
||||
assertEquals(1600 to 720, SessionDisplay.resolveChoice(2400 to 1080, SessionDisplay.DEFAULT_RESOLUTION))
|
||||
assertEquals(1608 to 720, SessionDisplay.resolveChoice(2412 to 1080, "720p"))
|
||||
// 1440p phone: bounded by the preset height, not the panel.
|
||||
assertEquals(1560 to 720, SessionDisplay.resolveChoice(3120 to 1440, "720p"))
|
||||
assertEquals(2340 to 1080, SessionDisplay.resolveChoice(3120 to 1440, "1080p"))
|
||||
// Foldable inner panel and 4:3 handhelds: never narrower than 16:9.
|
||||
assertEquals(1280 to 720, SessionDisplay.resolveChoice(2208 to 1840, "720p"))
|
||||
assertEquals(1280 to 720, SessionDisplay.resolveChoice(1440 to 1080, "720p"))
|
||||
// Never taller than the panel.
|
||||
assertEquals(1280 to 720, SessionDisplay.resolveChoice(1280 to 720, "1080p"))
|
||||
}
|
||||
|
||||
@Test fun optionsListTheHeightsThePanelCanShowThenThePanel() {
|
||||
val thor = SessionDisplay.resolutionOptions(1920 to 1080)
|
||||
assertEquals(listOf("1280x720", "1600x900", SessionDisplay.MATCH_SCREEN), thor)
|
||||
assertEquals(listOf("720p", "900p", SessionDisplay.MATCH_SCREEN), thor)
|
||||
assertEquals(listOf("720p", "900p", SessionDisplay.MATCH_SCREEN), SessionDisplay.resolutionOptions(2400 to 1080))
|
||||
assertEquals(listOf("720p", "900p", "1080p", SessionDisplay.MATCH_SCREEN), SessionDisplay.resolutionOptions(3120 to 1440))
|
||||
val small = SessionDisplay.resolutionOptions(1280 to 720)
|
||||
assertFalse(small.contains("1280x720"))
|
||||
assertEquals(listOf(SessionDisplay.MATCH_SCREEN), small)
|
||||
assertEquals(1280 to 720, SessionDisplay.resolveChoice(1280 to 720, SessionDisplay.MATCH_SCREEN))
|
||||
assertEquals(2560 to 1440, SessionDisplay.resolveChoice(2560 to 1440, SessionDisplay.MATCH_SCREEN))
|
||||
}
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import com.droiddeck.launcher.core.LogRedactor
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
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.util.zip.ZipFile
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [28], manifest = Config.NONE)
|
||||
class SessionLogShareTest {
|
||||
@get:Rule val tmp = TemporaryFolder()
|
||||
|
||||
private val secret = "GET /x?sessionid=abcdef123456 200"
|
||||
private val leaked = "abcdef123456"
|
||||
|
||||
private fun zip(folder: File): Map<String, String> =
|
||||
ZipFile(SessionLogShare.zipFolder(RuntimeEnvironment.getApplication(), folder)!!).use { z ->
|
||||
z.entries().toList().associate { it.name.substringAfter('/') to z.getInputStream(it).bufferedReader().readText() }
|
||||
}
|
||||
|
||||
/** A record as the session's ending writes it, listing [files] as they stand now. */
|
||||
private fun record(folder: File, vararg files: String, rules: Int = LogRedactor.RULES_VERSION) {
|
||||
File(folder, SessionArtifacts.SCRUBBED_TREE_MARKER).writeText(
|
||||
"rules $rules\n" + files.joinToString("") { val f = File(folder, it); "${f.length()}\t${f.lastModified()}\t$it\n" })
|
||||
}
|
||||
|
||||
@Test fun aRecordedUnchangedFileGoesInAsItIs() {
|
||||
val folder = tmp.newFolder("2026-10-06-01-steam")
|
||||
// Stands in for a file the ending scrubbed; the share must not pass it through again.
|
||||
File(folder, "session.log").writeText("$secret\n")
|
||||
record(folder, "session.log")
|
||||
assertTrue(zip(folder).getValue("session.log").contains(leaked))
|
||||
}
|
||||
|
||||
@Test fun anythingTheRecordDoesNotVouchForIsScrubbed() {
|
||||
val folder = tmp.newFolder("2026-10-06-02-steam")
|
||||
File(folder, "app.log").writeText("ok\n")
|
||||
File(folder, "session.log").writeText("ok\n")
|
||||
File(folder, "steam/deep").mkdirs()
|
||||
File(folder, "steam/deep/nested.txt").writeText("$secret\n")
|
||||
File(folder, ".hidden.txt").writeText("$secret\n")
|
||||
record(folder, "app.log", "session.log")
|
||||
// Appended to after the ending (the app's log capture), and touched with an older time.
|
||||
File(folder, "app.log").appendText("$secret\n")
|
||||
File(folder, "session.log").apply { writeText("$secret\n".padEnd(3, ' ')); setLastModified(1_000L) }
|
||||
File(folder, "events.jsonl").writeText("$secret\n")
|
||||
|
||||
val out = zip(folder)
|
||||
for (name in listOf("app.log", "session.log", "steam/deep/nested.txt", ".hidden.txt", "events.jsonl"))
|
||||
assertFalse(name, out.getValue(name).contains(leaked))
|
||||
}
|
||||
|
||||
@Test fun aRecordUnderOtherRedactorRulesVouchesForNothing() {
|
||||
val folder = tmp.newFolder("2026-10-06-03-steam")
|
||||
File(folder, "session.log").writeText("$secret\n")
|
||||
record(folder, "session.log", rules = LogRedactor.RULES_VERSION - 1)
|
||||
assertFalse(zip(folder).getValue("session.log").contains(leaked))
|
||||
}
|
||||
|
||||
@Test fun withoutARecordEveryFileIsScrubbed() {
|
||||
val folder = tmp.newFolder("2026-10-06-04-steam")
|
||||
File(folder, "session.log").writeText("$secret\n")
|
||||
File(folder, "steam").mkdirs()
|
||||
File(folder, "steam/console_log.txt").writeText("$secret\n")
|
||||
val out = zip(folder)
|
||||
assertFalse(out.getValue("session.log").contains(leaked))
|
||||
assertFalse(out.getValue("steam/console_log.txt").contains(leaked))
|
||||
}
|
||||
|
||||
@Test fun theEndingScrubsEveryFolderAndRecordsWhatItScrubbed() {
|
||||
val folder = tmp.newFolder("2026-10-06-05-steam")
|
||||
File(folder, "session.log").writeText("$secret\n")
|
||||
File(folder, "droiddeck-esync").mkdirs()
|
||||
File(folder, "droiddeck-esync/launches.log").writeText("$secret\n")
|
||||
File(folder, "steam/deep").mkdirs()
|
||||
File(folder, "steam/deep/nested.txt").writeText("$secret\n")
|
||||
|
||||
SessionArtifacts.scrubAndMark(folder)
|
||||
|
||||
for (name in listOf("session.log", "droiddeck-esync/launches.log", "steam/deep/nested.txt"))
|
||||
assertFalse(name, File(folder, name).readText().contains(leaked))
|
||||
assertEquals(setOf("session.log", "droiddeck-esync/launches.log", "steam/deep/nested.txt"),
|
||||
SessionArtifacts.scrubbedFiles(folder))
|
||||
assertTrue(zip(folder).values.none { it.contains(leaked) })
|
||||
}
|
||||
|
||||
@Test fun aFileThatCouldNotBeScrubbedLeavesTheFolderUnrecorded() {
|
||||
val folder = tmp.newFolder("2026-10-06-06-steam")
|
||||
File(folder, "session.log").writeText("$secret\n")
|
||||
// A folder the scrubbed copy cannot be written into: the scrub fails, the original stays.
|
||||
folder.setWritable(false)
|
||||
try {
|
||||
SessionArtifacts.scrubAndMark(folder)
|
||||
} finally {
|
||||
folder.setWritable(true)
|
||||
}
|
||||
assertTrue(File(folder, "session.log").readText().contains(leaked))
|
||||
assertFalse(File(folder, SessionArtifacts.SCRUBBED_TREE_MARKER).exists())
|
||||
assertTrue(SessionArtifacts.scrubbedFiles(folder).isEmpty())
|
||||
assertTrue(zip(folder).values.none { it.contains(leaked) })
|
||||
}
|
||||
|
||||
@Test fun steamLogsPastTheSizeLimitStayOut() {
|
||||
val folder = tmp.newFolder("2026-10-06-07-steam")
|
||||
File(folder, "session.log").writeText("ok\n")
|
||||
File(folder, "steam").mkdirs()
|
||||
File(folder, "steam/console_log.txt").writeText("ok\n")
|
||||
File(folder, "steam/cef_log.previous.txt").outputStream().use { out ->
|
||||
val line = ByteArray(1024) { 'x'.code.toByte() }.also { it[it.size - 1] = '\n'.code.toByte() }
|
||||
repeat(9 * 1024) { out.write(line) }
|
||||
}
|
||||
val names = zip(folder).keys
|
||||
assertTrue("steam/console_log.txt" in names)
|
||||
assertFalse("steam/cef_log.previous.txt" in names)
|
||||
}
|
||||
}
|
||||
@@ -42,7 +42,9 @@ class SessionScalingPrefsTest {
|
||||
|
||||
@Test fun freshSettingsUseTheConcreteDefaultAndCustomSizesAreNormalized() {
|
||||
val context = RuntimeEnvironment.getApplication()
|
||||
assertEquals("1280x720", SessionPrefs.resolutionChoice(context, "steam", 2400 to 1080))
|
||||
assertEquals(SessionDisplay.DEFAULT_RESOLUTION, SessionPrefs.resolutionChoice(context, "steam", 2400 to 1080))
|
||||
SessionPrefs.setResolutionChoice(context, "steam", "900p")
|
||||
assertEquals("900p", SessionPrefs.resolutionChoice(context, "steam", 2400 to 1080))
|
||||
SessionPrefs.setResolutionChoice(context, "steam", "1025×769")
|
||||
assertEquals("1024x768", SessionPrefs.resolutionChoice(context, "steam", 2400 to 1080))
|
||||
}
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
|
||||
class WinComponentNamesTest {
|
||||
@Test fun catalogKeysReadAsPeopleKnowThem() {
|
||||
val names = mapOf(
|
||||
"oalinst_dll" to "OpenAL", "vcredist2010_dll" to "Visual C++ 2010", "vcredist2022" to "Visual C++ 2015-2022",
|
||||
"dotnet48" to ".NET Framework 4.8", "dotnet452" to ".NET Framework 4.5.2", "dotnet20sp1" to ".NET Framework 2.0 SP1",
|
||||
"d3dcompiler_47" to "D3DCompiler 47", "xaudio2.7" to "XAudio 2.7", "mono-10.4.1" to "Wine Mono 10.4.1",
|
||||
"msxml6" to "MSXML 6", "dmsynth" to "DirectMusic (dmsynth)", "XLiveRedist" to "Games for Windows Live",
|
||||
"something-new" to "something-new",
|
||||
)
|
||||
for ((id, name) in names) assertEquals(id, name, WinComponentNames.of(id))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import com.droiddeck.launcher.session.WinComponents.Support
|
||||
import org.json.JSONObject
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.annotation.Config
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [33])
|
||||
class WinComponentsSupportTest {
|
||||
private val base = "https://github.com/The412Banner/winlator-contents/releases/download/system-libraries-v1"
|
||||
|
||||
private fun step(action: String, vararg pairs: Pair<String, String>) =
|
||||
WinComponents.Step(action, JSONObject().apply { pairs.forEach { (k, v) -> put(k, v) } })
|
||||
|
||||
private fun component(name: String, vararg steps: WinComponents.Step) =
|
||||
WinComponents.Component(name, "", "", "ready", emptyList(), steps.toList())
|
||||
|
||||
private fun support(c: WinComponents.Component) = WinComponents.support(c, mapOf(c.name to c))
|
||||
|
||||
@Test fun windowsInstallerPackagesInstallHere() {
|
||||
assertEquals(Support.READY, support(component("xna40", step("install_msi", "url" to "$base/xna40.msi"))))
|
||||
// The catalog names some .msi packages install_exe.
|
||||
assertEquals(Support.READY, support(component("XLiveRedist",
|
||||
step("install_exe", "url" to "$base/XLiveRedist.msi", "file_name" to "XLiveRedist1.2.0238.msi"))))
|
||||
assertEquals(Support.READY, support(component("msxml3", step("delete_dlls", "dest" to "win32"),
|
||||
step("override_dll", "dll" to "msxml3", "type" to "native"), step("install_msi", "url" to "$base/msxml3.msi"))))
|
||||
assertEquals(Support.READY, support(component("powershell_core",
|
||||
step("install_msi", "url" to "$base/ps-x86.msi"), step("install_msi", "url" to "$base/ps-x64.msi"))))
|
||||
}
|
||||
|
||||
@Test fun otherInstallersStillWait() {
|
||||
assertEquals(Support.NEEDS_INSTALLER, support(component("dotnet48", step("install_exe", "url" to "$base/ndp48.exe"))))
|
||||
// An uninstall step first (wine-mono) is not something done here.
|
||||
assertEquals(Support.NEEDS_INSTALLER, support(component("mono", step("uninstall"),
|
||||
step("install_msi", "url" to "$base/mono.msi"))))
|
||||
assertEquals(Support.NEEDS_INSTALLER, support(component("plain", step("install_msi", "url" to "http://example.com/a.msi"))))
|
||||
}
|
||||
|
||||
@Test fun whatProtonShipsIsNotOffered() {
|
||||
assertEquals(Support.UNSUPPORTED, support(component("gecko", step("install_msi", "url" to "$base/gecko.msi"))))
|
||||
}
|
||||
}
|
||||
@@ -23,6 +23,11 @@ and explicit removals take precedence over these defaults. FEX's own default
|
||||
remains the default preset. Shader caching in VKD3D/DXVK, synchronization, ray
|
||||
tracing and diagnostic logging otherwise retain the runtime's defaults.
|
||||
|
||||
On an Adreno 6xx, Turnip does not expose `storageBuffer8BitAccess`, which DXVK 3
|
||||
requires. A Steam or desktop session installs DXVK 2.7.1 into any Proton whose
|
||||
DXVK is still the copy that Proton shipped, including after a Proton update put
|
||||
that copy back. A DXVK package chosen in Components stays for that Proton build.
|
||||
|
||||
The variable-name picker offers 24 predefined variables and a Custom entry. Like
|
||||
WinNative, known variables use toggles, value dropdowns, multi-select lists, or
|
||||
numeric/text fields. Feature-level and shader-model dropdowns also accept custom
|
||||
|
||||
@@ -0,0 +1,230 @@
|
||||
# Steam session display sizing: research and device tests
|
||||
|
||||
Started 2026-10-06. This is a working log. Findings are added as they are measured on a device, so
|
||||
it reads in order.
|
||||
|
||||
## Question
|
||||
|
||||
Should the Steam session run gamescope at the panel's own size and let gamescope scale games, the
|
||||
way SteamOS does, instead of one session resolution shared by the Steam client and every game
|
||||
(1280x720 16:9 by default) that our compositor stretches onto the panel? What does that mean on
|
||||
very high-resolution panels and on foldables?
|
||||
|
||||
## How the session is sized today (main @ c636eea3)
|
||||
|
||||
- `droiddeck-session` starts gamescope with `-W/-H` (output) = `-w/-h` (nested, what games and the
|
||||
client see) = `BL_WIDTH x BL_HEIGHT`, the per-mode "Resolution" setting. The default is
|
||||
`1280x720` (`SessionDisplay.DEFAULT_RESOLUTION`). One Xwayland server holds both the Steam
|
||||
client and the games.
|
||||
- The Android compositor (`waylandcomp`) draws gamescope's output into a panel-sized swapchain
|
||||
(2414x1080 on a 20:9 phone) and fits it with bars where the shapes differ.
|
||||
- "Force game windows fullscreen" (`--force-windows-fullscreen`, off by default since #276) makes
|
||||
every window the nested size. A game whose own resolution differs fights it, and the resize
|
||||
storm that follows piles up GPU buffers until the low-memory killer ends the session (seen
|
||||
2026-10-06 on the AYN Thor with Alan Wake's American Nightmare).
|
||||
|
||||
Why the current choices were made, from the history:
|
||||
|
||||
| Choice | Reason given | Source |
|
||||
|---|---|---|
|
||||
| 720p default | The Steam client's CEF is the heaviest thing in a session, and 720p keeps Big Picture responsive on a regular flagship | `SessionPrefs.resolutionCap` comment |
|
||||
| Never narrower than 16:9 | Games handed a near-square display (Fold inner panel) crop their own menus | `d2ea9b89` |
|
||||
| 16:9 stretch option | Games on a narrow panel letterbox themselves; stretch fills it | #63, #133 |
|
||||
| Custom resolution | Parity with Bannerlator, 4:3 and 16:10 presets | `ad2f9f8a` |
|
||||
| Force fullscreen | A game that shrinks its window on focus loss (FlatOut) comes back small in a corner | #276, `droiddeck-session` |
|
||||
|
||||
## How SteamOS-style sessions do it
|
||||
|
||||
- gamescope output at the panel's size, `--xwayland-count 2`, and `STEAM_MULTIPLE_XWAYLANDS=1`
|
||||
(ChimeraOS `gamescope-session-plus` defaults to two Xwayland servers). The client lives on
|
||||
one server and games on the other.
|
||||
- Per-game "Game Resolution" (Deck mode game properties): Steam writes
|
||||
`GAMESCOPE_XWAYLAND_MODE_CONTROL = {server, width, height, allow_super_res}` on the root window,
|
||||
and gamescope resizes that Xwayland server (`steamcompmgr.cpp`, the `gamescopeXWaylandModeControl`
|
||||
handler). gamescope then scales the game to the output with the scaler and filter chosen in the QAM.
|
||||
- `GAMESCOPE_STEAM_MAX_HEIGHT` on the root window caps only the Steam client's window height, and
|
||||
gamescope scales it up (`steamcompmgr.cpp`, the `g_nSteamMaxHeight` branch). So a native output
|
||||
need not make the client render natively.
|
||||
- Our gamescope (3.16.29-p5) contains both atoms (checked in the installed binary on the Thor). We
|
||||
use neither, and we don't pass `--xwayland-count`.
|
||||
|
||||
## Android side
|
||||
|
||||
- Hardware scaler: a surface whose buffer is smaller than the view is scaled by the display
|
||||
hardware at no GPU cost (`SurfaceHolder.setFixedSize`; Android Developers blog 2013, NVIDIA).
|
||||
Our compositor always renders a panel-sized swapchain and scales on the GPU.
|
||||
- Android 16 ignores orientation and aspect-ratio locks on large screens, except for games. The
|
||||
manifest's game category covers us.
|
||||
- `game_mode_config.xml` already refuses OEM downscaling and FPS overrides.
|
||||
|
||||
## Device tests
|
||||
|
||||
All runs on the AYN Thor (SD 8 Gen 2, Adreno 740, 1920x1080 top panel), Deck mode on, Force
|
||||
fullscreen off, with a spike build of `feat/steam-native-output`. Each run sets
|
||||
`Download/droiddeck-env` and starts the session with
|
||||
`am start -n com.droiddeck.launcher/.SessionActivity --es mode steam [--es steamUrl ...]`.
|
||||
|
||||
### Run 1: baseline (Resolution = Match screen, 1920x1080)
|
||||
|
||||
Steam UI idle: GPU 0%, gamescope 27 dma-bufs, Xwayland 39. Everything renders at 1920x1080.
|
||||
|
||||
### Run 2: client height cap (`BL_STEAM_MAX_HEIGHT=720`)
|
||||
|
||||
- Log: `== steam: the client's height capped at 720 (was unset)`. The client never wrote its own
|
||||
value during the run, so a one-time set would hold.
|
||||
- On screen: the Steam UI lays out at 1280x720 and gamescope scales it to fill 1920x1080. The
|
||||
mangoapp overlay stays at native size and sharpness, so the cap affects only the client's window.
|
||||
|
||||
### Run 3: two Xwayland servers (`--xwayland-count 2`, `STEAM_MULTIPLE_XWAYLANDS=1`), Alan Wake's American Nightmare, Force fullscreen off
|
||||
|
||||
- gamescope starts Xwayland on `:0` and `:1`. The client stays on `:0`, and the game runs on `:1`:
|
||||
the second Xwayland's dma-buf count rises when the game starts.
|
||||
- The game runs full screen at about 60 fps with one swapchain, no resize churn, and stable buffer
|
||||
counts. Nothing visibly broke in the client.
|
||||
|
||||
### Run 4: as run 3, Force fullscreen on
|
||||
|
||||
The storm still happens. The games' Xwayland went from 16 to 840 dma-bufs in about 13 s, and the
|
||||
memory guard (kills the session under 2.5 GB free) stopped it. gamescope logged no mode change for
|
||||
server `#1`, so it stayed at the output size (1920x1080) while the game draws at 1280x720.
|
||||
|
||||
### Run 5: as run 4, writing `GAMESCOPE_XWAYLAND_MODE_CONTROL = 1,1280,720,0` at session start
|
||||
|
||||
gamescope applied it (`Updating mode for xwayland server #1: 1280x720`), then the client set it
|
||||
back to `1920x1080` when it launched the game, and the storm followed. **The client manages the games'
|
||||
Xwayland size itself:** at each launch it writes the game's "Game Resolution", which defaults to
|
||||
native.
|
||||
|
||||
### Run 6: as run 5, writing the mode 5 s after the game takes focus (what a chosen Game Resolution does)
|
||||
|
||||
**No storm.** Force fullscreen on, games' Xwayland at 1280x720: 10 dma-bufs on `:1` and 41 in
|
||||
gamescope for the whole run, 9 frame-size changes in total (runs 4/5: 835 and 1591), memory
|
||||
steady, 60 fps. gamescope scales the 1280x720 game to fill 1920x1080.
|
||||
|
||||
**Conclusion so far:** the resize storm comes from Force fullscreen resizing a game window to a
|
||||
display size the game won't accept. With the games on their own Xwayland server at the game's own
|
||||
resolution, Force fullscreen is harmless. Two Xwayland servers alone don't help, because the client
|
||||
sizes the games' server to native unless the game's resolution is set.
|
||||
|
||||
### Run 7: two Xwayland servers, output 1920x1080, `-w 1280 -h 720` (games 720p), Alan Wake, Force fullscreen off
|
||||
|
||||
The client ignores gamescope's nested size. It set both servers to the output size
|
||||
(`#0: 1920x1080`, `#1: 1920x1080`). **The client's "native" game resolution is gamescope's output
|
||||
size.** A panel-sized output on a 3120x1440 phone would therefore make every game default to
|
||||
3120x1440 until a per-game resolution is chosen.
|
||||
|
||||
Side finding: gamescope passed the game's 1280x720 buffers straight through to our compositor (its
|
||||
frame size changed to 1280x720) instead of compositing at the output size. Our compositor does the
|
||||
final scale either way.
|
||||
|
||||
### Default resolution history
|
||||
|
||||
Before #247 the default was `resolutionCap = 720` with shape `auto`: the panel's own shape at 720
|
||||
lines, never narrower than 16:9 (`SessionDisplay.resolve`). On a 2412x1080 phone that is 1608x720,
|
||||
which is exactly the "custom" size a tester had been using. #247 replaced it with fixed 16:9
|
||||
presets (`1280x720` default, `1600x900`, `1920x1080`). Those draw the client with bars on any panel
|
||||
wider than 16:9, which is the black border the tester reported after #247.
|
||||
|
||||
## Conclusions
|
||||
|
||||
1. **The output size sets the default game resolution** (run 7), so it must stay bounded on
|
||||
very high-resolution panels. A native output is only safe on panels about 1080 lines or shorter.
|
||||
2. **The output should keep the panel's shape**, so the client's interface is edge to edge, with
|
||||
the 16:9 floor from `d2ea9b89` so a foldable's inner panel doesn't make games crop themselves.
|
||||
3. **The resize storm is Force fullscreen against a display size the game won't accept** (runs
|
||||
4 to 6). The SteamOS model fixes it: two Xwayland servers, with the games' server at the game's
|
||||
resolution. That needs a per-game Game Resolution, so it is a follow-up, not a default.
|
||||
4. `GAMESCOPE_STEAM_MAX_HEIGHT` caps only the client and works on our gamescope (run 2). It
|
||||
becomes useful when the output is larger than the client should render, so it belongs with
|
||||
any future native-output option.
|
||||
|
||||
## Change made (this branch)
|
||||
|
||||
The resolution presets are heights: **720p (default), 900p, 1080p**, each in the panel's shape,
|
||||
never narrower than 16:9 and never taller than the panel. Then Match screen (exact panel), then
|
||||
Custom. Saved fixed sizes, custom sizes and Match screen are unchanged. Only the default and the
|
||||
preset list change. Resolved sizes:
|
||||
|
||||
| Panel | 720p | 900p | 1080p |
|
||||
|---|---|---|---|
|
||||
| 1920x1080 (Thor, 16:9) | 1280x720 | 1600x900 | Match screen |
|
||||
| 2412x1080 (20:9 phone) | 1608x720 | 2010x900 | Match screen |
|
||||
| 3120x1440 (1440p phone) | 1560x720 | 1950x900 | 2340x1080 |
|
||||
| 2208x1840 (foldable inner) | 1280x720 | 1600x900 | 1920x1080 |
|
||||
|
||||
### Run 9: default on the Thor
|
||||
|
||||
With no saved resolution (the saved choice, legacy shape and cap removed from `session.xml`, then
|
||||
restored): the session starts at `size=1280x720` and the device report shows `720p (1280x720)`.
|
||||
|
||||
## Follow-ups
|
||||
|
||||
- **Two Xwayland servers and per-game Game Resolution** (done, see below). Was to verify: whether the client shows
|
||||
Game Resolution under game Properties in our session, the Android clipboard bridge for games on
|
||||
`:1`, and the drawer's live Force fullscreen toggle (it writes `GAMESCOPE_FORCE_WINDOWS_FULLSCREEN`
|
||||
only on `:0`'s root, and gamescope reads it per server). The client's devtools (port 8080 when
|
||||
`.cef-enable-remote-debugging` exists) accept guest processes only, so test it from inside the
|
||||
session.
|
||||
- **Hardware scaler.** The compositor draws a panel-sized swapchain and scales on the GPU.
|
||||
`setFixedSize` to the session size, when no compositor effect is on, would hand that scale to
|
||||
the display hardware.
|
||||
- **Force fullscreen per game**, the way Quake-engine titles are handled (`cbcd3f80`), instead of a
|
||||
global switch.
|
||||
|
||||
### How runs 2 to 6 were driven
|
||||
|
||||
Two temporary session-script hooks, not kept on this branch: `BL_STEAM_MAX_HEIGHT=N` wrote
|
||||
`GAMESCOPE_STEAM_MAX_HEIGHT` on the root window, and `BL_GAME_XWAYLAND_MODE=WxH` wrote
|
||||
`GAMESCOPE_XWAYLAND_MODE_CONTROL = 1,W,H,0` five seconds after `GAMESCOPE_FOCUSED_APP` showed a
|
||||
game. `--xwayland-count 2` and `STEAM_MULTIPLE_XWAYLANDS=1` went through `Download/droiddeck-env`.
|
||||
|
||||
## Two Xwayland servers by default (`feat/steam-dual-xwayland`)
|
||||
|
||||
Steam sessions now start gamescope with `--xwayland-count 2` and `STEAM_MULTIPLE_XWAYLANDS=1`.
|
||||
`BL_XWAYLAND_COUNT=1` in `Download/droiddeck-env` goes back to one. The session script's
|
||||
root-window requests that are meant for the game (the drawer's live Force fullscreen,
|
||||
`GAMESCOPE_FORCE_WINDOWS_FULLSCREEN`, and the resume watcher's `GAMESCOPE_RESTORE_FOCUS_WINDOW`)
|
||||
go to both displays, `$DISPLAY` and `STEAM_GAME_DISPLAY_0`. gamescope reads both per server, so
|
||||
writing only to `:0` would have reached the Steam client and not the game.
|
||||
|
||||
Clipboard: gamescope copies a selection made on any of its Xwayland servers to all of them
|
||||
(`gamescope_set_selection`), so the Android text `droiddeck-clipboard` puts on `:0` reaches games
|
||||
on `:1` without changes here.
|
||||
|
||||
Device runs (Thor, no `droiddeck-env`):
|
||||
|
||||
| Run | Game | Game Resolution | Force fullscreen | Result |
|
||||
|---|---|---|---|---|
|
||||
| d1 | Alan Wake's American Nightmare | 1280x720 (set in Steam) | on | The client set `#1` to 1280x720 itself. 2 frame-size changes, `:1` steady at 10 dma-bufs, memory steady. No storm |
|
||||
| d2 | Alan Wake's American Nightmare | 1280x720 | on → off → on, live | `stretch games to fill the screen: 0 (live)` then `1`, written to both displays. Game stable |
|
||||
| d5 | 198X | default | off | The client set `#1` to native 1920x1080. Full screen, 60 fps |
|
||||
|
||||
Steam saves the per-game choice as `"ResolutionOverride2" "1280x720"` under the app in
|
||||
`userdata/<id>/config/localconfig.vdf`.
|
||||
|
||||
Checked by hand (2026-10-06, Thor, Force fullscreen off):
|
||||
- **FlatOut 2**, the game Force fullscreen was added for, does not shrink when the QAM opens over
|
||||
it and closes again. With the client's overlay on another X server, the game keeps its own X
|
||||
keyboard focus and never sees the deactivation that made it shrink.
|
||||
- Resume after the Steam menu: the resume watcher's restore request reaches both servers
|
||||
(`restore requested for focus window` logged once for the client's window and once for the
|
||||
game's).
|
||||
|
||||
Still to check by hand: pasting Android text into a game.
|
||||
|
||||
Force fullscreen is still unsafe without a matching Game Resolution: with the default (native),
|
||||
a game drawing at another size fights it as in run 4. It stays off by default.
|
||||
|
||||
## Force fullscreen removed (`feat/remove-force-fullscreen`)
|
||||
|
||||
With games on their own Xwayland server, FlatOut 2 no longer shrinks under the QAM, which was the
|
||||
reason "Force game windows fullscreen" existed. What it still did was make any game whose Game
|
||||
Resolution differs from what it draws fight it (runs 4 and 5). The switch is gone from Steam
|
||||
settings (Games) and the session drawer (Display), along with its preference, the
|
||||
`BL_GAMESCOPE_FORCE_FULLSCREEN` flag, the `~/.droiddeck-fill` live watcher and the device report
|
||||
line. `BL_GAMESCOPE_ARGS=--force-windows-fullscreen` in `Download/droiddeck-env` still passes the
|
||||
flag for an experiment.
|
||||
|
||||
Device check (Thor): Alan Wake's American Nightmare with its 1280x720 Game Resolution runs on `:1`
|
||||
at 1280x720 with no `--force-windows-fullscreen` in the session, 2 frame-size changes, no crash
|
||||
in logcat. The Games tab and the drawer render without the switch.
|
||||
@@ -3,10 +3,12 @@ import json
|
||||
import os
|
||||
import re
|
||||
import runpy
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
SYNC_KEYS = ("BL_SYNC_FALLBACK", "BL_FSYNC_FIRST", "BL_SYNC_MIN_NOFILE", "PROTON_NO_ESYNC", "PROTON_NO_FSYNC", "PROTON_NO_NTSYNC", "WINEESYNC")
|
||||
SEED_REDISTS = "/usr/local/bin/droiddeck-seed-redists"
|
||||
PACK_KEYS = ("WINESERVER", "BL_SYNC_PACK", "WINEESYNC", "PROTON_NO_ESYNC", "PROTON_NO_FSYNC")
|
||||
|
||||
|
||||
@@ -117,6 +119,21 @@ def engine_fixes(exe, args):
|
||||
return env, extra, notes
|
||||
|
||||
|
||||
def win_components(compat, app_id):
|
||||
"""The game's Windows components put into its prefix; returns their WINEDLLOVERRIDES entries."""
|
||||
if not compat:
|
||||
return ""
|
||||
try:
|
||||
module = runpy.run_path(str(Path(__file__).resolve().parent / "droiddeck-wincomponents"))
|
||||
names, notes = module["apply"](compat.rstrip("/"), app_id)
|
||||
for note in notes:
|
||||
print("droiddeck-game-env: " + note, file=sys.stderr)
|
||||
return module["overrides_value"](names)
|
||||
except Exception as error:
|
||||
print("droiddeck-game-env: Windows components not applied (%s)" % error, file=sys.stderr)
|
||||
return ""
|
||||
|
||||
|
||||
def apply_config(env, config, app_id, fixes=None):
|
||||
if config.get("version") != 1:
|
||||
raise ValueError("unsupported environment configuration")
|
||||
@@ -196,11 +213,57 @@ def without_pack(chosen_env, env):
|
||||
return result
|
||||
|
||||
|
||||
SSBS_LIB = "/usr/local/lib/libssbs.so"
|
||||
|
||||
|
||||
def force_ssbs(command, env):
|
||||
"""DROIDDECK_FORCE_SSBS=1 (a game's or the shared environment): preload libssbs.so into this
|
||||
Proton's Wine, which then keeps PSTATE.SSBS set across signal returns - speculative store
|
||||
bypass stays allowed, as force_ssbs.diff does inside a rebuilt ntdll. ARM64 Protons only: the
|
||||
library is aarch64 and only arm64 Wine has the signal path it fixes."""
|
||||
if env.get("DROIDDECK_FORCE_SSBS", "").lower() not in ("1", "on", "true", "yes"):
|
||||
return env
|
||||
proton = os.path.dirname(command[0]) if command else ""
|
||||
if not os.path.isdir(os.path.join(proton, "files/lib/wine/aarch64-unix")):
|
||||
print("droiddeck-game-env: force SSBS asked for, but this Proton is not an ARM64 one; left off", file=sys.stderr)
|
||||
return env
|
||||
if not os.path.isfile(SSBS_LIB):
|
||||
print("droiddeck-game-env: force SSBS asked for, but %s is missing; left off" % SSBS_LIB, file=sys.stderr)
|
||||
return env
|
||||
parts = [p for p in re.split(r"[:\s]+", env.get("LD_PRELOAD", "")) if p]
|
||||
if SSBS_LIB not in parts:
|
||||
env = dict(env, LD_PRELOAD=":".join(parts + [SSBS_LIB]))
|
||||
print("droiddeck-game-env: force SSBS on (libssbs.so preloaded)", file=sys.stderr)
|
||||
return env
|
||||
|
||||
|
||||
EVALUATOR_SCRIPT = re.compile(r"(?:^|[\\/])evaluatorscript_[0-9]+\.vdf$", re.IGNORECASE)
|
||||
|
||||
|
||||
def mark_install_scripts(command, env):
|
||||
"""The client is about to run a game's install scripts (iscriptevaluator.exe): mark every process
|
||||
in them as already run first, so no redistributable installer starts - on first launch the
|
||||
shared ones may still be downloading, and on ARM64 Proton the VC++ ones stop with an error."""
|
||||
if not any(arg.lower().replace("\\", "/").endswith("iscriptevaluator.exe") for arg in command):
|
||||
return
|
||||
root = env.get("STEAM_COMPAT_CLIENT_INSTALL_PATH") or str(Path.home() / ".local/share/Steam")
|
||||
scripts = [str(Path(root) / arg.replace("\\", "/")) for arg in command if EVALUATOR_SCRIPT.search(arg)]
|
||||
scripts = [path for path in scripts if os.path.isfile(path)]
|
||||
if not scripts:
|
||||
return
|
||||
try:
|
||||
subprocess.run([SEED_REDISTS, root], env=dict(env, DROIDDECK_SEED_SCRIPTS="\n".join(scripts)),
|
||||
stdout=sys.stderr, timeout=60, check=False)
|
||||
except (OSError, subprocess.SubprocessError) as error:
|
||||
print("droiddeck-game-env: install scripts not marked (%s)" % error, file=sys.stderr)
|
||||
|
||||
|
||||
def main():
|
||||
command = sys.argv[1:]
|
||||
if not command:
|
||||
return 2
|
||||
env = os.environ.copy()
|
||||
mark_install_scripts(command, env)
|
||||
app_id = game_id(env)
|
||||
if app_id:
|
||||
waiting = len(command) > 1 and command[1] == "waitforexitandrun"
|
||||
@@ -210,6 +273,10 @@ def main():
|
||||
for note in notes:
|
||||
print("droiddeck-game-env: " + note, file=sys.stderr)
|
||||
command += extra
|
||||
components = win_components(env.get("STEAM_COMPAT_DATA_PATH", ""), app_id)
|
||||
if components:
|
||||
own = fixes.get("WINEDLLOVERRIDES")
|
||||
fixes["WINEDLLOVERRIDES"] = components + ";" + own if own else components
|
||||
path = Path.home() / ".config/droiddeck/game-environment.json"
|
||||
try:
|
||||
with path.open(encoding="utf-8") as source:
|
||||
@@ -223,6 +290,7 @@ def main():
|
||||
env = apply_config(env, {"version": 1}, app_id, fixes)
|
||||
except (OSError, ValueError, TypeError, AttributeError):
|
||||
print("droiddeck-game-env: invalid configuration; using inherited environment", file=sys.stderr)
|
||||
env = force_ssbs(command, env)
|
||||
sync = load_sync()
|
||||
launch, launch_env = select_sync(command, env, sync)
|
||||
if launch[0] != command[0]:
|
||||
|
||||
@@ -21,22 +21,13 @@ ROOT = "/org/freedesktop/login1"
|
||||
INTERFACE = NAME + ".Manager"
|
||||
UPOWER = "org.freedesktop.UPower"
|
||||
UPOWER_ROOT = "/org/freedesktop/UPower"
|
||||
NATIVE_HOST_ACK_MS = 12000 # Android falls back after ten seconds; allow its freeze to finish.
|
||||
NATIVE_PREPARE_MS = 1500
|
||||
INTROSPECTION = """
|
||||
<node>
|
||||
<interface name="org.freedesktop.login1.Manager">
|
||||
<method name="Suspend"><arg type="b" direction="in"/></method>
|
||||
<method name="SuspendWithFlags"><arg type="t" direction="in"/></method>
|
||||
<method name="CanSuspend"><arg type="s" direction="out"/></method>
|
||||
<method name="Inhibit">
|
||||
<arg type="s" direction="in"/><arg type="s" direction="in"/>
|
||||
<arg type="s" direction="in"/><arg type="s" direction="in"/>
|
||||
<arg type="h" direction="out"/>
|
||||
</method>
|
||||
<method name="ListInhibitors"><arg type="a(ssssuu)" direction="out"/></method>
|
||||
<property name="BlockInhibited" type="s" access="read"/>
|
||||
<property name="DelayInhibited" type="s" access="read"/>
|
||||
<property name="InhibitDelayMaxUSec" type="t" access="read"/>
|
||||
<property name="PreparingForSleep" type="b" access="read"/>
|
||||
<signal name="PrepareForSleep"><arg type="b"/></signal>
|
||||
</interface>
|
||||
@@ -62,13 +53,7 @@ class LoginManager:
|
||||
self.native_ready = self.directory / "steam-native-ready"
|
||||
self.pending = None
|
||||
self.timeout = None
|
||||
self.inhibitors = {}
|
||||
self.next_inhibitor = 0
|
||||
self.native = False
|
||||
self.waiting = set()
|
||||
self.steam_participated = False
|
||||
self.preparation_failed = False
|
||||
self.preparation_flushed = False
|
||||
self.preparation = None
|
||||
info = Gio.DBusNodeInfo.new_for_xml(INTROSPECTION).interfaces[0]
|
||||
self.registration = bus.register_object(ROOT, info, self.method, self.property, None)
|
||||
# Steam can issue its suspend command through the legacy UPower service even
|
||||
@@ -81,13 +66,6 @@ class LoginManager:
|
||||
def property(self, connection, sender, path, interface, name):
|
||||
if name == "PreparingForSleep":
|
||||
return GLib.Variant("b", self.pending is not None)
|
||||
if name == "InhibitDelayMaxUSec":
|
||||
return GLib.Variant("t", 10000000)
|
||||
if name in ("BlockInhibited", "DelayInhibited"):
|
||||
mode = "block" if name == "BlockInhibited" else "delay"
|
||||
kinds = {kind for item in self.inhibitors.values() if item[3] == mode
|
||||
for kind in item[0].split(":")}
|
||||
return GLib.Variant("s", ":".join(sorted(kinds)))
|
||||
return None
|
||||
|
||||
def notify(self, sleeping):
|
||||
@@ -101,10 +79,6 @@ class LoginManager:
|
||||
def method(self, connection, sender, path, interface, name, args, reply):
|
||||
if name == "CanSuspend":
|
||||
reply.return_value(GLib.Variant("(s)", ("yes",)))
|
||||
elif name == "Inhibit":
|
||||
self.inhibit(sender, args.unpack(), reply)
|
||||
elif name == "ListInhibitors":
|
||||
reply.return_value(GLib.Variant("(a(ssssuu))", ([item[:6] for item in self.inhibitors.values()],)))
|
||||
elif name in ("Suspend", "SuspendWithFlags"):
|
||||
if self.pending:
|
||||
reply.return_dbus_error(NAME + ".OperationInProgress", "The session is already pausing")
|
||||
@@ -116,57 +90,6 @@ class LoginManager:
|
||||
# on the wire, publishing the request lets the host safely freeze this service.
|
||||
self.bus.flush(None, self.publish_after_flush, self.pending)
|
||||
|
||||
def peer(self, sender, method, signature):
|
||||
return self.bus.call_sync("org.freedesktop.DBus", "/org/freedesktop/DBus",
|
||||
"org.freedesktop.DBus", method, GLib.Variant("(s)", (sender,)),
|
||||
GLib.VariantType.new(signature), Gio.DBusCallFlags.NONE, 2000, None).unpack()[0]
|
||||
|
||||
def inhibit(self, sender, args, reply):
|
||||
what, who, why, mode = args
|
||||
kinds = set(what.split(":"))
|
||||
valid = {"sleep", "shutdown", "idle", "handle-power-key", "handle-suspend-key",
|
||||
"handle-hibernate-key", "handle-lid-switch"}
|
||||
if mode not in ("block", "delay") or not kinds <= valid or (mode == "delay" and not kinds <= {"sleep", "shutdown"}):
|
||||
reply.return_dbus_error("org.freedesktop.DBus.Error.InvalidArgs", "Invalid inhibitor type or mode")
|
||||
return
|
||||
try:
|
||||
uid = self.peer(sender, "GetConnectionUnixUser", "(u)")
|
||||
pid = self.peer(sender, "GetConnectionUnixProcessID", "(u)")
|
||||
read_fd, write_fd = os.pipe2(os.O_NONBLOCK | os.O_CLOEXEC)
|
||||
descriptors = Gio.UnixFDList.new()
|
||||
try:
|
||||
index = descriptors.append(write_fd)
|
||||
finally:
|
||||
os.close(write_fd)
|
||||
self.next_inhibitor += 1
|
||||
key = self.next_inhibitor
|
||||
self.inhibitors[key] = (what, who, why, mode, uid, pid, sender, read_fd)
|
||||
GLib.io_add_watch(read_fd, GLib.IOCondition.HUP | GLib.IOCondition.ERR,
|
||||
self.release_inhibitor, key)
|
||||
if self.native and mode == "delay" and "sleep" in kinds:
|
||||
self.waiting.add(key)
|
||||
self.steam_participated |= who.lower() == "steam"
|
||||
reply.return_value_with_unix_fd_list(GLib.Variant("(h)", (index,)), descriptors)
|
||||
print("== login1: inhibitor acquired: " + who + " " + what + " " + mode, flush=True)
|
||||
except (GLib.Error, OSError) as error:
|
||||
reply.return_dbus_error(NAME + ".Failed", str(error))
|
||||
|
||||
def release_inhibitor(self, fd, condition, key):
|
||||
item = self.inhibitors.pop(key)
|
||||
os.close(fd)
|
||||
print("== login1: inhibitor released: " + item[1], flush=True)
|
||||
if key in self.waiting:
|
||||
self.waiting.remove(key)
|
||||
# A disconnected/crashed client is not a preparation acknowledgement.
|
||||
try:
|
||||
alive = self.peer(item[6], "NameHasOwner", "(b)")
|
||||
os.kill(item[5], 0)
|
||||
except (GLib.Error, OSError):
|
||||
alive = False
|
||||
self.preparation_failed |= not alive
|
||||
self.finish_preparation()
|
||||
return False
|
||||
|
||||
def publish_after_flush(self, connection, result, token):
|
||||
try:
|
||||
connection.flush_finish(result)
|
||||
@@ -185,8 +108,6 @@ class LoginManager:
|
||||
staged = request.with_suffix(".tmp")
|
||||
staged.write_text(self.pending + "\n")
|
||||
staged.replace(request)
|
||||
if self.timeout is not None:
|
||||
GLib.source_remove(self.timeout)
|
||||
self.timeout = GLib.timeout_add_seconds(5, self.check_ack)
|
||||
except OSError as error:
|
||||
print("== login1: cannot request pause: " + str(error), file=sys.stderr)
|
||||
@@ -205,13 +126,6 @@ class LoginManager:
|
||||
if self.read_state() == token + ":awake":
|
||||
return
|
||||
self.pending = token
|
||||
self.native = True
|
||||
self.waiting = {key for key, item in self.inhibitors.items()
|
||||
if item[3] == "delay" and "sleep" in item[0].split(":")}
|
||||
self.steam_participated = any(self.inhibitors[key][1].lower() == "steam" for key in self.waiting)
|
||||
self.preparation_failed = False
|
||||
self.preparation_flushed = False
|
||||
self.timeout = GLib.timeout_add(NATIVE_HOST_ACK_MS, self.check_ack)
|
||||
self.notify(True)
|
||||
self.bus.flush(None, self.prepare_after_flush, token)
|
||||
|
||||
@@ -224,15 +138,13 @@ class LoginManager:
|
||||
return
|
||||
self.check_state()
|
||||
if self.pending == token:
|
||||
self.preparation_flushed = True
|
||||
self.finish_preparation()
|
||||
# Keep Steam runnable while it handles the system sleep notification.
|
||||
# This is a bounded grace period, not a claim that every game has saved.
|
||||
self.preparation = GLib.timeout_add(NATIVE_PREPARE_MS, self.finish_preparation, token)
|
||||
|
||||
def finish_preparation(self):
|
||||
self.check_state()
|
||||
if (self.native and self.pending and self.preparation_flushed and self.steam_participated
|
||||
and not self.waiting and not self.preparation_failed):
|
||||
self.native = False
|
||||
print("== login1: Steam acknowledged sleep preparation", flush=True)
|
||||
def finish_preparation(self, token):
|
||||
self.preparation = None
|
||||
if self.pending == token:
|
||||
self.publish(self.native_ready)
|
||||
return False
|
||||
|
||||
@@ -274,8 +186,9 @@ class LoginManager:
|
||||
self.bus.flush(None, self.finish_recovery, None)
|
||||
return
|
||||
self.pending = None
|
||||
self.native = False
|
||||
self.waiting.clear()
|
||||
if self.preparation is not None:
|
||||
GLib.source_remove(self.preparation)
|
||||
self.preparation = None
|
||||
if self.timeout is not None:
|
||||
GLib.source_remove(self.timeout)
|
||||
self.timeout = None
|
||||
|
||||
+771
@@ -0,0 +1,771 @@
|
||||
#!/usr/bin/python3
|
||||
"""Installs a Windows Installer package (.msi) the way Wine's own msiexec would, without running it.
|
||||
|
||||
droiddeck-msi-install <package.msi> <component dir>
|
||||
|
||||
A .msi is a database: which files go to which folder, which registry values to write, which .NET
|
||||
and side-by-side assemblies to register. This reads those tables (msiinfo), unpacks the package's
|
||||
cabinets (cabextract, which knows every compression a cabinet can use) and lays the result out
|
||||
for droiddeck-wincomponents, which puts it into a game's prefix at launch:
|
||||
|
||||
<component dir>/drive_c/... the files, at the paths they get on 64-bit Windows
|
||||
<component dir>/registry.json the registry values, in the view (32/64-bit) Windows uses
|
||||
|
||||
What a package does by running its own code (custom actions such as DXSETUP, self-registering
|
||||
DLLs) cannot be done this way; each is named in the notes, so nothing is left out silently.
|
||||
|
||||
Prints "progress <text>" lines while it works and ends with "result <json>": the counts and notes.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
TOOLS = Path(os.environ.get("DROIDDECK_MSITOOLS", "/usr/local/lib/droiddeck-msitools"))
|
||||
MSIINFO = os.environ.get("DROIDDECK_MSIINFO", str(TOOLS / "msiinfo"))
|
||||
CABEXTRACT = os.environ.get("DROIDDECK_CABEXTRACT", str(TOOLS / "cabextract"))
|
||||
|
||||
|
||||
def tool_env():
|
||||
"""The environment the tools run in: their own libraries (libmsi, libgsf, libgcab) beside them."""
|
||||
env = dict(os.environ)
|
||||
env["LD_LIBRARY_PATH"] = ":".join(p for p in (str(TOOLS), env.get("LD_LIBRARY_PATH", "")) if p)
|
||||
return env
|
||||
|
||||
# The folders Windows Installer knows by name, as a 64-bit Windows 10 prefix lays them out (Proton's
|
||||
# user is steamuser). None is a folder whose files a game never needs: installer temp files and
|
||||
# shortcuts.
|
||||
SKIP = None
|
||||
KNOWN_FOLDERS = {
|
||||
"TARGETDIR": "C:\\", "ROOTDRIVE": "C:\\", "WindowsVolume": "C:\\",
|
||||
"WindowsFolder": "C:\\windows\\",
|
||||
"SystemFolder": "C:\\windows\\syswow64\\",
|
||||
"System64Folder": "C:\\windows\\system32\\",
|
||||
"System16Folder": "C:\\windows\\system\\",
|
||||
"FontsFolder": "C:\\windows\\Fonts\\",
|
||||
"ProgramFilesFolder": "C:\\Program Files (x86)\\",
|
||||
"ProgramFiles64Folder": "C:\\Program Files\\",
|
||||
"CommonFilesFolder": "C:\\Program Files (x86)\\Common Files\\",
|
||||
"CommonFiles64Folder": "C:\\Program Files\\Common Files\\",
|
||||
"CommonAppDataFolder": "C:\\ProgramData\\",
|
||||
"AppDataFolder": "C:\\users\\steamuser\\AppData\\Roaming\\",
|
||||
"LocalAppDataFolder": "C:\\users\\steamuser\\AppData\\Local\\",
|
||||
"PersonalFolder": "C:\\users\\steamuser\\Documents\\",
|
||||
}
|
||||
for _name in ("TempFolder", "DesktopFolder", "ProgramMenuFolder", "StartMenuFolder", "StartupFolder",
|
||||
"SendToFolder", "FavoritesFolder", "NetHoodFolder", "PrintHoodFolder", "RecentFolder",
|
||||
"TemplateFolder", "MyPicturesFolder", "AdminToolsFolder"):
|
||||
KNOWN_FOLDERS[_name] = SKIP
|
||||
|
||||
# What Wine's msi reports on a 64-bit Windows 10 prefix, for the packages' conditions.
|
||||
SYSTEM_PROPERTIES = {
|
||||
"VersionNT": "603", "VersionNT64": "603", "WindowsBuild": "9600", "ServicePackLevel": "0",
|
||||
"Msix64": "6", "ALLUSERS": "1", "Privileged": "1", "AdminUser": "1", "MsiNTProductType": "1",
|
||||
"UILevel": "2", "INSTALLLEVEL": "1", "ProgramFilesFolder": None, "VersionMsi": "5.00",
|
||||
}
|
||||
|
||||
# Win64 component (msidbComponentAttributes64bit); file attributes.
|
||||
COMPONENT_64BIT = 0x100
|
||||
FILE_NONCOMPRESSED = 0x2000
|
||||
# Custom action types that only set a property or a folder: done here, the rest are named in notes.
|
||||
SET_PROPERTY, SET_DIRECTORY, ERROR_ACTION = 51, 35, 19
|
||||
# Microsoft's "SFP CA" merge module (MDAC, MSXML): on Windows 2000 and later it parks system DLLs in a
|
||||
# cache folder and its own code copies them into the system folder past Windows File Protection.
|
||||
# Skipping the folder change puts them where that copy would. Its actions, and the side-by-side
|
||||
# merge module's (done here from MsiAssembly), are then left out of the notes.
|
||||
SFP_CACHE_ACTION = "CDirSystemSFPCacheDir"
|
||||
HANDLED_ACTIONS = ("Wdsfpca_", "SxsInstallCA", "SxsUninstallCA")
|
||||
# Tables whose work needs the package's own code or is not done here yet.
|
||||
UNSUPPORTED_TABLES = ("SelfReg", "Class", "ProgId", "TypeLib", "Extension", "Verb", "MIME", "AppId",
|
||||
"IniFile", "ServiceInstall", "MoveFile", "IsolatedComponent", "PublishComponent",
|
||||
"ODBCDriver", "ODBCDataSource")
|
||||
|
||||
|
||||
class MsiError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def progress(text):
|
||||
print("progress " + text, flush=True)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- reading the package
|
||||
|
||||
IDT_ESCAPES = str.maketrans({"\x19": "\n", "\x11": "\r", "\x15": "\t", "\x1b": ";"})
|
||||
|
||||
|
||||
def msiinfo(*args, binary=False):
|
||||
try:
|
||||
result = subprocess.run([MSIINFO, *args], capture_output=True, timeout=600, env=tool_env())
|
||||
except OSError as error:
|
||||
raise MsiError("msitools is not available (%s)" % error)
|
||||
if result.returncode != 0:
|
||||
raise MsiError("msiinfo %s: %s" % (args[0], result.stderr.decode("utf-8", "replace").strip()[:300]))
|
||||
return result.stdout if binary else result.stdout.decode("utf-8", "replace")
|
||||
|
||||
|
||||
class Package:
|
||||
def __init__(self, path):
|
||||
self.path = str(path)
|
||||
self.table_names = set(msiinfo("tables", self.path).split())
|
||||
self._tables = {}
|
||||
self.summary = {}
|
||||
for line in msiinfo("suminfo", self.path).splitlines():
|
||||
name, sep, value = line.partition(":")
|
||||
if sep:
|
||||
self.summary[name.strip().lower()] = value.strip()
|
||||
|
||||
def table(self, name):
|
||||
"""The table's rows as dicts by column name; an absent table has none."""
|
||||
if name in self._tables:
|
||||
return self._tables[name]
|
||||
rows = []
|
||||
if name in self.table_names:
|
||||
lines = [line.rstrip("\r") for line in msiinfo("export", self.path, name).split("\n")]
|
||||
columns = lines[0].split("\t") if lines else []
|
||||
for line in lines[3:]:
|
||||
if not line:
|
||||
continue
|
||||
cells = [cell.translate(IDT_ESCAPES) for cell in line.split("\t")]
|
||||
cells += [""] * (len(columns) - len(cells))
|
||||
rows.append(dict(zip(columns, cells)))
|
||||
self._tables[name] = rows
|
||||
return rows
|
||||
|
||||
def stream(self, name, target):
|
||||
Path(target).write_bytes(msiinfo("extract", self.path, name, binary=True))
|
||||
|
||||
|
||||
def long_name(value):
|
||||
"""A Directory/File name column: "short|long", the long one when there are two."""
|
||||
return value.split("|")[-1]
|
||||
|
||||
|
||||
def to_int(value, default=0):
|
||||
try:
|
||||
return int(str(value).strip())
|
||||
except ValueError:
|
||||
return default
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- conditions
|
||||
|
||||
TOKEN = re.compile(r'\s*(?:(?P<str>"[^"]*")|(?P<num>-?\d+)(?![\w.])|(?P<op>~?(?:<>|<=|>=|><|<<|>>|=|<|>))'
|
||||
r'|(?P<paren>[()])|(?P<word>[%$?&!]?[A-Za-z_][\w.]*))')
|
||||
KEYWORDS = {"not", "and", "or", "xor", "eqv", "imp"}
|
||||
|
||||
|
||||
class Conditions:
|
||||
"""Windows Installer's condition language, enough of it for what packages ask at install time."""
|
||||
|
||||
def __init__(self, props, feature_state=None, component_state=None):
|
||||
self.props = props
|
||||
self.feature_state = feature_state or (lambda name: None)
|
||||
self.component_state = component_state or (lambda name: None)
|
||||
|
||||
def evaluate(self, text, default=True):
|
||||
text = (text or "").strip()
|
||||
if not text:
|
||||
return True
|
||||
try:
|
||||
self.tokens = self.tokenize(text)
|
||||
self.pos = 0
|
||||
value = self.expression()
|
||||
if self.pos != len(self.tokens):
|
||||
return default
|
||||
return self.truth(value)
|
||||
except (ValueError, IndexError):
|
||||
return default
|
||||
|
||||
def tokenize(self, text):
|
||||
tokens, pos = [], 0
|
||||
while pos < len(text):
|
||||
if text[pos:].strip() == "":
|
||||
break
|
||||
match = TOKEN.match(text, pos)
|
||||
if not match or match.end() == pos:
|
||||
raise ValueError(text)
|
||||
pos = match.end()
|
||||
kind = match.lastgroup
|
||||
value = match.group(kind)
|
||||
if kind == "word" and value.lower() in KEYWORDS:
|
||||
tokens.append(("kw", value.lower()))
|
||||
else:
|
||||
tokens.append((kind, value))
|
||||
return tokens
|
||||
|
||||
def peek(self):
|
||||
return self.tokens[self.pos] if self.pos < len(self.tokens) else (None, None)
|
||||
|
||||
def take(self, kind, value=None):
|
||||
token = self.peek()
|
||||
if token[0] == kind and (value is None or token[1] == value):
|
||||
self.pos += 1
|
||||
return True
|
||||
return False
|
||||
|
||||
def expression(self):
|
||||
value = self.binary(0)
|
||||
return value
|
||||
|
||||
LEVELS = ("imp", "eqv", "xor", "or", "and")
|
||||
|
||||
def binary(self, level):
|
||||
if level == len(self.LEVELS):
|
||||
return self.negation()
|
||||
left = self.binary(level + 1)
|
||||
op = self.LEVELS[level]
|
||||
while self.take("kw", op):
|
||||
right = self.truth(self.binary(level + 1))
|
||||
a = self.truth(left)
|
||||
left = {"and": a and right, "or": a or right, "xor": a != right,
|
||||
"eqv": a == right, "imp": (not a) or right}[op]
|
||||
return left
|
||||
|
||||
def negation(self):
|
||||
if self.take("kw", "not"):
|
||||
return not self.truth(self.negation())
|
||||
return self.comparison()
|
||||
|
||||
def comparison(self):
|
||||
left = self.operand()
|
||||
kind, op = self.peek()
|
||||
if kind != "op":
|
||||
return left
|
||||
self.pos += 1
|
||||
right = self.operand()
|
||||
return self.compare(left, op, right)
|
||||
|
||||
def operand(self):
|
||||
kind, value = self.peek()
|
||||
self.pos += 1
|
||||
if kind == "paren" and value == "(":
|
||||
inner = self.expression()
|
||||
if not self.take("paren", ")"):
|
||||
raise ValueError("unbalanced")
|
||||
return inner
|
||||
if kind == "str":
|
||||
return value[1:-1]
|
||||
if kind == "num":
|
||||
return int(value)
|
||||
if kind == "word":
|
||||
sigil, name = (value[0], value[1:]) if value[0] in "%$?&!" else ("", value)
|
||||
if sigil == "%":
|
||||
return os.environ.get(name, "")
|
||||
if sigil in ("&", "!"):
|
||||
state = self.feature_state(name)
|
||||
return state if state is not None else -1
|
||||
if sigil in ("$", "?"):
|
||||
state = self.component_state(name)
|
||||
return state if state is not None else -1
|
||||
found = self.props.get(name)
|
||||
return "" if found is None else found
|
||||
raise ValueError("operand expected")
|
||||
|
||||
@staticmethod
|
||||
def number(value):
|
||||
if isinstance(value, bool):
|
||||
return int(value)
|
||||
if isinstance(value, int):
|
||||
return value
|
||||
if isinstance(value, str) and re.fullmatch(r"-?\d+", value.strip()):
|
||||
return int(value)
|
||||
return None
|
||||
|
||||
def compare(self, left, op, right):
|
||||
fold = op.startswith("~")
|
||||
op = op.lstrip("~")
|
||||
a, b = self.number(left), self.number(right)
|
||||
if a is not None and b is not None:
|
||||
return {"=": a == b, "<>": a != b, "<": a < b, ">": a > b, "<=": a <= b, ">=": a >= b,
|
||||
"><": (a & b) != 0, "<<": (a >> 16) == b, ">>": (a & 0xFFFF) == b}[op]
|
||||
if isinstance(left, (int, bool)) or isinstance(right, (int, bool)):
|
||||
return op == "<>"
|
||||
a, b = str(left), str(right)
|
||||
if fold:
|
||||
a, b = a.lower(), b.lower()
|
||||
return {"=": a == b, "<>": a != b, "<": a < b, ">": a > b, "<=": a <= b, ">=": a >= b,
|
||||
"><": b in a, "<<": a.startswith(b), ">>": a.endswith(b)}[op]
|
||||
|
||||
@staticmethod
|
||||
def truth(value):
|
||||
if isinstance(value, bool):
|
||||
return value
|
||||
if isinstance(value, int):
|
||||
return value != 0
|
||||
return value not in ("", None)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- the install
|
||||
|
||||
def win_to_rel(path):
|
||||
"""C:\\windows\\x\\ -> drive_c/windows/x; None for a path off drive C or a folder left out."""
|
||||
if not path:
|
||||
return None
|
||||
match = re.match(r"^[Cc]:\\?(.*)$", path)
|
||||
if not match:
|
||||
return None
|
||||
rest = [part for part in match.group(1).replace("/", "\\").split("\\") if part not in ("", ".")]
|
||||
if any(part == ".." for part in rest):
|
||||
return None
|
||||
return "/".join(["drive_c"] + rest)
|
||||
|
||||
|
||||
def rel_to_win(rel, folder=True):
|
||||
parts = rel.split("/")[1:]
|
||||
return "C:\\" + "\\".join(parts) + ("\\" if folder and parts else "")
|
||||
|
||||
|
||||
def clean_version(version):
|
||||
parts = [str(to_int(p)) for p in version.split(".") if p != ""]
|
||||
return ".".join(parts) if parts else "0.0.0.0"
|
||||
|
||||
|
||||
def clr_version(path):
|
||||
"""The .NET runtime an assembly was built for ("v4.0.30319"), from its metadata header."""
|
||||
try:
|
||||
data = Path(path).read_bytes()
|
||||
except OSError:
|
||||
return ""
|
||||
at = data.find(b"BSJB")
|
||||
if at < 0 or at + 16 > len(data):
|
||||
return ""
|
||||
length = int.from_bytes(data[at + 12:at + 16], "little")
|
||||
return data[at + 16:at + 16 + min(length, 32)].split(b"\0")[0].decode("ascii", "replace")
|
||||
|
||||
|
||||
class Installer:
|
||||
def __init__(self, msi, out, package=None):
|
||||
self.pkg = package or Package(msi)
|
||||
self.out = Path(out)
|
||||
self.notes = []
|
||||
self.registry = []
|
||||
self.files = {} # File key -> rel path it was installed to
|
||||
self.counts = {"files": 0, "assemblies": 0, "registry": 0}
|
||||
template = self.pkg.summary.get("template", "")
|
||||
self.platform = template.split(";")[0].strip().lower()
|
||||
self.props = {k: v for k, v in SYSTEM_PROPERTIES.items() if v is not None}
|
||||
if self.platform in ("", "intel"):
|
||||
self.props["Intel"] = "6"
|
||||
for name, path in KNOWN_FOLDERS.items():
|
||||
self.props[name] = path if path is not None else "\0skip"
|
||||
for row in self.pkg.table("Property"):
|
||||
# The package's own defaults, but never over the folders and the system it runs on.
|
||||
if row["Property"] not in self.props or row["Property"] in ("INSTALLLEVEL", "ALLUSERS", "UILevel"):
|
||||
self.props[row["Property"]] = row["Value"]
|
||||
self.props["ALLUSERS"] = "1"
|
||||
self.directories = {row["Directory"]: row for row in self.pkg.table("Directory")}
|
||||
self.components = {row["Component"]: row for row in self.pkg.table("Component")}
|
||||
self.included_features = set()
|
||||
self.included_components = set()
|
||||
self.conditions = Conditions(self.props, self.feature_state, self.component_state)
|
||||
self._resolving = set()
|
||||
self._set_by_action = set()
|
||||
|
||||
# -- states, folders, formatted text
|
||||
|
||||
def feature_state(self, name):
|
||||
return 3 if name in self.included_features else -1
|
||||
|
||||
def component_state(self, name):
|
||||
return 3 if name in self.included_components else -1
|
||||
|
||||
def directory(self, key):
|
||||
"""The folder a Directory key resolves to, as drive_c/..., or None when it is left out."""
|
||||
if key in self._resolving:
|
||||
return None
|
||||
value = self.props.get(key)
|
||||
row = self.directories.get(key)
|
||||
# A folder Windows knows by name, one a custom action set, or a property naming a path.
|
||||
if key in KNOWN_FOLDERS or key in self._set_by_action or row is None:
|
||||
return None if value in (None, "", "\0skip") else win_to_rel(value)
|
||||
parent_key = row.get("Directory_Parent", "")
|
||||
default = long_name(row.get("DefaultDir", "").split(":")[0])
|
||||
if not parent_key or parent_key == key:
|
||||
# A root: TARGETDIR (SourceDir) is drive C.
|
||||
return "drive_c"
|
||||
self._resolving.add(key)
|
||||
try:
|
||||
parent = self.directory(parent_key)
|
||||
finally:
|
||||
self._resolving.discard(key)
|
||||
if parent is None:
|
||||
return None
|
||||
if default in (".", ""):
|
||||
return parent
|
||||
if "\\" in default or "/" in default or default == "..":
|
||||
return None
|
||||
return parent + "/" + default
|
||||
|
||||
def format(self, text):
|
||||
"""Formatted text: [Property], [Folder], [#file], [$component], [%env], [\\x], [~]."""
|
||||
if not text:
|
||||
return text
|
||||
|
||||
def one(match):
|
||||
inner = match.group(1)
|
||||
if inner.startswith("\\") and len(inner) == 2:
|
||||
return inner[1]
|
||||
if inner == "~":
|
||||
return "\0"
|
||||
if inner.startswith("#") or inner.startswith("!"):
|
||||
rel = self.files.get(inner[1:])
|
||||
return rel_to_win(rel, folder=False) if rel else ""
|
||||
if inner.startswith("$"):
|
||||
comp = self.components.get(inner[1:])
|
||||
rel = self.directory(comp["Directory_"]) if comp else None
|
||||
return rel_to_win(rel) if rel else ""
|
||||
if inner.startswith("%"):
|
||||
return os.environ.get(inner[1:], "")
|
||||
if inner in self.directories or inner in KNOWN_FOLDERS:
|
||||
rel = self.directory(inner)
|
||||
return rel_to_win(rel) if rel else ""
|
||||
value = self.props.get(inner, "")
|
||||
return "" if value == "\0skip" else value
|
||||
|
||||
previous = None
|
||||
for _ in range(8):
|
||||
if text == previous:
|
||||
break
|
||||
previous = text
|
||||
text = re.sub(r"\[([^\[\]]*)\]", one, text)
|
||||
return text
|
||||
|
||||
# -- what gets installed
|
||||
|
||||
def run_set_actions(self):
|
||||
"""The property/folder-setting custom actions, in sequence order; the rest go to the notes."""
|
||||
actions = {row["Action"]: row for row in self.pkg.table("CustomAction")}
|
||||
sequence = {}
|
||||
for table in ("InstallUISequence", "InstallExecuteSequence"):
|
||||
for row in self.pkg.table(table):
|
||||
if row["Action"] in actions and row["Action"] not in sequence:
|
||||
sequence[row["Action"]] = (to_int(row.get("Sequence"), 0), row.get("Condition", ""))
|
||||
skipped = []
|
||||
sfp = "_SfpCaInf" in self.pkg.table_names
|
||||
for name, (_, condition) in sorted(sequence.items(), key=lambda item: item[1][0]):
|
||||
row = actions[name]
|
||||
kind = to_int(row["Type"]) & 0x3F
|
||||
if name.startswith(HANDLED_ACTIONS) or (sfp and name.startswith(SFP_CACHE_ACTION)):
|
||||
continue
|
||||
if kind in (SET_PROPERTY, SET_DIRECTORY):
|
||||
if not self.conditions.evaluate(condition, default=True):
|
||||
continue
|
||||
value = self.format(row.get("Target", ""))
|
||||
self.props[row["Source"]] = value
|
||||
self._set_by_action.add(row["Source"])
|
||||
elif kind != ERROR_ACTION and self.conditions.evaluate(condition, default=True):
|
||||
skipped.append(name)
|
||||
if skipped:
|
||||
self.notes.append("setup actions not run (they need the installer's own code): " + ", ".join(skipped[:8])
|
||||
+ (" and %d more" % (len(skipped) - 8) if len(skipped) > 8 else ""))
|
||||
|
||||
def select(self):
|
||||
install_level = to_int(self.props.get("INSTALLLEVEL"), 1) or 1
|
||||
features = {row["Feature"]: dict(row) for row in self.pkg.table("Feature")}
|
||||
for row in self.pkg.table("Condition"):
|
||||
feature = features.get(row["Feature_"])
|
||||
if feature is not None and self.conditions.evaluate(row["Condition"], default=False):
|
||||
feature["Level"] = row["Level"]
|
||||
|
||||
def included(name, depth=0):
|
||||
feature = features.get(name)
|
||||
if feature is None or depth > 32:
|
||||
return False
|
||||
level = to_int(feature.get("Level"), 0)
|
||||
if level <= 0 or level > install_level:
|
||||
return False
|
||||
parent = feature.get("Feature_Parent", "")
|
||||
return not parent or parent == name or included(parent, depth + 1)
|
||||
|
||||
self.included_features = {name for name in features if included(name)}
|
||||
mapped = {}
|
||||
for row in self.pkg.table("FeatureComponents"):
|
||||
mapped.setdefault(row["Component_"], set()).add(row["Feature_"])
|
||||
for name, row in self.components.items():
|
||||
owners = mapped.get(name)
|
||||
if owners is not None and not owners & self.included_features:
|
||||
continue
|
||||
if not self.conditions.evaluate(row.get("Condition", ""), default=True):
|
||||
continue
|
||||
self.included_components.add(name)
|
||||
|
||||
def assemblies(self):
|
||||
"""Component -> where its files go when it is a global assembly (the GAC or winsxs)."""
|
||||
names = {}
|
||||
for row in self.pkg.table("MsiAssemblyName"):
|
||||
names.setdefault(row["Component_"], {})[row["Name"].lower()] = row["Value"]
|
||||
placed = {}
|
||||
for row in self.pkg.table("MsiAssembly"):
|
||||
comp = row["Component_"]
|
||||
if comp not in self.included_components or row.get("File_Application"):
|
||||
continue
|
||||
ident = names.get(comp, {})
|
||||
placed[comp] = (to_int(row.get("Attributes"), 0), ident, row.get("File_Manifest", ""))
|
||||
return placed
|
||||
|
||||
def gac_folder(self, ident, assembly_file):
|
||||
name = ident.get("name", "")
|
||||
token = ident.get("publickeytoken", "").lower()
|
||||
if not name or not token or "/" in name or "\\" in name:
|
||||
return None
|
||||
version = clean_version(ident.get("version", "0.0.0.0"))
|
||||
culture = ident.get("culture", "neutral")
|
||||
culture = "" if culture.lower() == "neutral" else culture
|
||||
arch = ident.get("processorarchitecture", "").lower()
|
||||
gac = {"x86": "GAC_32", "amd64": "GAC_64", "x64": "GAC_64", "msil": "GAC_MSIL"}.get(arch, "GAC_MSIL" if arch else "GAC")
|
||||
if clr_version(assembly_file).startswith("v4"):
|
||||
return "drive_c/windows/Microsoft.NET/assembly/%s/%s/v4.0_%s_%s_%s" % (gac, name, version, culture, token)
|
||||
return "drive_c/windows/assembly/%s/%s/%s_%s_%s" % (gac, name, version, culture, token)
|
||||
|
||||
@staticmethod
|
||||
def sxs_names(ident):
|
||||
"""Wine's winsxs names for a side-by-side assembly: its folder and, for a policy, the policy folder."""
|
||||
arch = ident.get("processorarchitecture", "x86").lower() or "x86"
|
||||
name = ident.get("name", "").lower()
|
||||
token = ident.get("publickeytoken", "").lower()
|
||||
version = ident.get("version", "")
|
||||
if not name or not token or not version or "/" in name or "\\" in name:
|
||||
return None
|
||||
if ident.get("type", "").lower() == "win32-policy":
|
||||
target = re.sub(r"^policy\.\d+\.\d+\.", "", name)
|
||||
return "policy", "drive_c/windows/winsxs/policies/%s_%s_%s_none_deadbeef" % (arch, target, token), version
|
||||
return "assembly", "%s_%s_%s_%s_none_deadbeef" % (arch, name, token, version), version
|
||||
|
||||
def unpack(self, work):
|
||||
"""Every cabinet in the package, unpacked; returns File key -> unpacked file."""
|
||||
found = {}
|
||||
for index, row in enumerate(self.pkg.table("Media")):
|
||||
cabinet = row.get("Cabinet", "")
|
||||
if not cabinet:
|
||||
continue
|
||||
if not cabinet.startswith("#"):
|
||||
self.notes.append("external cabinet %s is not part of the package; its files are missing" % cabinet)
|
||||
continue
|
||||
progress("unpacking %s" % cabinet[1:])
|
||||
cab = Path(work) / ("media%d.cab" % index)
|
||||
self.pkg.stream(cabinet[1:], cab)
|
||||
dest = Path(work) / ("media%d" % index)
|
||||
dest.mkdir()
|
||||
result = subprocess.run([CABEXTRACT, "-q", "-d", str(dest), str(cab)], capture_output=True, timeout=1800,
|
||||
env=tool_env())
|
||||
if result.returncode != 0:
|
||||
raise MsiError("cabextract: %s" % result.stderr.decode("utf-8", "replace").strip()[:300])
|
||||
cab.unlink()
|
||||
for entry in dest.rglob("*"):
|
||||
if entry.is_file():
|
||||
found.setdefault(entry.relative_to(dest).as_posix(), entry)
|
||||
return found
|
||||
|
||||
def put(self, source, rel):
|
||||
target = self.out / rel
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copyfile(source, target)
|
||||
|
||||
def install_files(self, unpacked):
|
||||
assemblies = self.assemblies()
|
||||
files = self.pkg.table("File")
|
||||
missing = 0
|
||||
destinations = {}
|
||||
# Where each file goes: its component's folder, or the assembly store for a global assembly.
|
||||
for row in files:
|
||||
comp = row["Component_"]
|
||||
if comp not in self.included_components:
|
||||
continue
|
||||
name = long_name(row["FileName"])
|
||||
if not name or "/" in name or "\\" in name or name in (".", ".."):
|
||||
continue
|
||||
if comp in assemblies:
|
||||
kind, ident, manifest = assemblies[comp]
|
||||
if kind == 0:
|
||||
source = unpacked.get(self.components[comp].get("KeyPath", ""))
|
||||
folder = self.gac_folder(ident, source) if source else None
|
||||
destinations[row["File"]] = folder + "/" + name if folder else None
|
||||
else:
|
||||
names = self.sxs_names(ident)
|
||||
if names is None:
|
||||
destinations[row["File"]] = None
|
||||
elif names[0] == "policy":
|
||||
destinations[row["File"]] = (names[1] + "/" + names[2] + ".policy") if row["File"] == manifest else None
|
||||
elif row["File"] == manifest:
|
||||
destinations[row["File"]] = "drive_c/windows/winsxs/manifests/%s.manifest" % names[1]
|
||||
elif name.lower().endswith(".cat"):
|
||||
destinations[row["File"]] = None
|
||||
else:
|
||||
destinations[row["File"]] = "drive_c/windows/winsxs/%s/%s" % (names[1], name)
|
||||
continue
|
||||
folder = self.directory(self.components[comp]["Directory_"])
|
||||
destinations[row["File"]] = folder + "/" + name if folder else None
|
||||
for key, rel in destinations.items():
|
||||
if rel:
|
||||
self.files[key] = rel
|
||||
assembly_folders = set()
|
||||
for key, rel in destinations.items():
|
||||
if not rel:
|
||||
continue
|
||||
source = unpacked.get(key)
|
||||
if source is None:
|
||||
missing += 1
|
||||
continue
|
||||
self.put(source, rel)
|
||||
self.counts["files"] += 1
|
||||
if "/assembly/" in rel or "/winsxs/" in rel:
|
||||
assembly_folders.add(rel.rsplit("/", 1)[0])
|
||||
self.counts["assemblies"] = len(assembly_folders)
|
||||
for row in self.pkg.table("DuplicateFile"):
|
||||
if row["Component_"] not in self.included_components or row["File_"] not in self.files:
|
||||
continue
|
||||
folder = self.directory(row["DestFolder"]) if row.get("DestFolder") else self.files[row["File_"]].rsplit("/", 1)[0]
|
||||
name = long_name(row.get("DestName", "")) or self.files[row["File_"]].rsplit("/", 1)[1]
|
||||
source = self.out / self.files[row["File_"]]
|
||||
if folder and source.is_file() and "/" not in name:
|
||||
self.put(source, folder + "/" + name)
|
||||
self.counts["files"] += 1
|
||||
if missing:
|
||||
self.notes.append("%d file(s) were not in the package's cabinets" % missing)
|
||||
|
||||
def value(self, hive, key, name, kind, data, wow64):
|
||||
# A 32-bit component writes through the 32-bit view, as Wine's msi does: HKLM\Software is
|
||||
# Software\Wow6432Node, and the prefix's link keys there (Classes, TypeLib, Fonts...) lead
|
||||
# to the keys both views share - droiddeck-wincomponents follows them when it writes.
|
||||
lower = key.lower()
|
||||
if hive == "HKLM" and wow64 and lower.startswith("software\\") and not lower.startswith("software\\wow6432node\\"):
|
||||
key = "Software\\Wow6432Node\\" + key[len("software\\"):]
|
||||
self.registry.append({"hive": hive, "key": key, "name": name, "type": kind, "data": data})
|
||||
|
||||
def registry_data(self, raw):
|
||||
"""A Registry table Value: (type, data) as droiddeck-wincomponents writes them."""
|
||||
if raw is None or raw == "":
|
||||
return "sz", ""
|
||||
if raw.startswith("#x") or raw.startswith("#X"):
|
||||
hexdigits = re.sub(r"[^0-9A-Fa-f]", "", self.format(raw[2:]))
|
||||
if len(hexdigits) % 2:
|
||||
hexdigits = "0" + hexdigits
|
||||
return "binary", hexdigits.lower()
|
||||
if raw.startswith("#%"):
|
||||
return "expand_sz", self.format(raw[2:])
|
||||
if raw.startswith("##"):
|
||||
return "sz", self.format(raw[1:])
|
||||
if raw.startswith("#"):
|
||||
number = self.format(raw[1:])
|
||||
if re.fullmatch(r"[+-]?\d+", number.strip()):
|
||||
return "dword", int(number) & 0xFFFFFFFF
|
||||
return "sz", number
|
||||
text = self.format(raw)
|
||||
if "\0" in text:
|
||||
parts = [part for part in text.split("\0") if part]
|
||||
return "multi_sz", parts
|
||||
return "sz", text
|
||||
|
||||
def install_registry(self):
|
||||
for row in self.pkg.table("Registry"):
|
||||
comp = row["Component_"]
|
||||
if comp not in self.included_components:
|
||||
continue
|
||||
root = to_int(row["Root"], 2)
|
||||
hive, prefix = {-1: ("HKLM", ""), 0: ("HKLM", "Software\\Classes\\"), 1: ("HKCU", ""),
|
||||
2: ("HKLM", "")}.get(root, (None, None))
|
||||
if hive is None:
|
||||
continue
|
||||
key = prefix + self.format(row["Key"]).strip("\\")
|
||||
wow64 = not (to_int(self.components[comp].get("Attributes"), 0) & COMPONENT_64BIT)
|
||||
name = row.get("Name", "")
|
||||
raw = row.get("Value", "")
|
||||
if name in ("+", "-", "*") and not raw:
|
||||
self.value(hive, key, None, "key", None, wow64)
|
||||
continue
|
||||
if not name and not raw:
|
||||
self.value(hive, key, None, "key", None, wow64)
|
||||
continue
|
||||
kind, data = self.registry_data(raw)
|
||||
self.value(hive, key, self.format(name) or "", kind, data, wow64)
|
||||
self.counts["registry"] += 1
|
||||
for row in self.pkg.table("Environment"):
|
||||
if row["Component_"] not in self.included_components:
|
||||
continue
|
||||
flags = re.match(r"^[=+\-!*]*", row["Name"]).group(0)
|
||||
name = row["Name"][len(flags):]
|
||||
if "!" in flags or not name:
|
||||
continue
|
||||
raw = row.get("Value", "") or ""
|
||||
hive, key = ("HKLM", "System\\CurrentControlSet\\Control\\Session Manager\\Environment") if "*" in flags \
|
||||
else ("HKCU", "Environment")
|
||||
mode = "set"
|
||||
if raw.startswith("[~]"):
|
||||
mode, raw = "append", raw[3:]
|
||||
elif raw.endswith("[~]"):
|
||||
mode, raw = "prepend", raw[:-3]
|
||||
separator = ";"
|
||||
if mode == "append" and raw[:1] in ";:":
|
||||
separator, raw = raw[0], raw[1:]
|
||||
elif mode == "prepend" and raw[-1:] in ";:":
|
||||
separator, raw = raw[-1], raw[:-1]
|
||||
value = self.format(raw)
|
||||
if value:
|
||||
self.registry.append({"hive": hive, "key": key, "name": name, "type": mode, "data": value, "separator": separator})
|
||||
self.counts["registry"] += 1
|
||||
for row in self.pkg.table("Font"):
|
||||
rel = self.files.get(row["File_"])
|
||||
if not rel:
|
||||
continue
|
||||
title = row.get("FontTitle") or Path(rel).stem + " (TrueType)"
|
||||
self.value("HKLM", "Software\\Microsoft\\Windows NT\\CurrentVersion\\Fonts", title, "sz",
|
||||
rel.rsplit("/", 1)[1], False)
|
||||
self.counts["registry"] += 1
|
||||
|
||||
def check(self):
|
||||
for row in self.pkg.table("LaunchCondition"):
|
||||
if not self.conditions.evaluate(row["Condition"], default=True):
|
||||
self.notes.append("the package says: " + self.format(row.get("Description", "")).strip())
|
||||
for name in UNSUPPORTED_TABLES:
|
||||
count = len(self.pkg.table(name)) if name in self.pkg.table_names else 0
|
||||
if count:
|
||||
what = "self-registering DLL(s) not registered" if name == "SelfReg" else "%s entries not written" % name
|
||||
self.notes.append("%d %s" % (count, what))
|
||||
|
||||
def install(self):
|
||||
progress("reading %s" % (self.pkg.summary.get("subject") or Path(self.pkg.path).name))
|
||||
self.run_set_actions()
|
||||
self.select()
|
||||
with tempfile.TemporaryDirectory(dir=str(self.out.parent), prefix=".msi-") as work:
|
||||
unpacked = self.unpack(work)
|
||||
progress("placing files")
|
||||
self.install_files(unpacked)
|
||||
self.install_registry()
|
||||
self.check()
|
||||
if not self.counts["files"] and not self.registry:
|
||||
raise MsiError("the package installs nothing here")
|
||||
# A component made of several packages (32- and 64-bit) gets them all in one registry.json.
|
||||
values = []
|
||||
try:
|
||||
with open(self.out / "registry.json", encoding="utf-8") as source:
|
||||
values = json.load(source).get("values", [])
|
||||
except (FileNotFoundError, ValueError, AttributeError):
|
||||
pass
|
||||
with open(self.out / "registry.json", "w", encoding="utf-8") as out:
|
||||
json.dump({"version": 1, "values": values + self.registry}, out, indent=1)
|
||||
return {"product": self.props.get("ProductName", ""), "version": self.props.get("ProductVersion", ""),
|
||||
"counts": self.counts, "notes": self.notes}
|
||||
|
||||
|
||||
def main():
|
||||
if len(sys.argv) != 3:
|
||||
print("usage: droiddeck-msi-install <package.msi> <component dir>", file=sys.stderr)
|
||||
return 2
|
||||
out = Path(sys.argv[2])
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
try:
|
||||
result = Installer(sys.argv[1], out).install()
|
||||
except MsiError as error:
|
||||
print("error " + str(error), flush=True)
|
||||
return 1
|
||||
print("result " + json.dumps(result), flush=True)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -11,28 +11,39 @@
|
||||
# WineUtils.seedVcRedistRegistryIfDllsPresent() takes for the app's own containers. The names and
|
||||
# versions come out of the install scripts rather than a list kept here, because Valve revises
|
||||
# them; a prefix already carrying the same set is left alone.
|
||||
#
|
||||
# Games also carry install scripts of their own (<game>/_CommonRedist/vcredist/2022/installscript.vdf
|
||||
# and the like), often with another version in the value name; those are read too. And the VC++
|
||||
# 2015-2022 runtime is recorded as installed the way Microsoft's installers look for it: on ARM64
|
||||
# Proton the x64 bundle otherwise stops with "Microsoft Visual C++ 2015-2022 Redistributable (arm64)
|
||||
# is required", while Proton's own msvcp140/vcruntime140 already serve the game.
|
||||
set -u
|
||||
steam_root=${1:?steam root}
|
||||
LIBRARIES=${DROIDDECK_LIBRARIES-/mnt/droiddeck /mnt/droiddeck-sd}
|
||||
|
||||
redist="$steam_root/steamapps/common/Steamworks Shared/_CommonRedist"
|
||||
|
||||
# Every process an install script would run, as the registry key and value the client writes once
|
||||
# it has run it. Names sit one level inside "Run Process", the key they share a level further in.
|
||||
pairs=$(find "$redist" -name installscript.vdf -print0 2>/dev/null | sort -z | xargs -0 -r awk '
|
||||
FNR == 1 { depth = 0; name = ""; key = "" }
|
||||
/^[[:space:]]*\{/ { depth++; next }
|
||||
read_scripts() { xargs -0 -r awk '
|
||||
# A block whose HasRunKey is set is one process; its name is the key the block opened under, at
|
||||
# whatever depth - an install script nests it under "Run Process", the client'"'"'s evaluator script
|
||||
# for a game wraps the same blocks once more.
|
||||
FNR == 1 { depth = 0; pending = "" }
|
||||
/^[[:space:]]*\{/ { depth++; name[depth] = pending; key[depth] = ""; pending = ""; next }
|
||||
/^[[:space:]]*\}/ {
|
||||
if (depth == 3 && name != "" && key != "")
|
||||
printf "%s\t%s\n", key, name
|
||||
depth--
|
||||
if (depth > 0 && key[depth] != "" && name[depth] != "")
|
||||
printf "%s\t%s\n", key[depth], name[depth]
|
||||
if (depth > 0) depth--
|
||||
next
|
||||
}
|
||||
{
|
||||
n = split($0, part, "\"")
|
||||
if (n >= 5 && tolower(part[2]) == "hasrunkey") { key = part[4]; next }
|
||||
if (n >= 3 && depth == 2) { name = part[2]; key = "" }
|
||||
if (n >= 5 && tolower(part[2]) == "hasrunkey") { key[depth] = part[4]; next }
|
||||
if (n == 3) pending = part[2]
|
||||
}
|
||||
')
|
||||
'; }
|
||||
pairs=$(find "$redist" -name installscript.vdf -print0 2>/dev/null | sort -z | read_scripts)
|
||||
# The client downloads the scripts with the first game that wants them, which is too late for that
|
||||
# game; until then the set they held when this was written stands in. (WinNative's list.)
|
||||
[ -n "$pairs" ] || pairs=$(sed 's/^\([^ ]*\) /HKEY_LOCAL_MACHINE\\\\Software\\\\Valve\\\\Steam\\\\Apps\\\\CommonRedist\\\\\1\t/' <<'KNOWN'
|
||||
@@ -54,9 +65,51 @@ vcredist\\2022 x86 14.51.36247.0
|
||||
vcredist\\2022 x64 14.51.36247.0
|
||||
KNOWN
|
||||
)
|
||||
|
||||
# The games' own scripts. Finding them walks every game folder, so the list is kept until a game is
|
||||
# installed, updated or removed (its appmanifest changes) - this runs every quarter minute.
|
||||
cache="$steam_root/.droiddeck-game-scripts"
|
||||
libraries="$steam_root"
|
||||
for library in $LIBRARIES; do libraries="$libraries
|
||||
$library"; done
|
||||
sig=$(while IFS= read -r library; do ls -l --time-style=+%s "$library"/steamapps/appmanifest_*.acf 2>/dev/null; done <<<"$libraries" | cksum)
|
||||
if [ "$(head -n 1 "$cache" 2>/dev/null)" != "$sig" ]; then
|
||||
{
|
||||
printf '%s\n' "$sig"
|
||||
while IFS= read -r library; do
|
||||
[ -d "$library/steamapps/common" ] || continue
|
||||
find "$library/steamapps/common" -mindepth 2 -maxdepth 5 -iname 'installscript*.vdf' \
|
||||
-not -path '*/Steamworks Shared/*' 2>/dev/null
|
||||
done <<<"$libraries" | sort -u
|
||||
} >"$cache.tmp" && mv -f "$cache.tmp" "$cache"
|
||||
fi
|
||||
game_pairs=$(tail -n +2 "$cache" 2>/dev/null | tr '\n' '\0' | read_scripts)
|
||||
# DROIDDECK_SEED_SCRIPTS: more scripts, one path a line - droiddeck-game-env passes the client's
|
||||
# evaluator script for the game about to run its installers, read before the client looks.
|
||||
if [ -n "${DROIDDECK_SEED_SCRIPTS:-}" ]; then
|
||||
game_pairs=$(printf '%s\n%s\n' "$game_pairs" "$(printf '%s\n' "$DROIDDECK_SEED_SCRIPTS" | tr '\n' '\0' | read_scripts)")
|
||||
fi
|
||||
[ -n "$(printf '%s' "$game_pairs" | tr -d '[:space:]')" ] && pairs=$(printf '%s\n%s\n' "$pairs" "$game_pairs" | sort -u | sed '/^$/d')
|
||||
|
||||
# The VC++ 2015-2022 runtime as its installers check for it, for each architecture and both registry
|
||||
# views. The version is the newest the scripts above know, so any 2015-2022 bundle finds itself
|
||||
# already installed and exits without asking for anything.
|
||||
VCRT_MAJOR=14 VCRT_MINOR=51 VCRT_BUILD=36247
|
||||
vcrt() {
|
||||
local view arch
|
||||
for view in 'Software' 'Software\\Wow6432Node'; do
|
||||
for arch in x86 x64 arm64; do
|
||||
printf '\n[%s\\\\Microsoft\\\\VisualStudio\\\\14.0\\\\VC\\\\Runtimes\\\\%s] %d\n' "$view" "$arch" "$1"
|
||||
printf '"Bld"=dword:%08x\n"Installed"=dword:00000001\n"Major"=dword:%08x\n"Minor"=dword:%08x\n"Rbld"=dword:00000000\n' \
|
||||
"$VCRT_BUILD" "$VCRT_MAJOR" "$VCRT_MINOR"
|
||||
printf '"Version"="v%d.%d.%d.00"\n' "$VCRT_MAJOR" "$VCRT_MINOR" "$VCRT_BUILD"
|
||||
done
|
||||
done
|
||||
}
|
||||
|
||||
# The stamp is the set of names, taken before the block below dates its keys: stamped from the
|
||||
# dated block it never matched, and every prefix had the whole block appended again on every beat.
|
||||
stamp=$(printf '%s' "$pairs" | cksum)
|
||||
stamp=$(printf '%s vcrt %s.%s.%s' "$pairs" "$VCRT_MAJOR" "$VCRT_MINOR" "$VCRT_BUILD" | cksum)
|
||||
|
||||
block=$(printf '%s\n' "$pairs" | awk -F'\t' -v now="$(date +%s)" '
|
||||
{
|
||||
@@ -67,11 +120,14 @@ block=$(printf '%s\n' "$pairs" | awk -F'\t' -v now="$(date +%s)" '
|
||||
printf "\n[%s] %d\n\"%s\"=dword:00000001\n", path, now, $2
|
||||
# The client writes these from 32-bit steam.exe, so its own copy lands under Wow6432Node;
|
||||
# both spellings are seeded because the reader picks by its own word size.
|
||||
sub(/^Software\\\\/, "Software\\\\\\\\Wow6432Node\\\\\\\\", path)
|
||||
printf "\n[%s] %d\n\"%s\"=dword:00000001\n", path, now, $2
|
||||
# Joined rather than sub()stituted: gawk and mawk read backslashes in a replacement differently.
|
||||
if (substr(path, 1, 10) != "Software\\\\")
|
||||
next
|
||||
printf "\n[%s] %d\n\"%s\"=dword:00000001\n", "Software\\\\Wow6432Node\\\\" substr(path, 11), now, $2
|
||||
}
|
||||
')
|
||||
[ -n "$block" ] || exit 0
|
||||
block="$block
|
||||
$(vcrt "$(date +%s)")"
|
||||
|
||||
# Proton builds a new prefix from its template, and the client runs the install scripts in that
|
||||
# prefix moments later, so the template carries the markers too. Its date is kept: Proton reads a
|
||||
|
||||
@@ -38,7 +38,10 @@ collect_steam_logs() {
|
||||
# Into steam/ beside this session's own logs. The app scrubs these line by line after the
|
||||
# session ends - they carry the account's session token and id - so nothing here is the last
|
||||
# word on what the user ends up sharing; this is just the copy that survives the runtime.
|
||||
[ -d "$steam_root/logs" ] && cp -r "$steam_root/logs/." "$BL_DEBUG_DIR/steam/" 2>/dev/null
|
||||
# Up to 8 MB each, as the app's own copy takes them: the client's CEF and *.previous.txt logs
|
||||
# reach 17 MB and say little about this session, and every share scrubs whatever is here.
|
||||
[ -d "$steam_root/logs" ] && find "$steam_root/logs" -maxdepth 1 -type f -size -8192k \
|
||||
-exec cp {} "$BL_DEBUG_DIR/steam/" \; 2>/dev/null
|
||||
[ -f "$HOME/.steam/steam/logs/steamwebhelper.log" ] && cp "$HOME/.steam/steam/logs/steamwebhelper.log" "$BL_DEBUG_DIR/steam/" 2>/dev/null
|
||||
# NOT copied, ever: loginusers.vdf, config.vdf and the ssfn* files, which hold the credentials
|
||||
# themselves rather than a mention of them.
|
||||
@@ -162,7 +165,7 @@ if [ -z "${BL_INSIDE:-}" ]; then
|
||||
fi
|
||||
fi
|
||||
args=(--backend wayland --expose-wayland -f -W "$width" -H "$height" -w "$nested" -h "$height")
|
||||
[ "$nested" != "$width" ] && args+=(-S stretch)
|
||||
[ "$nested" != "$width" ] && args+=(-S stretch) && export BL_STRETCHED=1
|
||||
# -r is what gamescope advertises as the refresh rate, and what a game reads as the display's.
|
||||
# Left unset it defaults to 60, so a 120 Hz panel offers only 60 Hz in game settings. The FPS
|
||||
# limiter wins when it is on (it is a deliberate cap); otherwise use the panel's own rate.
|
||||
@@ -172,17 +175,27 @@ if [ -z "${BL_INSIDE:-}" ]; then
|
||||
args+=(-r "$BL_REFRESH")
|
||||
fi
|
||||
[ "$mode" = steam ] && args+=(-e)
|
||||
# Two Xwayland servers, as SteamOS runs Steam: the client on the first, games on the second
|
||||
# (STEAM_GAME_DISPLAY_0). The client then sizes the games' server to each game's Game Resolution
|
||||
# (GAMESCOPE_XWAYLAND_MODE_CONTROL; native unless one is set), and gamescope scales it to the
|
||||
# output. With one server the client and its games share the output's size, so a game's own Game
|
||||
# Resolution never reaches its display (docs/development/steam-display-scaling.md). The client's
|
||||
# overlay is also on another server than the game, so opening it no longer takes the game's X
|
||||
# keyboard focus, which made games like FlatOut shrink their window.
|
||||
# BL_XWAYLAND_COUNT=1 in Download/droiddeck-env goes back to one.
|
||||
if [ "$mode" = steam ] && [ "${BL_XWAYLAND_COUNT:-2}" -gt 1 ]; then
|
||||
args+=(--xwayland-count "${BL_XWAYLAND_COUNT:-2}")
|
||||
export STEAM_MULTIPLE_XWAYLANDS=1
|
||||
fi
|
||||
# Touch passes through to the client as touch until the client says otherwise, as SteamOS's
|
||||
# gamescope-session starts it (TOUCH_MODE=4). The client sets the mode itself (STEAM_TOUCH_CLICK_MODE)
|
||||
# only once it has a controller; until then gamescope's own default made a finger a left-click
|
||||
# mouse, so the Steam interface took taps but would not scroll on a phone with no pad attached.
|
||||
[ "$mode" = steam ] && args+=(--default-touch-mode 4)
|
||||
# A game that resizes its own window when it loses focus (the Steam menu opening over it) comes
|
||||
# back smaller, and gamescope draws a window that is not flagged fullscreen at its own size in
|
||||
# the top-left corner. Forcing every window to the output's size keeps it filling the screen,
|
||||
# but a game running at a resolution other than the screen's fights it and flickers, so it is
|
||||
# off unless the app asks for it: BL_GAMESCOPE_FORCE_FULLSCREEN=1 turns it on.
|
||||
[ "$mode" = steam ] && [ "${BL_GAMESCOPE_FORCE_FULLSCREEN:-0}" = 1 ] && args+=(--force-windows-fullscreen)
|
||||
# No --force-windows-fullscreen: it was for games that shrink their window when the Steam menu
|
||||
# opens over them (FlatOut), which no longer happens with the games on their own Xwayland server
|
||||
# (above), and it made any game drawing at another size than its display fight it. An experiment
|
||||
# can still pass it with BL_GAMESCOPE_ARGS.
|
||||
# HDR10: the app opened its compositor's colour-management gate for this session (BL_HDR=1);
|
||||
# gamescope then offers HDR to its clients through the same wp_color_manager_v1 it binds on ours.
|
||||
[ "${BL_HDR:-0}" = 1 ] && args+=(--hdr-enabled)
|
||||
@@ -206,6 +219,21 @@ if [ -z "${BL_INSIDE:-}" ]; then
|
||||
fi
|
||||
|
||||
# gamescope manages X windows: toolkits go through Xwayland, not gamescope's own Wayland socket.
|
||||
# Root-window requests for the game (restore) go to every display gamescope gave us:
|
||||
# the client's ($DISPLAY) and, with two servers, the games' (STEAM_GAME_DISPLAY_0); gamescope reads
|
||||
# them per server.
|
||||
bl_displays() {
|
||||
printf '%s\n' "$DISPLAY"
|
||||
[ -n "${STEAM_GAME_DISPLAY_0:-}" ] && [ "$STEAM_GAME_DISPLAY_0" != "$DISPLAY" ] && printf '%s\n' "$STEAM_GAME_DISPLAY_0"
|
||||
return 0
|
||||
}
|
||||
bl_xprop_set_all() {
|
||||
local d ok=1
|
||||
for d in $(bl_displays); do
|
||||
DISPLAY=$d xprop -root -f "$1" 32c -set "$1" "$2" 2>/dev/null || ok=0
|
||||
done
|
||||
[ "$ok" = 1 ]
|
||||
}
|
||||
export GDK_BACKEND=x11 QT_QPA_PLATFORM=xcb SDL_VIDEODRIVER=x11
|
||||
# gamescope's reaper waits for every process left under it before the compositor comes down. A
|
||||
# process a game left behind - a Wine service blocked on a server that is already gone - is
|
||||
@@ -441,22 +469,17 @@ case $mode in
|
||||
# moments later, so the seeder has only that gap to mark the redistributables as already run.
|
||||
# It stamps each prefix it has covered and skips it thereafter, so the extra passes cost
|
||||
# almost nothing.
|
||||
# The drawer's "Stretch games to fill the screen" works live: the app writes its choice to
|
||||
# ~/.droiddeck-fill, and each change goes to gamescope as GAMESCOPE_FORCE_WINDOWS_FULLSCREEN on
|
||||
# the root window, which it watches. What gamescope was started with is where this begins.
|
||||
# Not on the desktop (BL_DESKTOP): no gamescope there, and the loop would outlive the client.
|
||||
[ -z "${BL_DESKTOP:-}" ] && (
|
||||
last=${BL_GAMESCOPE_FORCE_FULLSCREEN:-0}
|
||||
# With the 16:9 stretch on, the client's own scaler must not undo it: in Deck mode it sets
|
||||
# GAMESCOPE_NEW_SCALING_SCALER to Auto (0), which fits the 16:9 picture with bars and outranks -S.
|
||||
# Auto is put back to Stretch (4); a mode picked in the QAM (Integer, Fit, Fill) is kept.
|
||||
[ -z "${BL_DESKTOP:-}" ] && [ "${BL_STRETCHED:-0}" = 1 ] && (
|
||||
while :; do
|
||||
nap 1
|
||||
want=
|
||||
{ read -r want || [ -n "$want" ]; } < "$HOME/.droiddeck-fill" 2>/dev/null || continue
|
||||
case $want in 0|1) ;; *) continue ;; esac
|
||||
[ "$want" = "$last" ] && continue
|
||||
if xprop -root -f GAMESCOPE_FORCE_WINDOWS_FULLSCREEN 32c -set GAMESCOPE_FORCE_WINDOWS_FULLSCREEN "$want" 2>/dev/null; then
|
||||
echo "== stretch games to fill the screen: $want (live)"
|
||||
last=$want
|
||||
fi
|
||||
cur=$(xprop -root GAMESCOPE_NEW_SCALING_SCALER 2>/dev/null) || continue
|
||||
case $cur in *" = "*) cur=${cur##* = } ;; *) cur=0 ;; esac
|
||||
[ "$cur" = 0 ] || continue
|
||||
xprop -root -f GAMESCOPE_NEW_SCALING_SCALER 32c -set GAMESCOPE_NEW_SCALING_SCALER 4 2>/dev/null \
|
||||
&& echo "== stretch 16:9 to panel: the client's scaler was Auto, set to Stretch"
|
||||
done
|
||||
) &
|
||||
# Resume from the Steam menu. The menu is an overlay that takes input, and a fullscreen game that
|
||||
@@ -473,7 +496,7 @@ case $mode in
|
||||
case $app in ''|*[!0-9]*) prev=; continue ;; esac
|
||||
if [ "$prev" = 769 ] && [ "$app" != 769 ]; then
|
||||
nap 1
|
||||
xprop -root -f GAMESCOPE_RESTORE_FOCUS_WINDOW 32c -set GAMESCOPE_RESTORE_FOCUS_WINDOW 1 2>/dev/null \
|
||||
bl_xprop_set_all GAMESCOPE_RESTORE_FOCUS_WINDOW 1 \
|
||||
&& echo "== resume: asked gamescope to restore the game window (app $app)"
|
||||
fi
|
||||
prev=$app
|
||||
@@ -685,6 +708,8 @@ BUSCONF
|
||||
_bl_ui+=(-steamdeck -steamos3)
|
||||
# The QAM's Scaling Filter lists NVIDIA Image Scaling only when told gamescope has it (it does).
|
||||
export STEAM_GAMESCOPE_NIS_SUPPORTED=1
|
||||
# And shows its Scaling Mode and Scaling Filter only when told gamescope takes them.
|
||||
export STEAM_GAMESCOPE_FANCY_SCALING_SUPPORT=1
|
||||
echo "== steam: Deck mode on (-steamdeck -steamos3)"
|
||||
fi
|
||||
# What a killed session leaves behind. Android ends sessions without warning (backgrounding, the
|
||||
|
||||
+606
@@ -0,0 +1,606 @@
|
||||
#!/usr/bin/python3
|
||||
"""Windows components (OpenAL, d3dx, XAudio, ...) for a game's Proton prefix.
|
||||
|
||||
The app installs each component under STORE/<id>: its files in system32/ (64-bit) and syswow64/
|
||||
(32-bit) as Windows lays them out, and component.json naming the overrides that make Wine load
|
||||
them instead of its own ("name" for native-then-builtin, or "name=n" with Wine's own letters) and
|
||||
the components it bundles ("requires"). The ids are Bannerlator's catalog names (xaudio2.7,
|
||||
oalinst_dll...). The user picks components per game; the picks are in SELECTION as
|
||||
{"version": 1, "games": {"<appid>": ["oalinst_dll", ...]}}.
|
||||
|
||||
A component installed from a Windows Installer package (droiddeck-msi-install) also has drive_c/,
|
||||
its files at their Windows paths (Program Files, the .NET GAC, winsxs...), and registry.json, the
|
||||
values its package writes.
|
||||
|
||||
droiddeck-game-env calls apply() before every game launch. It copies what is missing or changed
|
||||
into compatdata/<appid>/pfx, writes the components' registry values into the prefix's registry
|
||||
files (system.reg, user.reg) and returns the overrides for WINEDLLOVERRIDES, so Wine never has to
|
||||
be running. A prefix Proton has not made yet gets the registry values on the launch after.
|
||||
|
||||
Proton leaves the files alone afterwards: its builtin refresh (update_builtin_libs) replaces only
|
||||
files that are its own builtins, and a new prefix is built around files already there (copy_pfx
|
||||
skips them). The one case that removes them is a launch on an older Proton than the prefix's,
|
||||
which deletes every file Proton once placed - and the next launch's apply() puts ours back.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
STORE = Path("/opt/droiddeck/wincomponents")
|
||||
SELECTION = Path.home() / ".config/droiddeck/wincomponents.json"
|
||||
# What this prefix holds from us, so a component the user turns off is taken out again.
|
||||
STATE = ".droiddeck-wincomponents.json"
|
||||
# A file ours replaced that was not Proton's (a real installer's, the user's own), put back when the
|
||||
# component is turned off. Proton's builtins need no copy: it restores those itself.
|
||||
BACKUP = ".droiddeck-wincomponents-backup"
|
||||
BUILTIN_MARKS = (b"Wine builtin DLL", b"Wine placeholder DLL")
|
||||
ARCH_DIRS = ("system32", "syswow64")
|
||||
ID = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]{0,63}")
|
||||
# The registry file of each hive in a prefix, and the kinds of value registry.json holds: "key"
|
||||
# makes a key, "append"/"prepend" add to a list such as PATH unless it is already there.
|
||||
HIVES = {"HKLM": "system.reg", "HKCU": "user.reg"}
|
||||
VALUE_TYPES = {"key", "sz", "expand_sz", "multi_sz", "dword", "binary", "append", "prepend"}
|
||||
|
||||
|
||||
def valid_id(value):
|
||||
return isinstance(value, str) and ID.fullmatch(value) is not None and ".." not in value
|
||||
|
||||
|
||||
def wanted(app_id, selection=SELECTION):
|
||||
try:
|
||||
with open(selection, encoding="utf-8") as source:
|
||||
config = json.load(source)
|
||||
except FileNotFoundError:
|
||||
return []
|
||||
if config.get("version") != 1:
|
||||
raise ValueError("unsupported components selection")
|
||||
ids = config.get("games", {}).get(app_id, [])
|
||||
if not isinstance(ids, list) or not all(valid_id(i) for i in ids):
|
||||
raise ValueError("invalid components selection")
|
||||
return ids
|
||||
|
||||
|
||||
def component(store, cid):
|
||||
"""The component's overrides, its files as (relative path, source) and the ids it bundles, or None if not installed."""
|
||||
root = Path(store) / cid
|
||||
try:
|
||||
with open(root / "component.json", encoding="utf-8") as source:
|
||||
meta = json.load(source)
|
||||
except (FileNotFoundError, ValueError):
|
||||
return None
|
||||
files = []
|
||||
for arch in ARCH_DIRS:
|
||||
folder = root / arch
|
||||
if folder.is_dir():
|
||||
# A few go one level down (gmdls: system32/drivers/gm.dls).
|
||||
for entry in sorted(folder.rglob("*")):
|
||||
if entry.is_file() and not entry.is_symlink():
|
||||
rel = entry.relative_to(folder).as_posix().lower()
|
||||
files.append(("drive_c/windows/%s/%s" % (arch, rel), entry))
|
||||
drive = root / "drive_c"
|
||||
if drive.is_dir():
|
||||
for entry in sorted(drive.rglob("*")):
|
||||
if entry.is_file() and not entry.is_symlink():
|
||||
files.append(("drive_c/" + entry.relative_to(drive).as_posix(), entry))
|
||||
requires = [r for r in meta.get("requires", []) if valid_id(r)]
|
||||
return [str(o) for o in meta.get("overrides", [])], files, requires, registry_values(root)
|
||||
|
||||
|
||||
def registry_values(root):
|
||||
"""The component's registry values (registry.json), the ones that are well formed."""
|
||||
try:
|
||||
with open(Path(root) / "registry.json", encoding="utf-8") as source:
|
||||
values = json.load(source).get("values", [])
|
||||
except (FileNotFoundError, ValueError, AttributeError):
|
||||
return []
|
||||
good = []
|
||||
for value in values if isinstance(values, list) else []:
|
||||
if isinstance(value, dict) and value.get("hive") in HIVES and isinstance(value.get("key"), str) \
|
||||
and value.get("type") in VALUE_TYPES and value["key"].strip("\\") and "\0" not in value["key"]:
|
||||
good.append(value)
|
||||
return good
|
||||
|
||||
|
||||
def expand(store, ids):
|
||||
"""The picks with everything they bundle, each once, a bundle's parts before it."""
|
||||
out, seen = [], set()
|
||||
|
||||
def visit(cid, depth):
|
||||
if cid in seen or depth > 8:
|
||||
return
|
||||
seen.add(cid)
|
||||
found = component(store, cid)
|
||||
for dep in (found[2] if found else []):
|
||||
visit(dep, depth + 1)
|
||||
out.append(cid)
|
||||
|
||||
for cid in ids:
|
||||
visit(cid, 0)
|
||||
return out
|
||||
|
||||
|
||||
def spelled(path):
|
||||
"""path with each folder that exists spelled as the prefix spells it (Windows names ignore case)."""
|
||||
parts = path.parts
|
||||
current = Path(parts[0])
|
||||
for part in parts[1:]:
|
||||
candidate = current / part
|
||||
if not candidate.exists():
|
||||
try:
|
||||
with os.scandir(current) as entries:
|
||||
for entry in entries:
|
||||
if entry.name.lower() == part.lower() and entry.is_dir():
|
||||
candidate = current / entry.name
|
||||
break
|
||||
except OSError:
|
||||
pass
|
||||
current = candidate
|
||||
return current
|
||||
|
||||
|
||||
def existing(path):
|
||||
"""The file at path as the prefix spells it: Windows names ignore case, the filesystem may not."""
|
||||
folder = spelled(path.parent)
|
||||
path = folder / path.name
|
||||
try:
|
||||
with os.scandir(folder) as entries:
|
||||
for entry in entries:
|
||||
if entry.name.lower() == path.name.lower():
|
||||
return folder / entry.name
|
||||
except OSError:
|
||||
pass
|
||||
return None
|
||||
|
||||
|
||||
def same(src, dst):
|
||||
try:
|
||||
if dst.is_symlink():
|
||||
return False
|
||||
a, b = src.stat(), dst.stat()
|
||||
except OSError:
|
||||
return False
|
||||
return a.st_size == b.st_size and int(a.st_mtime) == int(b.st_mtime)
|
||||
|
||||
|
||||
def builtin(path):
|
||||
"""Proton's own: a symlink into its files, or a Wine DLL that says so in its DOS stub."""
|
||||
if path.is_symlink():
|
||||
return True
|
||||
try:
|
||||
with open(path, "rb") as source:
|
||||
head = source.read(512)
|
||||
except OSError:
|
||||
return False
|
||||
return any(mark in head for mark in BUILTIN_MARKS)
|
||||
|
||||
|
||||
def place(src, target, backup=None):
|
||||
"""Copies src over target unless it is already there; a file of someone else's goes to backup first."""
|
||||
target = spelled(target.parent) / target.name
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
found = existing(target)
|
||||
if found is not None and same(src, found):
|
||||
return False
|
||||
if found is not None and backup is not None and not backup.exists() and not builtin(found):
|
||||
backup.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copy2(found, backup)
|
||||
final = found or target
|
||||
temp = final.with_name(".%s.droiddeck" % final.name)
|
||||
shutil.copy2(src, temp)
|
||||
# Over a Proton builtin this swaps its symlink for our file.
|
||||
os.replace(temp, final)
|
||||
return True
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- the prefix's registry files
|
||||
|
||||
def reg_escape(text, extra=""):
|
||||
"""A string as Wine's registry files write it."""
|
||||
out = []
|
||||
for ch in text:
|
||||
if ch == "\\" or ch == '"' or ch in extra:
|
||||
out.append("\\" + ch)
|
||||
elif ch == "\n":
|
||||
out.append("\\n")
|
||||
elif ch == "\r":
|
||||
out.append("\\r")
|
||||
elif ch == "\t":
|
||||
out.append("\\t")
|
||||
elif ch == "\0":
|
||||
out.append("\\0")
|
||||
elif ch < " " or ch > "~":
|
||||
out.append("\\x%04x" % ord(ch))
|
||||
else:
|
||||
out.append(ch)
|
||||
return "".join(out)
|
||||
|
||||
|
||||
def reg_unescape(text):
|
||||
out, i = [], 0
|
||||
while i < len(text):
|
||||
ch = text[i]
|
||||
if ch != "\\" or i + 1 >= len(text):
|
||||
out.append(ch)
|
||||
i += 1
|
||||
continue
|
||||
nxt = text[i + 1]
|
||||
if nxt == "x":
|
||||
match = re.match(r"[0-9a-fA-F]{1,4}", text[i + 2:])
|
||||
if match:
|
||||
out.append(chr(int(match.group(0), 16)))
|
||||
i += 2 + len(match.group(0))
|
||||
continue
|
||||
out.append({"n": "\n", "r": "\r", "t": "\t", "0": "\0"}.get(nxt, nxt))
|
||||
i += 2
|
||||
return "".join(out)
|
||||
|
||||
|
||||
def reg_key_line(key):
|
||||
return "[%s]" % "\\\\".join(reg_escape(part, "[]") for part in key.strip("\\").split("\\"))
|
||||
|
||||
|
||||
def reg_value_line(name, kind, data):
|
||||
"""name=data as one registry file line; None for a kind that has no line of its own."""
|
||||
head = "@" if name == "" else '"%s"' % reg_escape(name)
|
||||
if kind == "sz":
|
||||
return '%s="%s"' % (head, reg_escape(str(data)))
|
||||
if kind == "expand_sz":
|
||||
return '%s=str(2):"%s"' % (head, reg_escape(str(data)))
|
||||
if kind == "multi_sz":
|
||||
parts = [str(part) for part in data] if isinstance(data, list) else [str(data)]
|
||||
return '%s=str(7):"%s"' % (head, reg_escape("".join(part + "\0" for part in parts)))
|
||||
if kind == "dword":
|
||||
return "%s=dword:%08x" % (head, int(data) & 0xFFFFFFFF)
|
||||
if kind == "binary":
|
||||
digits = re.sub(r"[^0-9a-f]", "", str(data).lower())
|
||||
return "%s=hex:%s" % (head, ",".join(digits[i:i + 2] for i in range(0, len(digits) - 1, 2)))
|
||||
return None
|
||||
|
||||
|
||||
def reg_string(line):
|
||||
"""The text of a string value line (plain or str(2)), or None for any other kind."""
|
||||
match = re.match(r'^(?:@|"(?:[^"\\]|\\.)*")=(?:str\(2\):)?"((?:[^"\\]|\\.)*)"\s*$', line)
|
||||
return reg_unescape(match.group(1)) if match else None
|
||||
|
||||
|
||||
class RegistryFile:
|
||||
"""One of a prefix's registry files, as Wine keeps them: [key] sections of name=value lines."""
|
||||
|
||||
def __init__(self, path):
|
||||
self.path = Path(path)
|
||||
with open(self.path, encoding="utf-8", errors="surrogateescape", newline="") as source:
|
||||
self.lines = source.read().split("\n")
|
||||
self.changed = False
|
||||
self.index = {}
|
||||
self.links = {}
|
||||
root = ""
|
||||
for line in self.lines[:4]:
|
||||
match = re.match(r"^;; All keys relative to (.*)$", line)
|
||||
if match:
|
||||
root = reg_unescape(match.group(1)).strip("\\").lower()
|
||||
current = None
|
||||
for number, line in enumerate(self.lines):
|
||||
if line.startswith("["):
|
||||
key = self.parse_key(line)
|
||||
current = key
|
||||
if key is not None:
|
||||
self.index.setdefault(key.lower(), number)
|
||||
elif line == "#link" and current is not None:
|
||||
target = self.link_target(number, root)
|
||||
if target:
|
||||
self.links[current.lower()] = target
|
||||
|
||||
def link_target(self, number, root):
|
||||
"""Where the link key whose "#link" line is at number leads, relative to this file's root."""
|
||||
for at in range(number + 1, min(number + 8, len(self.lines))):
|
||||
line = self.lines[at]
|
||||
if line.startswith("["):
|
||||
return None
|
||||
if line.startswith('"SymbolicLinkValue"=hex(6):'):
|
||||
data = line.split(":", 1)[1]
|
||||
while data.endswith("\\") and at + 1 < len(self.lines):
|
||||
at += 1
|
||||
data = data[:-1] + self.lines[at].strip()
|
||||
try:
|
||||
raw = bytes(int(part, 16) for part in data.split(",") if part.strip())
|
||||
target = raw.decode("utf-16-le").strip("\\")
|
||||
except ValueError:
|
||||
return None
|
||||
if root and target.lower().startswith(root + "\\"):
|
||||
return target[len(root) + 1:]
|
||||
return None
|
||||
return None
|
||||
|
||||
def resolve(self, key):
|
||||
"""The key Wine really keeps key in: a path through a link key leads to the link's target."""
|
||||
key = key.strip("\\")
|
||||
for _ in range(8):
|
||||
lower = key.lower()
|
||||
for link, target in self.links.items():
|
||||
if lower == link or lower.startswith(link + "\\"):
|
||||
key = target + key[len(link):]
|
||||
break
|
||||
else:
|
||||
return key
|
||||
return key
|
||||
|
||||
@staticmethod
|
||||
def parse_key(line):
|
||||
end, i = None, 1
|
||||
while i < len(line):
|
||||
if line[i] == "\\":
|
||||
i += 2
|
||||
continue
|
||||
if line[i] == "]":
|
||||
end = i
|
||||
break
|
||||
i += 1
|
||||
return None if end is None else reg_unescape(line[1:end])
|
||||
|
||||
def section(self, key):
|
||||
"""(start, end) line numbers of the key's values, or None."""
|
||||
start = self.index.get(self.resolve(key).lower())
|
||||
if start is None:
|
||||
return None
|
||||
end = start + 1
|
||||
while end < len(self.lines) and not self.lines[end].startswith("["):
|
||||
end += 1
|
||||
return start + 1, end
|
||||
|
||||
@staticmethod
|
||||
def value_name(line):
|
||||
if line.startswith("@="):
|
||||
return ""
|
||||
match = re.match(r'^"((?:[^"\\]|\\.)*)"=', line)
|
||||
return reg_unescape(match.group(1)).lower() if match else None
|
||||
|
||||
def find(self, key, name):
|
||||
"""(first, last + 1) of the value's lines, or None."""
|
||||
span = self.section(key)
|
||||
if span is None:
|
||||
return None
|
||||
wanted = name.lower()
|
||||
number = span[0]
|
||||
while number < span[1]:
|
||||
line = self.lines[number]
|
||||
last = number
|
||||
while self.lines[last].endswith("\\") and last + 1 < span[1]:
|
||||
last += 1
|
||||
if self.value_name(line) == wanted:
|
||||
return number, last + 1
|
||||
number = last + 1
|
||||
return None
|
||||
|
||||
def get(self, key, name):
|
||||
found = self.find(key, name)
|
||||
return None if found is None else "\n".join(self.lines[found[0]:found[1]])
|
||||
|
||||
def ensure_key(self, key):
|
||||
key = self.resolve(key)
|
||||
if key.lower() in self.index:
|
||||
return
|
||||
now = time.time()
|
||||
while self.lines and self.lines[-1] == "":
|
||||
self.lines.pop()
|
||||
self.lines += ["", "%s %d" % (reg_key_line(key), int(now)),
|
||||
"#time=%x" % (int(now * 10000000) + 116444736000000000)]
|
||||
self.index[key.lower()] = len(self.lines) - 2
|
||||
self.lines.append("")
|
||||
self.changed = True
|
||||
|
||||
def put(self, key, name, raw):
|
||||
"""Sets the value's line(s) to raw, or removes the value when raw is None; True if that changed it."""
|
||||
found = self.find(key, name)
|
||||
if raw is None:
|
||||
if found is None:
|
||||
return False
|
||||
del self.lines[found[0]:found[1]]
|
||||
self.shift(found[0], found[0] - found[1])
|
||||
self.changed = True
|
||||
return True
|
||||
new = raw.split("\n")
|
||||
if found is not None:
|
||||
if self.lines[found[0]:found[1]] == new:
|
||||
return False
|
||||
self.lines[found[0]:found[1]] = new
|
||||
self.shift(found[0], len(new) - (found[1] - found[0]))
|
||||
else:
|
||||
self.ensure_key(key)
|
||||
start, end = self.section(key)
|
||||
while end > start and self.lines[end - 1] == "":
|
||||
end -= 1
|
||||
self.lines[end:end] = new
|
||||
self.shift(end, len(new))
|
||||
self.changed = True
|
||||
return True
|
||||
|
||||
def shift(self, at, by):
|
||||
if by:
|
||||
for key, number in self.index.items():
|
||||
if number >= at:
|
||||
self.index[key] = number + by
|
||||
|
||||
def save(self):
|
||||
if not self.changed:
|
||||
return
|
||||
temp = self.path.with_name("." + self.path.name + ".droiddeck")
|
||||
with open(temp, "w", encoding="utf-8", errors="surrogateescape", newline="") as out:
|
||||
out.write("\n".join(self.lines))
|
||||
shutil.copymode(self.path, temp)
|
||||
os.replace(temp, self.path)
|
||||
self.changed = False
|
||||
|
||||
|
||||
def list_line(name, current, item, separator, add, at_end=True):
|
||||
"""current (a string value line) with item added to or taken out of its list, None if it had
|
||||
nothing else; a value that is not a string is left as it is."""
|
||||
text = reg_string(current) if current is not None else ""
|
||||
if text is None:
|
||||
return current
|
||||
items = [part for part in text.split(separator) if part and part.lower() != item.lower()]
|
||||
if add:
|
||||
items = items + [item] if at_end else [item] + items
|
||||
if not items:
|
||||
return None
|
||||
expand = current is None or "=str(2):" in current
|
||||
return reg_value_line(name, "expand_sz" if expand else "sz", separator.join(items))
|
||||
|
||||
|
||||
def apply_registry(pfx, values, state):
|
||||
"""Writes the picked components' registry values into the prefix and takes out the ones of
|
||||
components turned off: a value goes back to what it was before, an entry added to a list such
|
||||
as PATH just leaves the list. Returns (values written, notes)."""
|
||||
files = {}
|
||||
for hive, name in HIVES.items():
|
||||
if (pfx / name).is_file():
|
||||
files[hive] = RegistryFile(pfx / name)
|
||||
old = state.get("registry") if isinstance(state.get("registry"), dict) else {}
|
||||
keep, notes, written, waiting = {}, [], 0, 0
|
||||
for cid, value in values:
|
||||
reg = files.get(value["hive"])
|
||||
if reg is None:
|
||||
waiting += 1
|
||||
continue
|
||||
if value["type"] == "key":
|
||||
reg.ensure_key(value["key"])
|
||||
continue
|
||||
name = value.get("name") or ""
|
||||
ident = "%s\t%s\t%s" % (value["hive"], value["key"].lower(), name.lower())
|
||||
current = reg.get(value["key"], name)
|
||||
record = keep.get(ident) or (old.get(ident) if isinstance(old.get(ident), dict) else None) or {"prev": current}
|
||||
if value["type"] in ("append", "prepend"):
|
||||
line = list_line(name, current, str(value.get("data", "")), value.get("separator") or ";", True,
|
||||
value["type"] == "append")
|
||||
record = dict(record, item=str(value.get("data", "")), separator=value.get("separator") or ";")
|
||||
else:
|
||||
line = reg_value_line(name, value["type"], value.get("data"))
|
||||
if line != current and reg.put(value["key"], name, line):
|
||||
written += 1
|
||||
keep[ident] = dict(record, cid=cid, hive=value["hive"], key=value["key"], name=name)
|
||||
for ident, record in old.items():
|
||||
if ident in keep or not isinstance(record, dict) or not isinstance(record.get("key"), str):
|
||||
continue
|
||||
reg = files.get(record.get("hive"))
|
||||
if reg is None:
|
||||
keep[ident] = record
|
||||
continue
|
||||
name = record.get("name") or ""
|
||||
if "item" in record:
|
||||
line = list_line(name, reg.get(record["key"], name), record["item"], record.get("separator") or ";", False)
|
||||
else:
|
||||
line = record.get("prev")
|
||||
if reg.put(record["key"], name, line):
|
||||
written += 1
|
||||
for reg in files.values():
|
||||
reg.save()
|
||||
state["registry"] = keep
|
||||
if waiting:
|
||||
notes.append("%d registry value(s) wait for the prefix: they go in on the next launch" % waiting)
|
||||
return written, notes
|
||||
|
||||
def load_state(compat):
|
||||
try:
|
||||
with open(compat / STATE, encoding="utf-8") as source:
|
||||
state = json.load(source)
|
||||
return state if isinstance(state.get("files"), dict) else {"files": {}}
|
||||
except (FileNotFoundError, ValueError, AttributeError):
|
||||
return {"files": {}}
|
||||
|
||||
|
||||
def save_state(compat, state):
|
||||
temp = compat / (STATE + ".tmp")
|
||||
with open(temp, "w", encoding="utf-8") as out:
|
||||
json.dump(state, out, indent=1, sort_keys=True)
|
||||
os.replace(temp, compat / STATE)
|
||||
|
||||
|
||||
def apply(compat_path, app_id, selection=SELECTION, store=STORE):
|
||||
"""Brings the prefix in line with the game's picks. Returns (overrides, notes)."""
|
||||
compat = Path(compat_path)
|
||||
pfx = compat / "pfx"
|
||||
ids = wanted(app_id, selection)
|
||||
state = load_state(compat)
|
||||
if not ids and not state["files"] and not state.get("registry"):
|
||||
return [], []
|
||||
notes, overrides, keep = [], [], {}
|
||||
copied = 0
|
||||
installed = []
|
||||
values = []
|
||||
for cid in expand(store, ids):
|
||||
found = component(store, cid)
|
||||
if found is None:
|
||||
notes.append("%s is not installed; skipped" % cid)
|
||||
continue
|
||||
installed.append(cid)
|
||||
names, files, _, registry = found
|
||||
overrides += names
|
||||
values += [(cid, value) for value in registry]
|
||||
for rel, src in files:
|
||||
# A file this prefix already has from us is ours to replace; anything else is kept.
|
||||
if place(src, pfx / rel, None if rel in state["files"] else compat / BACKUP / rel):
|
||||
copied += 1
|
||||
keep[rel] = cid
|
||||
removed = restored = 0
|
||||
for rel, cid in state["files"].items():
|
||||
if rel in keep:
|
||||
continue
|
||||
path = existing(pfx / rel)
|
||||
saved = compat / BACKUP / rel
|
||||
if saved.is_file():
|
||||
target = path or (pfx / rel)
|
||||
os.replace(saved, target)
|
||||
restored += 1
|
||||
elif path is not None and not path.is_symlink():
|
||||
path.unlink()
|
||||
removed += 1
|
||||
if removed:
|
||||
# Proton refreshes its builtins only when its config changes; forgetting the config puts
|
||||
# its own DLLs back where ours were on the next launch - this one.
|
||||
try:
|
||||
(compat / "config_info").unlink()
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
compat.mkdir(parents=True, exist_ok=True)
|
||||
new_state = {"files": keep, "components": installed, "registry": state.get("registry", {})}
|
||||
written = 0
|
||||
if values or new_state["registry"]:
|
||||
written, registry_notes = apply_registry(pfx, values, new_state)
|
||||
notes += registry_notes
|
||||
save_state(compat, new_state)
|
||||
if copied or removed or restored or written:
|
||||
note = "components %s: %d file(s) placed, %d removed" % (",".join(ids) or "none", copied, removed)
|
||||
note += ", %d put back as they were" % restored if restored else ""
|
||||
notes.append(note + (", %d registry value(s) written" % written if written else ""))
|
||||
return overrides, notes
|
||||
|
||||
|
||||
def overrides_value(names):
|
||||
"""WINEDLLOVERRIDES entries: native-then-builtin unless the component says otherwise; the last word on a DLL wins."""
|
||||
modes = {}
|
||||
for entry in names:
|
||||
name, _, mode = entry.partition("=")
|
||||
name = name.strip().lower()
|
||||
if name and re.fullmatch(r"[a-z0-9._-]+", name) and re.fullmatch(r"[nb,]*", mode):
|
||||
modes.pop(name, None)
|
||||
modes[name] = mode if "=" in entry else "n,b"
|
||||
return ";".join("%s=%s" % item for item in modes.items())
|
||||
|
||||
|
||||
def main():
|
||||
# droiddeck-wincomponents <compatdata dir> <appid>: what a launch would do, for a shell.
|
||||
if len(sys.argv) != 3:
|
||||
print("usage: droiddeck-wincomponents <compatdata dir> <appid>", file=sys.stderr)
|
||||
return 2
|
||||
names, notes = apply(sys.argv[1], sys.argv[2])
|
||||
for note in notes:
|
||||
print(note)
|
||||
print("WINEDLLOVERRIDES=" + overrides_value(names))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,446 @@
|
||||
/*
|
||||
* The Steam client's directory listings on the SD library, kept in the process.
|
||||
*
|
||||
* Steam resolves every path case-insensitively. For each file it creates while it allocates an
|
||||
* install, it first checks the exact name with access() several times, then lists the file's
|
||||
* directory to look for a differently cased match, and only then creates it. On an SD card Android
|
||||
* serves the library through its FUSE daemon, where listing a directory costs 20-100 ms and each
|
||||
* failed access() 2-4 ms, so an install of a few thousand files spends many minutes in "Reserving
|
||||
* space" before any byte is downloaded. Measured on an AYN Thor, Portal 2 (3,698 files) listed
|
||||
* directories 11,712 times.
|
||||
*
|
||||
* Only the client writes into its library, so a listing it has read once stays true as long as the
|
||||
* client's own creates, renames and deletes are applied to it. Those are, and a listing also
|
||||
* expires after DIRCACHE_TTL_NS. The cache serves:
|
||||
* - readdir() of a directory listed before, from memory (opendir() still opens it for real);
|
||||
* - access() of a name absent from its directory's listing: ENOENT without a FUSE round trip.
|
||||
* Only absolute paths under the library's mount, only in the client. BL_NO_DIRCACHE=1 turns it off.
|
||||
*/
|
||||
#define _GNU_SOURCE
|
||||
#include <dirent.h>
|
||||
#include <dlfcn.h>
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <pthread.h>
|
||||
#include <stdint.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/stat.h>
|
||||
#include <time.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#define DIRCACHE_SLOTS 64
|
||||
#define DIRCACHE_TTL_NS 30000000000LL
|
||||
#define DIRCACHE_PATH_MAX 1024
|
||||
|
||||
struct name {
|
||||
unsigned char type;
|
||||
ino_t ino;
|
||||
char *name;
|
||||
};
|
||||
|
||||
struct listing {
|
||||
char path[DIRCACHE_PATH_MAX];
|
||||
long long expires;
|
||||
long long used;
|
||||
size_t count, capacity;
|
||||
struct name *names;
|
||||
};
|
||||
|
||||
/* One open DIR the cache serves or records. */
|
||||
struct reader {
|
||||
DIR *dir;
|
||||
char path[DIRCACHE_PATH_MAX];
|
||||
int serving; /* entries come from snapshot */
|
||||
size_t pos;
|
||||
size_t count;
|
||||
struct name *snapshot; /* serving: copy taken at opendir */
|
||||
int recording, broken; /* not serving: capture a full read */
|
||||
size_t capacity;
|
||||
struct dirent64 out;
|
||||
struct reader *next;
|
||||
};
|
||||
|
||||
static struct listing listings[DIRCACHE_SLOTS];
|
||||
static struct reader *readers;
|
||||
static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
|
||||
|
||||
void bl_meta_log(const char *op, int dirfd, const char *path, int flags, unsigned long long start, long result, int err)
|
||||
__attribute__((visibility("hidden")));
|
||||
unsigned long long bl_meta_now(void) __attribute__((visibility("hidden")));
|
||||
|
||||
static long long now_ns(void) {
|
||||
struct timespec t;
|
||||
clock_gettime(CLOCK_MONOTONIC_COARSE, &t);
|
||||
return (long long)t.tv_sec * 1000000000LL + t.tv_nsec;
|
||||
}
|
||||
|
||||
static int in_scope(const char *path) {
|
||||
static int on = -1;
|
||||
if (on < 0) {
|
||||
const char *off = getenv("BL_NO_DIRCACHE");
|
||||
on = strcmp(program_invocation_short_name, "steam") == 0 &&
|
||||
strstr(program_invocation_name, "steamrtarm64") != NULL && !(off && strcmp(off, "1") == 0);
|
||||
}
|
||||
if (!on || path == NULL || path[0] != '/') return 0;
|
||||
if (strlen(path) >= DIRCACHE_PATH_MAX) return 0;
|
||||
return strncmp(path, "/mnt/droiddeck-sd/", 18) == 0 || strcmp(path, "/mnt/droiddeck-sd") == 0 ||
|
||||
strncmp(path, "/mnt/bannerlator-sd/", 20) == 0 || strcmp(path, "/mnt/bannerlator-sd") == 0;
|
||||
}
|
||||
|
||||
/* "/a/b//c/" -> "/a/b/c"; refuses "." and ".." components. */
|
||||
static int normalize(const char *in, char *out) {
|
||||
size_t o = 0;
|
||||
for (const char *p = in; *p;) {
|
||||
while (*p == '/') p++;
|
||||
if (!*p) break;
|
||||
const char *end = strchr(p, '/');
|
||||
size_t len = end ? (size_t)(end - p) : strlen(p);
|
||||
if ((len == 1 && p[0] == '.') || (len == 2 && p[0] == '.' && p[1] == '.')) return 0;
|
||||
if (o + 1 + len >= DIRCACHE_PATH_MAX) return 0;
|
||||
out[o++] = '/';
|
||||
memcpy(out + o, p, len);
|
||||
o += len;
|
||||
p += len;
|
||||
}
|
||||
if (o == 0) out[o++] = '/';
|
||||
out[o] = '\0';
|
||||
return 1;
|
||||
}
|
||||
|
||||
static int split(const char *path, char *parent, const char **base) {
|
||||
if (!normalize(path, parent)) return 0;
|
||||
char *slash = strrchr(parent, '/');
|
||||
if (slash == NULL || slash[1] == '\0') return 0;
|
||||
*base = path + (strlen(path) - strlen(slash + 1));
|
||||
/* base must point at the normalized last component; recompute from parent copy */
|
||||
static __thread char last[DIRCACHE_PATH_MAX];
|
||||
strcpy(last, slash + 1);
|
||||
*base = last;
|
||||
if (slash == parent) slash[1] = '\0'; else *slash = '\0';
|
||||
return 1;
|
||||
}
|
||||
|
||||
static void drop(struct listing *l) {
|
||||
for (size_t i = 0; i < l->count; i++) free(l->names[i].name);
|
||||
free(l->names);
|
||||
memset(l, 0, sizeof(*l));
|
||||
}
|
||||
|
||||
static struct listing *find(const char *path, long long now) {
|
||||
for (int i = 0; i < DIRCACHE_SLOTS; i++) {
|
||||
struct listing *l = &listings[i];
|
||||
if (l->names == NULL && l->count == 0 && l->path[0] == '\0') continue;
|
||||
if (strcmp(l->path, path) != 0) continue;
|
||||
if (l->expires <= now) { drop(l); return NULL; }
|
||||
l->used = now;
|
||||
return l;
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static ssize_t index_of(struct listing *l, const char *name) {
|
||||
for (size_t i = 0; i < l->count; i++)
|
||||
if (strcmp(l->names[i].name, name) == 0) return (ssize_t)i;
|
||||
return -1;
|
||||
}
|
||||
|
||||
static void add_name(struct listing *l, const char *name, unsigned char type, ino_t ino) {
|
||||
if (index_of(l, name) >= 0) return;
|
||||
if (l->count == l->capacity) {
|
||||
size_t cap = l->capacity ? l->capacity * 2 : 32;
|
||||
struct name *grown = realloc(l->names, cap * sizeof(*grown));
|
||||
if (grown == NULL) { drop(l); return; }
|
||||
l->names = grown;
|
||||
l->capacity = cap;
|
||||
}
|
||||
char *copy = strdup(name);
|
||||
if (copy == NULL) { drop(l); return; }
|
||||
l->names[l->count++] = (struct name){type, ino, copy};
|
||||
}
|
||||
|
||||
static void remove_name(struct listing *l, const char *name) {
|
||||
ssize_t i = index_of(l, name);
|
||||
if (i < 0) return;
|
||||
free(l->names[i].name);
|
||||
l->names[i] = l->names[--l->count];
|
||||
}
|
||||
|
||||
static int in_scope(const char *path);
|
||||
|
||||
/* A change the cache can't place (a relative path): no listing can be trusted after it. */
|
||||
static void forget_all(void) {
|
||||
if (!in_scope("/mnt/droiddeck-sd")) return;
|
||||
pthread_mutex_lock(&lock);
|
||||
for (int i = 0; i < DIRCACHE_SLOTS; i++) drop(&listings[i]);
|
||||
pthread_mutex_unlock(&lock);
|
||||
}
|
||||
|
||||
/* The client's own change to a directory, applied to its listing when one is cached. */
|
||||
static void note(const char *path, int added, unsigned char type) {
|
||||
char parent[DIRCACHE_PATH_MAX];
|
||||
const char *base;
|
||||
if (path != NULL && path[0] != '/') { forget_all(); return; }
|
||||
if (!in_scope(path) || !split(path, parent, &base)) return;
|
||||
pthread_mutex_lock(&lock);
|
||||
struct listing *l = find(parent, now_ns());
|
||||
if (l) {
|
||||
if (added) add_name(l, base, type, 0);
|
||||
else remove_name(l, base);
|
||||
}
|
||||
if (!added && type == DT_DIR) {
|
||||
char self[DIRCACHE_PATH_MAX];
|
||||
if (normalize(path, self)) {
|
||||
size_t n = strlen(self);
|
||||
for (int i = 0; i < DIRCACHE_SLOTS; i++)
|
||||
if (strncmp(listings[i].path, self, n) == 0 && (listings[i].path[n] == '\0' || listings[i].path[n] == '/'))
|
||||
drop(&listings[i]);
|
||||
}
|
||||
}
|
||||
pthread_mutex_unlock(&lock);
|
||||
}
|
||||
|
||||
void bl_dircache_created(const char *path) __attribute__((visibility("hidden")));
|
||||
void bl_dircache_created(const char *path) { note(path, 1, DT_REG); }
|
||||
|
||||
/* 1: the path is known not to exist (errno set to ENOENT); 0: ask the filesystem. */
|
||||
int bl_dircache_absent(const char *path) __attribute__((visibility("hidden")));
|
||||
int bl_dircache_absent(const char *path) {
|
||||
char parent[DIRCACHE_PATH_MAX];
|
||||
const char *base;
|
||||
if (!in_scope(path) || !split(path, parent, &base)) return 0;
|
||||
int absent = 0;
|
||||
pthread_mutex_lock(&lock);
|
||||
struct listing *l = find(parent, now_ns());
|
||||
if (l && index_of(l, base) < 0) absent = 1;
|
||||
pthread_mutex_unlock(&lock);
|
||||
if (absent) errno = ENOENT;
|
||||
return absent;
|
||||
}
|
||||
|
||||
static struct reader *reader_of(DIR *d) {
|
||||
for (struct reader *r = readers; r; r = r->next)
|
||||
if (r->dir == d) return r;
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static void store_listing(struct reader *r) {
|
||||
long long now = now_ns();
|
||||
struct listing *slot = NULL;
|
||||
for (int i = 0; i < DIRCACHE_SLOTS; i++) {
|
||||
struct listing *l = &listings[i];
|
||||
if (strcmp(l->path, r->path) == 0) { slot = l; break; }
|
||||
}
|
||||
if (slot == NULL) {
|
||||
for (int i = 0; i < DIRCACHE_SLOTS; i++) {
|
||||
struct listing *l = &listings[i];
|
||||
if (l->path[0] == '\0' || l->expires <= now) { slot = l; break; }
|
||||
if (slot == NULL || l->used < slot->used) slot = l;
|
||||
}
|
||||
}
|
||||
drop(slot);
|
||||
strcpy(slot->path, r->path);
|
||||
slot->names = r->snapshot;
|
||||
slot->count = slot->capacity = r->count;
|
||||
slot->expires = now + DIRCACHE_TTL_NS;
|
||||
slot->used = now;
|
||||
r->snapshot = NULL;
|
||||
r->count = 0;
|
||||
}
|
||||
|
||||
static void free_reader(struct reader *r) {
|
||||
if (r->snapshot) {
|
||||
for (size_t i = 0; i < r->count; i++) free(r->snapshot[i].name);
|
||||
free(r->snapshot);
|
||||
}
|
||||
free(r);
|
||||
}
|
||||
|
||||
DIR *opendir(const char *path) {
|
||||
static DIR *(*real)(const char *);
|
||||
if (real == NULL) real = dlsym(RTLD_NEXT, "opendir");
|
||||
unsigned long long t0 = bl_meta_now();
|
||||
DIR *d = real(path);
|
||||
int e = errno;
|
||||
bl_meta_log("opendir", -100, path, 0, t0, d ? 0 : -1, e);
|
||||
if (d == NULL || !in_scope(path)) { errno = e; return d; }
|
||||
struct reader *r = calloc(1, sizeof(*r));
|
||||
if (r == NULL || !normalize(path, r->path)) { free(r); errno = e; return d; }
|
||||
r->dir = d;
|
||||
pthread_mutex_lock(&lock);
|
||||
struct listing *l = find(r->path, now_ns());
|
||||
if (l) {
|
||||
r->snapshot = calloc(l->count ? l->count : 1, sizeof(struct name));
|
||||
if (r->snapshot) {
|
||||
r->serving = 1;
|
||||
for (size_t i = 0; i < l->count; i++) {
|
||||
r->snapshot[i] = l->names[i];
|
||||
r->snapshot[i].name = strdup(l->names[i].name);
|
||||
if (r->snapshot[i].name == NULL) { r->serving = 0; break; }
|
||||
r->count = i + 1;
|
||||
}
|
||||
if (!r->serving) { for (size_t i = 0; i < r->count; i++) free(r->snapshot[i].name); free(r->snapshot); r->snapshot = NULL; r->count = 0; }
|
||||
}
|
||||
}
|
||||
if (!r->serving) r->recording = 1;
|
||||
r->next = readers;
|
||||
readers = r;
|
||||
pthread_mutex_unlock(&lock);
|
||||
errno = e;
|
||||
return d;
|
||||
}
|
||||
|
||||
struct dirent64 *readdir64(DIR *d) {
|
||||
static struct dirent64 *(*real)(DIR *);
|
||||
if (real == NULL) real = dlsym(RTLD_NEXT, "readdir64");
|
||||
pthread_mutex_lock(&lock);
|
||||
struct reader *r = reader_of(d);
|
||||
if (r && r->serving) {
|
||||
/* "." and ".." first, as the filesystem lists them. */
|
||||
struct dirent64 *out = &r->out;
|
||||
memset(out, 0, sizeof(*out));
|
||||
size_t total = r->count + 2;
|
||||
if (r->pos >= total) { pthread_mutex_unlock(&lock); return NULL; }
|
||||
if (r->pos < 2) {
|
||||
strcpy(out->d_name, r->pos == 0 ? "." : "..");
|
||||
out->d_type = DT_DIR;
|
||||
out->d_ino = 1;
|
||||
} else {
|
||||
struct name *n = &r->snapshot[r->pos - 2];
|
||||
strncpy(out->d_name, n->name, sizeof(out->d_name) - 1);
|
||||
out->d_type = n->type;
|
||||
out->d_ino = n->ino ? n->ino : 2 + r->pos;
|
||||
}
|
||||
r->pos++;
|
||||
out->d_off = (off_t)r->pos;
|
||||
out->d_reclen = sizeof(*out);
|
||||
pthread_mutex_unlock(&lock);
|
||||
return out;
|
||||
}
|
||||
pthread_mutex_unlock(&lock);
|
||||
int entry_errno = errno;
|
||||
errno = 0; /* the end of a listing leaves errno alone; a failure sets it */
|
||||
struct dirent64 *e = real(d);
|
||||
int err = errno;
|
||||
pthread_mutex_lock(&lock);
|
||||
r = reader_of(d);
|
||||
if (r && r->recording && !r->broken) {
|
||||
if (e == NULL) {
|
||||
if (err == 0) store_listing(r);
|
||||
r->recording = 0;
|
||||
} else if (strcmp(e->d_name, ".") != 0 && strcmp(e->d_name, "..") != 0) {
|
||||
if (r->count == r->capacity) {
|
||||
size_t cap = r->capacity ? r->capacity * 2 : 32;
|
||||
struct name *grown = realloc(r->snapshot, cap * sizeof(*grown));
|
||||
if (grown == NULL) r->broken = 1;
|
||||
else { r->snapshot = grown; r->capacity = cap; }
|
||||
}
|
||||
if (!r->broken) {
|
||||
char *copy = strdup(e->d_name);
|
||||
if (copy == NULL) r->broken = 1;
|
||||
else r->snapshot[r->count++] = (struct name){e->d_type, e->d_ino, copy};
|
||||
}
|
||||
}
|
||||
}
|
||||
pthread_mutex_unlock(&lock);
|
||||
errno = err == 0 ? entry_errno : err;
|
||||
return e;
|
||||
}
|
||||
struct dirent *readdir(DIR *d) __attribute__((alias("readdir64")));
|
||||
|
||||
int closedir(DIR *d) {
|
||||
static int (*real)(DIR *);
|
||||
if (real == NULL) real = dlsym(RTLD_NEXT, "closedir");
|
||||
pthread_mutex_lock(&lock);
|
||||
for (struct reader **link = &readers; *link; link = &(*link)->next) {
|
||||
if ((*link)->dir == d) {
|
||||
struct reader *r = *link;
|
||||
*link = r->next;
|
||||
free_reader(r);
|
||||
break;
|
||||
}
|
||||
}
|
||||
pthread_mutex_unlock(&lock);
|
||||
return real(d);
|
||||
}
|
||||
|
||||
void rewinddir(DIR *d) {
|
||||
static void (*real)(DIR *);
|
||||
if (real == NULL) real = dlsym(RTLD_NEXT, "rewinddir");
|
||||
pthread_mutex_lock(&lock);
|
||||
struct reader *r = reader_of(d);
|
||||
if (r) {
|
||||
if (r->serving) r->pos = 0;
|
||||
else r->broken = 1; /* a partial recording can't be trusted */
|
||||
}
|
||||
pthread_mutex_unlock(&lock);
|
||||
real(d);
|
||||
}
|
||||
|
||||
/* Positions in a served listing are ours; a recording stops being trusted once the caller seeks. */
|
||||
long telldir(DIR *d) {
|
||||
static long (*real)(DIR *);
|
||||
if (real == NULL) real = dlsym(RTLD_NEXT, "telldir");
|
||||
pthread_mutex_lock(&lock);
|
||||
struct reader *r = reader_of(d);
|
||||
long pos = r && r->serving ? (long)r->pos : -2;
|
||||
pthread_mutex_unlock(&lock);
|
||||
return pos != -2 ? pos : real(d);
|
||||
}
|
||||
|
||||
void seekdir(DIR *d, long pos) {
|
||||
static void (*real)(DIR *, long);
|
||||
if (real == NULL) real = dlsym(RTLD_NEXT, "seekdir");
|
||||
pthread_mutex_lock(&lock);
|
||||
struct reader *r = reader_of(d);
|
||||
if (r && r->serving) { r->pos = pos < 0 ? 0 : (size_t)pos; pthread_mutex_unlock(&lock); return; }
|
||||
if (r) r->broken = 1;
|
||||
pthread_mutex_unlock(&lock);
|
||||
real(d, pos);
|
||||
}
|
||||
|
||||
#define MUTATE(name, sig, args, path, after) \
|
||||
int name sig { \
|
||||
static int (*real) sig; \
|
||||
if (real == NULL) real = dlsym(RTLD_NEXT, #name); \
|
||||
int r = real args; \
|
||||
int e = errno; \
|
||||
if (r == 0) { after; } \
|
||||
errno = e; \
|
||||
return r; \
|
||||
}
|
||||
|
||||
MUTATE(mkdir, (const char *p, mode_t m), (p, m), p, note(p, 1, DT_DIR))
|
||||
MUTATE(unlink, (const char *p), (p), p, note(p, 0, DT_REG))
|
||||
MUTATE(rmdir, (const char *p), (p), p, note(p, 0, DT_DIR))
|
||||
MUTATE(rename, (const char *a, const char *b), (a, b), a, { note(a, 0, DT_DIR); note(b, 0, DT_DIR); note(b, 1, DT_UNKNOWN); })
|
||||
|
||||
|
||||
#define MUTATE_AT(name, sig, args) \
|
||||
int name sig { \
|
||||
static int (*real) sig; \
|
||||
if (real == NULL) real = dlsym(RTLD_NEXT, #name); \
|
||||
int r = real args; \
|
||||
int e = errno; \
|
||||
if (r == 0) forget_all(); \
|
||||
errno = e; \
|
||||
return r; \
|
||||
}
|
||||
|
||||
MUTATE_AT(mkdirat, (int d, const char *p, mode_t m), (d, p, m))
|
||||
MUTATE_AT(unlinkat, (int d, const char *p, int f), (d, p, f))
|
||||
MUTATE_AT(renameat, (int a, const char *p, int b, const char *q), (a, p, b, q))
|
||||
MUTATE_AT(renameat2, (int a, const char *p, int b, const char *q, unsigned f), (a, p, b, q, f))
|
||||
MUTATE_AT(linkat, (int a, const char *p, int b, const char *q, int f), (a, p, b, q, f))
|
||||
MUTATE_AT(symlinkat, (const char *t, int d, const char *p), (t, d, p))
|
||||
MUTATE(link, (const char *a, const char *b), (a, b), b, note(b, 1, DT_UNKNOWN))
|
||||
MUTATE(symlink, (const char *a, const char *b), (a, b), b, note(b, 1, DT_LNK))
|
||||
int creat(const char *p, mode_t m) {
|
||||
static int (*real)(const char *, mode_t);
|
||||
if (real == NULL) real = dlsym(RTLD_NEXT, "creat");
|
||||
int fd = real(p, m);
|
||||
int e = errno;
|
||||
if (fd >= 0) note(p, 1, DT_REG);
|
||||
errno = e;
|
||||
return fd;
|
||||
}
|
||||
+96
-27
@@ -14,6 +14,7 @@
|
||||
#include <stdlib.h>
|
||||
#include <sys/ioctl.h>
|
||||
#include <sys/stat.h>
|
||||
#include <sys/syscall.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#define MAX_HANDLES 4096
|
||||
@@ -25,8 +26,15 @@ struct gem_close {
|
||||
};
|
||||
#define GEM_CLOSE _IOW('d', 0x09, struct gem_close)
|
||||
|
||||
struct handle_entry {
|
||||
uint32_t handle;
|
||||
int dma_fd;
|
||||
int drm_fd;
|
||||
};
|
||||
|
||||
static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
|
||||
static int handle_fds[MAX_HANDLES];
|
||||
static struct handle_entry handle_entries[MAX_HANDLES];
|
||||
static uint32_t next_handle = 1;
|
||||
static dev_t kgsl_dev;
|
||||
static int kgsl_state; /* 0 unknown, 1 known, -1 absent */
|
||||
|
||||
@@ -49,6 +57,58 @@ static void *real(const char *name) {
|
||||
return fn;
|
||||
}
|
||||
|
||||
static int same_file_description(int a, int b) {
|
||||
if (a == b) {
|
||||
return 1;
|
||||
}
|
||||
#ifdef SYS_kcmp
|
||||
int saved_errno = errno;
|
||||
long ret = syscall(SYS_kcmp, getpid(), getpid(), 0 /* KCMP_FILE */, a, b);
|
||||
errno = saved_errno;
|
||||
return ret == 0;
|
||||
#else
|
||||
return 0;
|
||||
#endif
|
||||
}
|
||||
|
||||
static int find_handle_locked(int fd, uint32_t handle) {
|
||||
for (int i = 0; i < MAX_HANDLES; i++) {
|
||||
if (handle_entries[i].handle == handle &&
|
||||
same_file_description(handle_entries[i].drm_fd, fd)) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
/*
|
||||
* The old table used its slot index as the public handle. Once #275 started freeing slots,
|
||||
* rapidly recreated swapchains immediately reused those numbers. Keep storage slots reusable but
|
||||
* make the public token monotonic so a stale handle can fail instead of aliasing a newer buffer.
|
||||
*/
|
||||
static uint32_t alloc_handle_locked(void) {
|
||||
for (int tries = 0; tries <= MAX_HANDLES; tries++) {
|
||||
uint32_t candidate = next_handle++;
|
||||
if (next_handle == 0) {
|
||||
next_handle = 1;
|
||||
}
|
||||
if (candidate == 0) {
|
||||
continue;
|
||||
}
|
||||
int used = 0;
|
||||
for (int i = 0; i < MAX_HANDLES; i++) {
|
||||
if (handle_entries[i].handle == candidate) {
|
||||
used = 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!used) {
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
int drmPrimeFDToHandle(int fd, int prime_fd, uint32_t *handle) {
|
||||
if (!is_kgsl(fd)) {
|
||||
int (*fn)(int, int, uint32_t *) = (int (*)(int, int, uint32_t *)) real("drmPrimeFDToHandle");
|
||||
@@ -60,10 +120,16 @@ int drmPrimeFDToHandle(int fd, int prime_fd, uint32_t *handle) {
|
||||
}
|
||||
int ret = -ENOMEM;
|
||||
pthread_mutex_lock(&lock);
|
||||
for (uint32_t i = 1; i < MAX_HANDLES; i++) {
|
||||
if (handle_fds[i] == 0) {
|
||||
handle_fds[i] = dup_fd;
|
||||
*handle = i;
|
||||
for (int i = 0; i < MAX_HANDLES; i++) {
|
||||
if (handle_entries[i].handle == 0) {
|
||||
uint32_t token = alloc_handle_locked();
|
||||
if (!token) {
|
||||
break;
|
||||
}
|
||||
handle_entries[i].handle = token;
|
||||
handle_entries[i].dma_fd = dup_fd;
|
||||
handle_entries[i].drm_fd = fd;
|
||||
*handle = token;
|
||||
ret = 0;
|
||||
break;
|
||||
}
|
||||
@@ -82,21 +148,23 @@ int drmPrimeHandleToFD(int fd, uint32_t handle, uint32_t flags, int *prime_fd) {
|
||||
}
|
||||
int ret = -EINVAL;
|
||||
pthread_mutex_lock(&lock);
|
||||
if (handle > 0 && handle < MAX_HANDLES && handle_fds[handle] > 0) {
|
||||
*prime_fd = fcntl(handle_fds[handle], F_DUPFD_CLOEXEC, 0);
|
||||
int index = find_handle_locked(fd, handle);
|
||||
if (index >= 0) {
|
||||
*prime_fd = fcntl(handle_entries[index].dma_fd, F_DUPFD_CLOEXEC, 0);
|
||||
ret = *prime_fd < 0 ? -errno : 0;
|
||||
}
|
||||
pthread_mutex_unlock(&lock);
|
||||
return ret;
|
||||
}
|
||||
|
||||
/* Drops a handle's descriptor; false when the handle was never given out. */
|
||||
static int release_handle(uint32_t handle) {
|
||||
/* Drops only a handle belonging to this KGSL file description. */
|
||||
static int release_handle(int fd, uint32_t handle) {
|
||||
int found = 0;
|
||||
pthread_mutex_lock(&lock);
|
||||
if (handle > 0 && handle < MAX_HANDLES && handle_fds[handle] > 0) {
|
||||
close(handle_fds[handle]);
|
||||
handle_fds[handle] = 0;
|
||||
int index = find_handle_locked(fd, handle);
|
||||
if (index >= 0) {
|
||||
close(handle_entries[index].dma_fd);
|
||||
handle_entries[index] = (struct handle_entry){0};
|
||||
found = 1;
|
||||
}
|
||||
pthread_mutex_unlock(&lock);
|
||||
@@ -108,29 +176,30 @@ int drmCloseBufferHandle(int fd, uint32_t handle) {
|
||||
int (*fn)(int, uint32_t) = (int (*)(int, uint32_t)) real("drmCloseBufferHandle");
|
||||
return fn ? fn(fd, handle) : -ENOSYS;
|
||||
}
|
||||
return release_handle(handle) ? 0 : -EINVAL;
|
||||
return release_handle(fd, handle) ? 0 : -EINVAL;
|
||||
}
|
||||
|
||||
/*
|
||||
* Zink gives its handles back with the GEM_CLOSE ioctl itself, not drmCloseBufferHandle
|
||||
* (zink_bo.c, bo_destroy). KGSL refuses the ioctl, so the duplicated descriptor stayed open and
|
||||
* kept the whole buffer alive: Xwayland asks for a handle for every buffer it imports, and a game
|
||||
* whose swapchain was recreated on each resize piled up gigabytes of old swapchain images until
|
||||
* Android killed the session.
|
||||
* kept the whole buffer alive. Preserve #275's reclamation without letting another KGSL file
|
||||
* description release the token or making a new buffer immediately inherit a retired token.
|
||||
*
|
||||
* Caught at ioctl() (netif.c), which libdrm's drmIoctl calls, rather than by exporting drmIoctl:
|
||||
* every session process preloads this library, and exporting drmIoctl from it brought on a
|
||||
* judder replaying old frames in No Man's Sky on an Adreno 840 even with no handle released.
|
||||
*/
|
||||
int drmIoctl(int fd, unsigned long request, void *arg) {
|
||||
if (request == GEM_CLOSE && arg && is_kgsl(fd)) {
|
||||
if (release_handle(((struct gem_close *) arg)->handle)) {
|
||||
return 0;
|
||||
}
|
||||
__attribute__((visibility("hidden"))) int bl_drm_gem_close(int fd, unsigned long request, void *arg, int *rc) {
|
||||
if (request != GEM_CLOSE || !arg || !is_kgsl(fd)) {
|
||||
return 0;
|
||||
}
|
||||
if (release_handle(fd, ((struct gem_close *) arg)->handle)) {
|
||||
*rc = 0;
|
||||
} else {
|
||||
errno = EINVAL;
|
||||
return -1;
|
||||
*rc = -1;
|
||||
}
|
||||
int (*fn)(int, unsigned long, void *) = (int (*)(int, unsigned long, void *)) real("drmIoctl");
|
||||
if (!fn) {
|
||||
return -1;
|
||||
}
|
||||
return fn(fd, request, arg);
|
||||
return 1;
|
||||
}
|
||||
|
||||
/*
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
/*
|
||||
* EXPERIMENT: per-call log of the Steam client's metadata calls on library paths, to find what
|
||||
* dominates its allocation phase on a FUSE-served SD library. On only while
|
||||
* /root/.droiddeck-metaprof exists; lines go to /tmp/bl-meta.log.
|
||||
*/
|
||||
#define _GNU_SOURCE
|
||||
#include <dirent.h>
|
||||
#include <dlfcn.h>
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <sys/stat.h>
|
||||
#include <sys/syscall.h>
|
||||
#include <time.h>
|
||||
#include <unistd.h>
|
||||
|
||||
static int prof_state = -1;
|
||||
static volatile unsigned long prof_lines;
|
||||
|
||||
uint64_t bl_meta_now(void) __attribute__((visibility("hidden")));
|
||||
uint64_t bl_meta_now(void) {
|
||||
struct timespec ts;
|
||||
clock_gettime(CLOCK_MONOTONIC, &ts);
|
||||
return (uint64_t)ts.tv_sec * 1000000000ULL + (uint64_t)ts.tv_nsec;
|
||||
}
|
||||
|
||||
int bl_meta_on(void) __attribute__((visibility("hidden")));
|
||||
int bl_meta_on(void) {
|
||||
if (prof_state < 0) {
|
||||
struct stat st;
|
||||
prof_state = strcmp(program_invocation_short_name, "steam") == 0 &&
|
||||
syscall(SYS_newfstatat, AT_FDCWD, "/root/.droiddeck-metaprof", &st, 0) == 0;
|
||||
}
|
||||
return prof_state;
|
||||
}
|
||||
|
||||
void bl_meta_log(const char *op, int dirfd, const char *path, int flags, uint64_t start, long result, int err)
|
||||
__attribute__((visibility("hidden")));
|
||||
void bl_meta_log(const char *op, int dirfd, const char *path, int flags, uint64_t start, long result, int err) {
|
||||
if (!bl_meta_on() || path == NULL) return;
|
||||
if (path[0] == '/' && strstr(path, "steamapps") == NULL && strstr(path, "droiddeck-sd") == NULL) return;
|
||||
if (__atomic_add_fetch(&prof_lines, 1, __ATOMIC_RELAXED) > 400000) return;
|
||||
uint64_t end = bl_meta_now();
|
||||
char line[768];
|
||||
int n = snprintf(line, sizeof(line), "%llu %ld %s fd=%d fl=0x%x us=%llu r=%ld e=%d %s\n",
|
||||
(unsigned long long)(end / 1000000ULL), (long)syscall(SYS_gettid), op, dirfd, flags,
|
||||
(unsigned long long)((end - start) / 1000ULL), result, result < 0 ? err : 0, path);
|
||||
if (n <= 0 || (size_t)n >= sizeof(line)) return;
|
||||
int fd = (int)syscall(SYS_openat, AT_FDCWD, "/tmp/bl-meta.log", O_WRONLY | O_CREAT | O_APPEND | O_CLOEXEC, 0600);
|
||||
if (fd < 0) return;
|
||||
syscall(SYS_write, fd, line, n);
|
||||
syscall(SYS_close, fd);
|
||||
}
|
||||
|
||||
#define WRAP_PATH(name, ret, sig, args, dirfd, path, flags) \
|
||||
ret name sig { \
|
||||
static ret (*real) sig; \
|
||||
if (real == NULL) real = dlsym(RTLD_NEXT, #name); \
|
||||
if (!bl_meta_on()) return real args; \
|
||||
uint64_t t0 = bl_meta_now(); \
|
||||
ret r = real args; \
|
||||
int e = errno; \
|
||||
bl_meta_log(#name, dirfd, path, flags, t0, (long)(r), e); \
|
||||
errno = e; \
|
||||
return r; \
|
||||
}
|
||||
|
||||
WRAP_PATH(stat, int, (const char *p, struct stat *s), (p, s), -100, p, 0)
|
||||
WRAP_PATH(lstat, int, (const char *p, struct stat *s), (p, s), -100, p, 0)
|
||||
WRAP_PATH(fstatat, int, (int d, const char *p, struct stat *s, int f), (d, p, s, f), d, p, f)
|
||||
WRAP_PATH(statx, int, (int d, const char *p, int f, unsigned m, struct statx *s), (d, p, f, m, s), d, p, f)
|
||||
|
||||
int stat64(const char *p, struct stat64 *s) __attribute__((alias("stat")));
|
||||
int lstat64(const char *p, struct stat64 *s) __attribute__((alias("lstat")));
|
||||
int fstatat64(int d, const char *p, struct stat64 *s, int f) __attribute__((alias("fstatat")));
|
||||
@@ -30,6 +30,8 @@
|
||||
#include <sys/socket.h>
|
||||
#include <unistd.h>
|
||||
|
||||
void bl_dircache_created(const char *path) __attribute__((visibility("hidden")));
|
||||
|
||||
#define LINK_FILE "/etc/droiddeck-net"
|
||||
#define LO_NAME "lo"
|
||||
#define LO_INDEX 1
|
||||
@@ -353,6 +355,7 @@ void bl_kgsl_chip_id_fixup(unsigned long request, void *arg, int rc); /* kgslid.
|
||||
int bl_kgsl_poll(int (*real)(int, unsigned long, void *), int fd, unsigned long request,
|
||||
void *arg, int *rc) __attribute__((visibility("hidden")));
|
||||
int bl_ntsync_ioctl(int fd, unsigned long request, void *arg, int *rc) __attribute__((visibility("hidden")));
|
||||
int bl_drm_gem_close(int fd, unsigned long request, void *arg, int *rc) __attribute__((visibility("hidden")));
|
||||
|
||||
/* Every DRM and evdev call comes through here, so the lookup is done once. Two threads racing
|
||||
* to store it store the same pointer. */
|
||||
@@ -366,6 +369,7 @@ int ioctl(int fd, unsigned long request, ...) {
|
||||
|
||||
int rc;
|
||||
if (bl_ntsync_ioctl(fd, request, arg, &rc)) return rc;
|
||||
if (bl_drm_gem_close(fd, request, arg, &rc)) return rc;
|
||||
if (real == NULL) real = (ioctl_fn) dlsym(RTLD_NEXT, "ioctl");
|
||||
if (!bl_kgsl_poll(real, fd, request, arg, &rc)) rc = real(fd, request, arg);
|
||||
bl_kgsl_chip_id_fixup(request, arg, rc);
|
||||
@@ -497,6 +501,7 @@ static FILE *open_stream(const char *symbol, const char *path, const char *mode)
|
||||
return copy;
|
||||
}
|
||||
FILE *f = ((fopen_fn) dlsym(RTLD_NEXT, symbol))(path, mode);
|
||||
if (f && mode != NULL && mode[0] != 'r') bl_dircache_created(path);
|
||||
if (f || path == NULL || mode == NULL || mode[0] != 'r') return f;
|
||||
int saved = errno;
|
||||
const char *table = denied_table(path);
|
||||
|
||||
@@ -1250,12 +1250,22 @@ ssize_t recvmsg(int fd, struct msghdr *msg, int flags) {
|
||||
}
|
||||
|
||||
void bl_fsync_fds_closed(unsigned int first, unsigned int last) __attribute__((visibility("hidden")));
|
||||
int bl_meta_on(void) __attribute__((visibility("hidden")));
|
||||
uint64_t bl_meta_now(void) __attribute__((visibility("hidden")));
|
||||
void bl_meta_log(const char *op, int dirfd, const char *path, int flags, uint64_t start, long result, int err)
|
||||
__attribute__((visibility("hidden")));
|
||||
|
||||
int close(int fd) {
|
||||
if (fd >= 0) bl_fsync_fds_closed((unsigned int)fd, (unsigned int)fd);
|
||||
uint64_t *t = __atomic_load_n(&ns_fdt, __ATOMIC_ACQUIRE);
|
||||
if (t && fd >= 0 && fd < NS_FDS && __atomic_load_n(&t[fd], __ATOMIC_ACQUIRE)) ns_forget(fd);
|
||||
return ns_close_fd(fd);
|
||||
if (!bl_meta_on()) return ns_close_fd(fd);
|
||||
uint64_t t0 = bl_meta_now();
|
||||
int r = ns_close_fd(fd);
|
||||
int e = errno;
|
||||
if (bl_meta_now() - t0 > 1000000ULL) bl_meta_log("close", fd, "/steamapps/(slow close)", 0, t0, r, e);
|
||||
errno = e;
|
||||
return r;
|
||||
}
|
||||
|
||||
int dup2(int oldfd, int newfd) {
|
||||
|
||||
@@ -36,6 +36,10 @@
|
||||
int bl_status_without_tracer(const char *path, int flags) __attribute__((visibility("hidden")));
|
||||
int bl_writable_retry(int dirfd, const char *path, int flags) __attribute__((visibility("hidden")));
|
||||
int bl_ntsync_open(const char *path, int flags) __attribute__((visibility("hidden")));
|
||||
void bl_dircache_created(const char *path) __attribute__((visibility("hidden")));
|
||||
unsigned long long bl_meta_now(void) __attribute__((visibility("hidden")));
|
||||
void bl_meta_log(const char *op, int dirfd, const char *path, int flags, unsigned long long start, long result, int err)
|
||||
__attribute__((visibility("hidden")));
|
||||
|
||||
static int retry_without_noatime(int fd, int flags) {
|
||||
return fd < 0 && errno == EPERM && (flags & O_NOATIME);
|
||||
@@ -68,10 +72,13 @@ int open(const char *path, int flags, ...) {
|
||||
errno = ENOSYS;
|
||||
return -1;
|
||||
}
|
||||
unsigned long long t0 = bl_meta_now();
|
||||
fd = real_open(path, flags, mode);
|
||||
bl_meta_log("open", -100, path, flags, t0, fd, errno);
|
||||
if (retry_without_noatime(fd, flags)) fd = real_open(path, flags & ~O_NOATIME, mode);
|
||||
/* A read-only file the Steam client rewrites (perms.c). */
|
||||
if (fd < 0 && bl_writable_retry(AT_FDCWD, path, flags)) fd = real_open(path, flags & ~O_NOATIME, mode);
|
||||
if (fd >= 0 && (flags & O_CREAT)) bl_dircache_created(path);
|
||||
return fd;
|
||||
}
|
||||
|
||||
@@ -95,9 +102,12 @@ int openat(int dirfd, const char *path, int flags, ...) {
|
||||
errno = ENOSYS;
|
||||
return -1;
|
||||
}
|
||||
unsigned long long t0 = bl_meta_now();
|
||||
fd = real_openat(dirfd, path, flags, mode);
|
||||
bl_meta_log("openat", dirfd, path, flags, t0, fd, errno);
|
||||
if (retry_without_noatime(fd, flags)) fd = real_openat(dirfd, path, flags & ~O_NOATIME, mode);
|
||||
if (fd < 0 && bl_writable_retry(dirfd, path, flags)) fd = real_openat(dirfd, path, flags & ~O_NOATIME, mode);
|
||||
if (fd >= 0 && (flags & O_CREAT)) bl_dircache_created(path);
|
||||
return fd;
|
||||
}
|
||||
|
||||
|
||||
@@ -125,18 +125,33 @@ char *bl_cached_realpath(const char *path, char *resolved, char *(*real)(const c
|
||||
return strdup(out);
|
||||
}
|
||||
|
||||
unsigned long long bl_meta_now(void) __attribute__((visibility("hidden")));
|
||||
void bl_meta_log(const char *op, int dirfd, const char *path, int flags, unsigned long long start, long result, int err)
|
||||
__attribute__((visibility("hidden")));
|
||||
|
||||
int bl_dircache_absent(const char *path) __attribute__((visibility("hidden")));
|
||||
|
||||
static int cached_access(const char *path, int mode, int flags, int (*check)(const char *, int, int)) {
|
||||
unsigned h;
|
||||
int hit;
|
||||
int result;
|
||||
|
||||
if (!cacheable(path)) return check(path, mode, flags);
|
||||
if (path != NULL && path[0] == '/' && bl_dircache_absent(path)) return -1;
|
||||
|
||||
if (!cacheable(path)) {
|
||||
unsigned long long t0 = bl_meta_now();
|
||||
result = check(path, mode, flags);
|
||||
bl_meta_log("access", -100, path, mode, t0, result, errno);
|
||||
return result;
|
||||
}
|
||||
h = hash_of(path, KIND_ACCESS, mode, flags);
|
||||
pthread_mutex_lock(&lock);
|
||||
hit = find(path, KIND_ACCESS, mode, flags, h) != NULL;
|
||||
pthread_mutex_unlock(&lock);
|
||||
if (hit) return 0;
|
||||
unsigned long long t0 = bl_meta_now();
|
||||
result = check(path, mode, flags);
|
||||
bl_meta_log("access", -100, path, mode, t0, result, errno);
|
||||
if (result == 0) {
|
||||
pthread_mutex_lock(&lock);
|
||||
store(path, KIND_ACCESS, mode, flags, h, NULL);
|
||||
|
||||
+115
-12
@@ -7,6 +7,12 @@
|
||||
* each process, allocation details are capped, writes are sampled, and storage.log has a global
|
||||
* size limit because every Steam child shares it.
|
||||
*
|
||||
* One deliberate exception: when the user opts to skip space reservation, plain reservation
|
||||
* requests on the selected library report success without touching the file. On a portable SD
|
||||
* card Steam's reservation goes through Android's FUSE layer and can take tens of minutes; with it
|
||||
* skipped Steam goes straight to downloading, and a full card shows up as a write error during the
|
||||
* download rather than up front.
|
||||
*
|
||||
* LD_PRELOAD cannot see direct syscalls or libc-internal calls that bypass public symbols. A
|
||||
* missing entry therefore does not prove the operation did not happen.
|
||||
*/
|
||||
@@ -45,6 +51,8 @@ static volatile unsigned int alloc_details;
|
||||
static long long selected_device;
|
||||
static int init_state;
|
||||
static int enabled;
|
||||
static int device_valid;
|
||||
static int skip_preallocation;
|
||||
|
||||
static uint64_t add(volatile uint64_t *slot, uint64_t value) {
|
||||
return __atomic_add_fetch(slot, value, __ATOMIC_RELAXED);
|
||||
@@ -71,14 +79,17 @@ static void initialize(void) {
|
||||
return;
|
||||
}
|
||||
const char *on = getenv("BL_STORAGE_DIAGNOSTICS");
|
||||
const char *skip = getenv("BL_STORAGE_PREALLOCATE_SKIP");
|
||||
const char *device = getenv("BL_STORAGE_DEVICE");
|
||||
if (on != NULL && strcmp(on, "1") == 0 && device != NULL && *device != '\0') {
|
||||
if (device != NULL && *device != '\0') {
|
||||
char *end = NULL;
|
||||
errno = 0;
|
||||
long long parsed = strtoll(device, &end, 10);
|
||||
if (errno == 0 && end != device && *end == '\0') {
|
||||
selected_device = parsed;
|
||||
enabled = 1;
|
||||
device_valid = 1;
|
||||
enabled = on != NULL && strcmp(on, "1") == 0;
|
||||
skip_preallocation = skip != NULL && strcmp(skip, "1") == 0;
|
||||
}
|
||||
}
|
||||
__atomic_store_n(&init_state, 2, __ATOMIC_RELEASE);
|
||||
@@ -90,10 +101,11 @@ static uint64_t now_ns(void) {
|
||||
return (uint64_t)ts.tv_sec * 1000000000ULL + (uint64_t)ts.tv_nsec;
|
||||
}
|
||||
|
||||
static int on_selected_device(int fd, const struct stat *known) {
|
||||
/* Diagnostics watch every wrapped call; skipping only concerns the allocation wrappers. */
|
||||
static int on_selected_device(int fd, const struct stat *known, int allocation) {
|
||||
struct stat local;
|
||||
initialize();
|
||||
if (!enabled) return 0;
|
||||
if (!device_valid || !(enabled || (allocation && skip_preallocation))) return 0;
|
||||
if (known == NULL) {
|
||||
if (next_fstat == NULL) next_fstat = dlsym(RTLD_NEXT, "fstat");
|
||||
if (next_fstat == NULL || next_fstat(fd, &local) != 0) return 0;
|
||||
@@ -154,19 +166,45 @@ static void allocation_line(const char *api, int result, int error, int flags,
|
||||
if (n > 0 && (size_t)n < sizeof(line)) append_line(line, (size_t)n);
|
||||
}
|
||||
|
||||
/* EXPERIMENT: how Steam sizes files once the reservation is skipped. exFAT has no sparse files,
|
||||
* so growing a file writes zeros for the whole new range. */
|
||||
static volatile unsigned int extend_details;
|
||||
static int truncate_skip = -1;
|
||||
|
||||
static int skip_extension(void) {
|
||||
if (truncate_skip < 0) truncate_skip = access("/root/.droiddeck-truncate-skip", F_OK) == 0;
|
||||
return skip_preallocation && truncate_skip;
|
||||
}
|
||||
|
||||
static void extend_line(const char *api, long long from, long long to, int result, uint64_t elapsed) {
|
||||
char line[256], comm[48];
|
||||
if (__atomic_add_fetch(&extend_details, 1, __ATOMIC_RELAXED) > 256) return;
|
||||
comm_name(comm, sizeof(comm));
|
||||
int n = snprintf(line, sizeof(line), "extend pid=%ld tid=%ld comm=%s api=%s from=%lld to=%lld result=%d elapsed_us=%llu\n",
|
||||
(long)getpid(), (long)syscall(SYS_gettid), comm, api, from, to, result,
|
||||
(unsigned long long)(elapsed / 1000ULL));
|
||||
if (n > 0 && (size_t)n < sizeof(line)) append_line(line, (size_t)n);
|
||||
}
|
||||
|
||||
int fallocate(int fd, int mode, off_t offset, off_t length) {
|
||||
int entry_errno = errno;
|
||||
if (next_fallocate == NULL) next_fallocate = dlsym(RTLD_NEXT, "fallocate");
|
||||
if (next_fallocate == NULL) { errno = ENOSYS; return -1; }
|
||||
int selected = on_selected_device(fd, NULL);
|
||||
int selected = on_selected_device(fd, NULL, 1);
|
||||
errno = entry_errno;
|
||||
if (!selected) return next_fallocate(fd, mode, offset, length);
|
||||
uint64_t start = now_ns();
|
||||
/* Only a plain reservation is skipped; hole punching and the other modes change contents. */
|
||||
if (skip_preallocation && (mode == 0 || mode == FALLOC_FL_KEEP_SIZE)) {
|
||||
if (enabled) allocation_line("fallocate_skipped", 0, entry_errno, mode, offset, length, now_ns() - start);
|
||||
errno = entry_errno;
|
||||
return 0;
|
||||
}
|
||||
errno = entry_errno;
|
||||
int result = next_fallocate(fd, mode, offset, length);
|
||||
int call_errno = errno;
|
||||
uint64_t elapsed = now_ns() - start;
|
||||
allocation_line("fallocate", result, call_errno, mode, offset, length, elapsed);
|
||||
if (enabled) allocation_line("fallocate", result, call_errno, mode, offset, length, elapsed);
|
||||
errno = call_errno;
|
||||
return result;
|
||||
}
|
||||
@@ -175,7 +213,7 @@ int posix_fallocate(int fd, off_t offset, off_t length) {
|
||||
int entry_errno = errno;
|
||||
if (next_posix_fallocate == NULL) next_posix_fallocate = dlsym(RTLD_NEXT, "posix_fallocate");
|
||||
if (next_posix_fallocate == NULL) { errno = entry_errno; return ENOSYS; }
|
||||
int selected = on_selected_device(fd, NULL);
|
||||
int selected = on_selected_device(fd, NULL, 1);
|
||||
errno = entry_errno;
|
||||
if (!selected) {
|
||||
int result = next_posix_fallocate(fd, offset, length);
|
||||
@@ -183,11 +221,16 @@ int posix_fallocate(int fd, off_t offset, off_t length) {
|
||||
return result;
|
||||
}
|
||||
uint64_t start = now_ns();
|
||||
if (skip_preallocation) {
|
||||
if (enabled) allocation_line("posix_fallocate_skipped", 0, entry_errno, 0, offset, length, now_ns() - start);
|
||||
errno = entry_errno;
|
||||
return 0;
|
||||
}
|
||||
errno = entry_errno;
|
||||
int result = next_posix_fallocate(fd, offset, length);
|
||||
int call_errno = errno;
|
||||
uint64_t elapsed = now_ns() - start;
|
||||
allocation_line("posix_fallocate", result, call_errno, 0, offset, length, elapsed);
|
||||
if (enabled) allocation_line("posix_fallocate", result, call_errno, 0, offset, length, elapsed);
|
||||
errno = entry_errno; /* POSIX requires the error to be returned, leaving errno unchanged. */
|
||||
return result;
|
||||
}
|
||||
@@ -197,9 +240,21 @@ ssize_t pwrite(int fd, const void *buffer, size_t count, off_t offset) {
|
||||
if (next_pwrite == NULL) next_pwrite = dlsym(RTLD_NEXT, "pwrite");
|
||||
if (next_pwrite == NULL) { errno = ENOSYS; return -1; }
|
||||
initialize();
|
||||
if (enabled && extend_details < 256 && on_selected_device(fd, NULL, 0)) {
|
||||
struct stat st;
|
||||
if (next_fstat(fd, &st) == 0 && (long long)offset > (long long)st.st_size + 65536) {
|
||||
uint64_t t0 = now_ns();
|
||||
errno = entry_errno;
|
||||
ssize_t r = next_pwrite(fd, buffer, count, offset);
|
||||
int e = errno;
|
||||
extend_line("pwrite_past_eof", (long long)st.st_size, (long long)offset + (long long)count, (int)r, now_ns() - t0);
|
||||
errno = e;
|
||||
return r;
|
||||
}
|
||||
}
|
||||
uint64_t sequence = enabled ? add(&pwrite_seen, 1) : 1;
|
||||
int sample = enabled && (sequence % 32ULL) == 0;
|
||||
int selected = sample && on_selected_device(fd, NULL);
|
||||
int selected = sample && on_selected_device(fd, NULL, 0);
|
||||
errno = entry_errno;
|
||||
if (!selected)
|
||||
return next_pwrite(fd, buffer, count, offset);
|
||||
@@ -219,16 +274,26 @@ ssize_t pwrite(int fd, const void *buffer, size_t count, off_t offset) {
|
||||
|
||||
int ftruncate(int fd, off_t length) {
|
||||
int entry_errno = errno;
|
||||
struct stat st;
|
||||
if (next_ftruncate == NULL) next_ftruncate = dlsym(RTLD_NEXT, "ftruncate");
|
||||
if (next_ftruncate == NULL) { errno = ENOSYS; return -1; }
|
||||
int selected = on_selected_device(fd, NULL);
|
||||
if (next_fstat == NULL) next_fstat = dlsym(RTLD_NEXT, "fstat");
|
||||
int selected = on_selected_device(fd, NULL, 1);
|
||||
errno = entry_errno;
|
||||
if (!selected) return next_ftruncate(fd, length);
|
||||
long long from = (next_fstat != NULL && next_fstat(fd, &st) == 0) ? (long long)st.st_size : -1;
|
||||
int extending = from >= 0 && (long long)length > from;
|
||||
if (extending && skip_extension()) {
|
||||
extend_line("ftruncate_skipped", from, (long long)length, 0, 0);
|
||||
errno = entry_errno;
|
||||
return 0;
|
||||
}
|
||||
uint64_t start = now_ns();
|
||||
errno = entry_errno;
|
||||
int result = next_ftruncate(fd, length);
|
||||
int call_errno = errno;
|
||||
uint64_t elapsed = now_ns() - start;
|
||||
if (extending) extend_line("ftruncate", from, (long long)length, result, elapsed);
|
||||
add(&stats.ftruncate_calls, 1);
|
||||
if (result != 0) add(&stats.ftruncate_failures, 1);
|
||||
add(&stats.ftruncate_elapsed_ns, elapsed);
|
||||
@@ -237,19 +302,56 @@ int ftruncate(int fd, off_t length) {
|
||||
return result;
|
||||
}
|
||||
|
||||
int truncate(const char *path, off_t length) {
|
||||
static int (*next_truncate)(const char *, off_t);
|
||||
int entry_errno = errno;
|
||||
struct stat st;
|
||||
if (next_truncate == NULL) next_truncate = dlsym(RTLD_NEXT, "truncate");
|
||||
if (next_truncate == NULL) { errno = ENOSYS; return -1; }
|
||||
initialize();
|
||||
int selected = device_valid && (enabled || skip_preallocation) && stat(path, &st) == 0 &&
|
||||
(long long)st.st_dev == selected_device;
|
||||
errno = entry_errno;
|
||||
if (!selected) return next_truncate(path, length);
|
||||
int extending = (long long)length > (long long)st.st_size;
|
||||
if (extending && skip_extension()) {
|
||||
extend_line("truncate_skipped", (long long)st.st_size, (long long)length, 0, 0);
|
||||
errno = entry_errno;
|
||||
return 0;
|
||||
}
|
||||
uint64_t start = now_ns();
|
||||
int result = next_truncate(path, length);
|
||||
int call_errno = errno;
|
||||
if (extending) extend_line("truncate", (long long)st.st_size, (long long)length, result, now_ns() - start);
|
||||
errno = call_errno;
|
||||
return result;
|
||||
}
|
||||
|
||||
int bl_meta_on(void) __attribute__((visibility("hidden")));
|
||||
void bl_meta_log(const char *op, int dirfd, const char *path, int flags, uint64_t start, long result, int err)
|
||||
__attribute__((visibility("hidden")));
|
||||
|
||||
int fstat(int fd, struct stat *out) {
|
||||
int entry_errno = errno;
|
||||
if (next_fstat == NULL) next_fstat = dlsym(RTLD_NEXT, "fstat");
|
||||
if (next_fstat == NULL) { errno = ENOSYS; return -1; }
|
||||
initialize();
|
||||
errno = entry_errno;
|
||||
if (bl_meta_on()) {
|
||||
uint64_t t0 = now_ns();
|
||||
int r = next_fstat(fd, out);
|
||||
int e = errno;
|
||||
if (now_ns() - t0 > 500000ULL) bl_meta_log("fstat", fd, "/steamapps/(slow fstat)", 0, t0, r, e);
|
||||
errno = e;
|
||||
if (!enabled) return r;
|
||||
}
|
||||
if (!enabled) return next_fstat(fd, out);
|
||||
uint64_t start = now_ns();
|
||||
errno = entry_errno;
|
||||
int result = next_fstat(fd, out);
|
||||
int call_errno = errno;
|
||||
uint64_t elapsed = now_ns() - start;
|
||||
if (result == 0 && on_selected_device(fd, out)) {
|
||||
if (result == 0 && on_selected_device(fd, out, 0)) {
|
||||
add(&stats.fstat_calls, 1);
|
||||
add(&stats.fstat_elapsed_ns, elapsed);
|
||||
update_max(&stats.fstat_max_ns, elapsed);
|
||||
@@ -262,7 +364,7 @@ int fsync(int fd) {
|
||||
int entry_errno = errno;
|
||||
if (next_fsync == NULL) next_fsync = dlsym(RTLD_NEXT, "fsync");
|
||||
if (next_fsync == NULL) { errno = ENOSYS; return -1; }
|
||||
int selected = on_selected_device(fd, NULL);
|
||||
int selected = on_selected_device(fd, NULL, 0);
|
||||
errno = entry_errno;
|
||||
if (!selected) return next_fsync(fd);
|
||||
uint64_t start = now_ns();
|
||||
@@ -313,5 +415,6 @@ int fallocate64(int fd, int mode, off64_t offset, off64_t length) __attribute__(
|
||||
int posix_fallocate64(int fd, off64_t offset, off64_t length) __attribute__((alias("posix_fallocate")));
|
||||
ssize_t pwrite64(int fd, const void *buffer, size_t count, off64_t offset) __attribute__((alias("pwrite")));
|
||||
int ftruncate64(int fd, off64_t length) __attribute__((alias("ftruncate")));
|
||||
int truncate64(const char *path, off64_t length) __attribute__((alias("truncate")));
|
||||
int fstat64(int fd, struct stat64 *out) __attribute__((alias("fstat")));
|
||||
#endif
|
||||
@@ -0,0 +1,180 @@
|
||||
/*
|
||||
* libssbs.so - keep PSTATE.SSBS set across signal returns, without rebuilding Wine.
|
||||
*
|
||||
* Wine's arm64 signal code writes PSTATE back from a Windows CONTEXT, whose Cpsr never carries
|
||||
* SSBS (bit 12). Every signal return through that code (exception fixups, NtSetContextThread on
|
||||
* another thread, the SIGUSR2 suspend path) therefore resumes the thread with SSBS clear, so the
|
||||
* CPU runs it with speculative store bypass disabled - slower on cores such as Oryon.
|
||||
* force_ssbs.diff (Sonicadvance1, FEX) fixes this inside ntdll; this library does the same from
|
||||
* outside, for Protons that cannot be rebuilt: the Valve, GE and CachyOS ARM64 builds DroidDeck
|
||||
* runs, which come prebuilt from Steam. Same source as Bannerlator's adapter (bionic), built here
|
||||
* for glibc.
|
||||
*
|
||||
* How: interpose sigaction()/signal() via LD_PRELOAD. Every handler is installed behind one
|
||||
* SA_SIGINFO trampoline that calls the real handler and then sets SSBS in the ucontext it is
|
||||
* about to return through. The kernel accepts SSBS from userspace on sigreturn and context-
|
||||
* switches it per thread, so the bit sticks until the next sigreturn. Handlers that never return
|
||||
* (siglongjmp) are unaffected either way.
|
||||
*
|
||||
* Env:
|
||||
* SSBS_ADAPTER_DISABLE=1 pass everything through untouched.
|
||||
* SSBS_ADAPTER_OBSERVE=1 wrap and count, but leave SSBS as the handler left it (the baseline).
|
||||
* SSBS_ADAPTER_DEBUG=1 log to stderr (implied by OBSERVE):
|
||||
* - "returned with SSBS clear": a handler was about to resume a thread without SSBS.
|
||||
* - "arrived with SSBS clear": a thread was RUNNING without SSBS when a signal reached it.
|
||||
* Under the adapter this should stop after each thread's first fixed return; if it keeps
|
||||
* counting, something other than a signal return is clearing the bit.
|
||||
*/
|
||||
#define _GNU_SOURCE
|
||||
#include <dlfcn.h>
|
||||
#include <signal.h>
|
||||
#include <stdatomic.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <ucontext.h>
|
||||
|
||||
#define PSTATE_SSBS 0x1000ULL
|
||||
#define MAX_SIG 65
|
||||
|
||||
typedef void (*sigact_fn)(int, siginfo_t *, void *);
|
||||
typedef void (*sighand_fn)(int);
|
||||
typedef int (*sigaction_fn)(int, const struct sigaction *, struct sigaction *);
|
||||
|
||||
/* Per signal: the handler the program asked for, and whether it wanted SA_SIGINFO. */
|
||||
static _Atomic(void *) real_handler[MAX_SIG];
|
||||
static atomic_bool real_siginfo[MAX_SIG];
|
||||
|
||||
static sigaction_fn next_sigaction;
|
||||
static int disabled;
|
||||
static int observe;
|
||||
static int debug;
|
||||
static atomic_ulong n_returns, n_fixed, n_arrived, n_arrived_clear;
|
||||
|
||||
static void init(void)
|
||||
{
|
||||
if (next_sigaction) return;
|
||||
next_sigaction = (sigaction_fn)dlsym(RTLD_NEXT, "sigaction");
|
||||
const char *e = getenv("SSBS_ADAPTER_DISABLE");
|
||||
disabled = e && *e == '1';
|
||||
e = getenv("SSBS_ADAPTER_OBSERVE");
|
||||
observe = e && *e == '1';
|
||||
e = getenv("SSBS_ADAPTER_DEBUG");
|
||||
debug = observe || (e && *e == '1');
|
||||
}
|
||||
|
||||
__attribute__((constructor)) static void ctor(void)
|
||||
{
|
||||
init();
|
||||
if (debug) fprintf(stderr, "libssbs: loaded (%s)\n", disabled ? "disabled" : observe ? "observing only" : "active");
|
||||
}
|
||||
|
||||
/* 1, 2, 4, 8, ...: enough lines to see a trend without flooding the log. */
|
||||
static int milestone(unsigned long n) { return (n & (n - 1)) == 0; }
|
||||
|
||||
static void trampoline(int sig, siginfo_t *info, void *uc_v)
|
||||
{
|
||||
ucontext_t *uc = uc_v;
|
||||
if (debug) {
|
||||
unsigned long a = atomic_fetch_add(&n_arrived, 1) + 1;
|
||||
if (!(uc->uc_mcontext.pstate & PSTATE_SSBS)) {
|
||||
unsigned long c = atomic_fetch_add(&n_arrived_clear, 1) + 1;
|
||||
if (milestone(c))
|
||||
fprintf(stderr, "libssbs: sig %d arrived with SSBS clear (%lu of %lu arrivals)\n", sig, c, a);
|
||||
}
|
||||
}
|
||||
void *h = atomic_load_explicit(&real_handler[sig], memory_order_acquire);
|
||||
if (h) {
|
||||
if (atomic_load_explicit(&real_siginfo[sig], memory_order_relaxed))
|
||||
((sigact_fn)h)(sig, info, uc_v);
|
||||
else
|
||||
((sighand_fn)h)(sig);
|
||||
}
|
||||
if (debug) {
|
||||
unsigned long r = atomic_fetch_add(&n_returns, 1) + 1;
|
||||
if (!(uc->uc_mcontext.pstate & PSTATE_SSBS)) {
|
||||
unsigned long f = atomic_fetch_add(&n_fixed, 1) + 1;
|
||||
if (milestone(f))
|
||||
fprintf(stderr, "libssbs: sig %d returned with SSBS clear, %s (%lu of %lu returns)\n",
|
||||
sig, observe ? "left as is" : "set it", f, r);
|
||||
}
|
||||
}
|
||||
if (!observe) uc->uc_mcontext.pstate |= PSTATE_SSBS;
|
||||
}
|
||||
|
||||
static int wrapped(void *h)
|
||||
{
|
||||
return h != (void *)SIG_DFL && h != (void *)SIG_IGN && h != (void *)SIG_ERR;
|
||||
}
|
||||
|
||||
int sigaction(int sig, const struct sigaction *act, struct sigaction *oldact)
|
||||
{
|
||||
init();
|
||||
if (disabled || sig <= 0 || sig >= MAX_SIG)
|
||||
return next_sigaction(sig, act, oldact);
|
||||
|
||||
struct sigaction mine;
|
||||
const struct sigaction *pass = act;
|
||||
void *new_h = NULL;
|
||||
int new_info = 0;
|
||||
if (act) {
|
||||
new_info = (act->sa_flags & SA_SIGINFO) != 0;
|
||||
new_h = new_info ? (void *)act->sa_sigaction : (void *)act->sa_handler;
|
||||
if (wrapped(new_h)) {
|
||||
mine = *act;
|
||||
mine.sa_flags |= SA_SIGINFO;
|
||||
mine.sa_sigaction = trampoline;
|
||||
pass = &mine;
|
||||
}
|
||||
}
|
||||
|
||||
void *prev_h = atomic_load(&real_handler[sig]);
|
||||
int prev_info = atomic_load(&real_siginfo[sig]);
|
||||
/* Publish before installing so the trampoline never runs with a stale handler. */
|
||||
if (act && wrapped(new_h)) {
|
||||
atomic_store(&real_siginfo[sig], new_info);
|
||||
atomic_store_explicit(&real_handler[sig], new_h, memory_order_release);
|
||||
}
|
||||
|
||||
int ret = next_sigaction(sig, pass, oldact);
|
||||
if (ret != 0 && act && wrapped(new_h)) {
|
||||
atomic_store(&real_siginfo[sig], prev_info);
|
||||
atomic_store(&real_handler[sig], prev_h);
|
||||
}
|
||||
|
||||
/* Report the caller's own handler, not the trampoline, so handler chaining keeps working. */
|
||||
if (ret == 0 && oldact && oldact->sa_sigaction == trampoline && prev_h) {
|
||||
if (prev_info) {
|
||||
oldact->sa_sigaction = (sigact_fn)prev_h;
|
||||
} else {
|
||||
oldact->sa_flags &= ~SA_SIGINFO;
|
||||
oldact->sa_handler = (sighand_fn)prev_h;
|
||||
}
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
sighandler_t signal(int sig, sighandler_t handler)
|
||||
{
|
||||
struct sigaction sa, old;
|
||||
memset(&sa, 0, sizeof(sa));
|
||||
sa.sa_handler = handler;
|
||||
sa.sa_flags = SA_RESTART;
|
||||
sigemptyset(&sa.sa_mask);
|
||||
if (sigaction(sig, &sa, &old) != 0) return SIG_ERR;
|
||||
return (old.sa_flags & SA_SIGINFO) ? (sighandler_t)(void *)old.sa_sigaction : old.sa_handler;
|
||||
}
|
||||
|
||||
sighandler_t bsd_signal(int sig, sighandler_t handler) { return signal(sig, handler); }
|
||||
|
||||
/* glibc's System V flavour: a one-shot handler with no restart. */
|
||||
sighandler_t sysv_signal(int sig, sighandler_t handler)
|
||||
{
|
||||
struct sigaction sa, old;
|
||||
memset(&sa, 0, sizeof(sa));
|
||||
sa.sa_handler = handler;
|
||||
sa.sa_flags = SA_RESETHAND | SA_NODEFER;
|
||||
sigemptyset(&sa.sa_mask);
|
||||
if (sigaction(sig, &sa, &old) != 0) return SIG_ERR;
|
||||
return (old.sa_flags & SA_SIGINFO) ? (sighandler_t)(void *)old.sa_sigaction : old.sa_handler;
|
||||
}
|
||||
@@ -0,0 +1,338 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 2, June 1991
|
||||
|
||||
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
|
||||
<https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The licenses for most software are designed to take away your
|
||||
freedom to share and change it. By contrast, the GNU General Public
|
||||
License is intended to guarantee your freedom to share and change free
|
||||
software--to make sure the software is free for all its users. This
|
||||
General Public License applies to most of the Free Software
|
||||
Foundation's software and to any other program whose authors commit to
|
||||
using it. (Some other Free Software Foundation software is covered by
|
||||
the GNU Lesser General Public License instead.) You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
this service if you wish), that you receive source code or can get it
|
||||
if you want it, that you can change the software or use pieces of it
|
||||
in new free programs; and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to make restrictions that forbid
|
||||
anyone to deny you these rights or to ask you to surrender the rights.
|
||||
These restrictions translate to certain responsibilities for you if you
|
||||
distribute copies of the software, or if you modify it.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must give the recipients all the rights that
|
||||
you have. You must make sure that they, too, receive or can get the
|
||||
source code. And you must show them these terms so they know their
|
||||
rights.
|
||||
|
||||
We protect your rights with two steps: (1) copyright the software, and
|
||||
(2) offer you this license which gives you legal permission to copy,
|
||||
distribute and/or modify the software.
|
||||
|
||||
Also, for each author's protection and ours, we want to make certain
|
||||
that everyone understands that there is no warranty for this free
|
||||
software. If the software is modified by someone else and passed on, we
|
||||
want its recipients to know that what they have is not the original, so
|
||||
that any problems introduced by others will not reflect on the original
|
||||
authors' reputations.
|
||||
|
||||
Finally, any free program is threatened constantly by software
|
||||
patents. We wish to avoid the danger that redistributors of a free
|
||||
program will individually obtain patent licenses, in effect making the
|
||||
program proprietary. To prevent this, we have made it clear that any
|
||||
patent must be licensed for everyone's free use or not licensed at all.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
|
||||
|
||||
0. This License applies to any program or other work which contains
|
||||
a notice placed by the copyright holder saying it may be distributed
|
||||
under the terms of this General Public License. The "Program", below,
|
||||
refers to any such program or work, and a "work based on the Program"
|
||||
means either the Program or any derivative work under copyright law:
|
||||
that is to say, a work containing the Program or a portion of it,
|
||||
either verbatim or with modifications and/or translated into another
|
||||
language. (Hereinafter, translation is included without limitation in
|
||||
the term "modification".) Each licensee is addressed as "you".
|
||||
|
||||
Activities other than copying, distribution and modification are not
|
||||
covered by this License; they are outside its scope. The act of
|
||||
running the Program is not restricted, and the output from the Program
|
||||
is covered only if its contents constitute a work based on the
|
||||
Program (independent of having been made by running the Program).
|
||||
Whether that is true depends on what the Program does.
|
||||
|
||||
1. You may copy and distribute verbatim copies of the Program's
|
||||
source code as you receive it, in any medium, provided that you
|
||||
conspicuously and appropriately publish on each copy an appropriate
|
||||
copyright notice and disclaimer of warranty; keep intact all the
|
||||
notices that refer to this License and to the absence of any warranty;
|
||||
and give any other recipients of the Program a copy of this License
|
||||
along with the Program.
|
||||
|
||||
You may charge a fee for the physical act of transferring a copy, and
|
||||
you may at your option offer warranty protection in exchange for a fee.
|
||||
|
||||
2. You may modify your copy or copies of the Program or any portion
|
||||
of it, thus forming a work based on the Program, and copy and
|
||||
distribute such modifications or work under the terms of Section 1
|
||||
above, provided that you also meet all of these conditions:
|
||||
|
||||
a) You must cause the modified files to carry prominent notices
|
||||
stating that you changed the files and the date of any change.
|
||||
|
||||
b) You must cause any work that you distribute or publish, that in
|
||||
whole or in part contains or is derived from the Program or any
|
||||
part thereof, to be licensed as a whole at no charge to all third
|
||||
parties under the terms of this License.
|
||||
|
||||
c) If the modified program normally reads commands interactively
|
||||
when run, you must cause it, when started running for such
|
||||
interactive use in the most ordinary way, to print or display an
|
||||
announcement including an appropriate copyright notice and a
|
||||
notice that there is no warranty (or else, saying that you provide
|
||||
a warranty) and that users may redistribute the program under
|
||||
these conditions, and telling the user how to view a copy of this
|
||||
License. (Exception: if the Program itself is interactive but
|
||||
does not normally print such an announcement, your work based on
|
||||
the Program is not required to print an announcement.)
|
||||
|
||||
These requirements apply to the modified work as a whole. If
|
||||
identifiable sections of that work are not derived from the Program,
|
||||
and can be reasonably considered independent and separate works in
|
||||
themselves, then this License, and its terms, do not apply to those
|
||||
sections when you distribute them as separate works. But when you
|
||||
distribute the same sections as part of a whole which is a work based
|
||||
on the Program, the distribution of the whole must be on the terms of
|
||||
this License, whose permissions for other licensees extend to the
|
||||
entire whole, and thus to each and every part regardless of who wrote it.
|
||||
|
||||
Thus, it is not the intent of this section to claim rights or contest
|
||||
your rights to work written entirely by you; rather, the intent is to
|
||||
exercise the right to control the distribution of derivative or
|
||||
collective works based on the Program.
|
||||
|
||||
In addition, mere aggregation of another work not based on the Program
|
||||
with the Program (or with a work based on the Program) on a volume of
|
||||
a storage or distribution medium does not bring the other work under
|
||||
the scope of this License.
|
||||
|
||||
3. You may copy and distribute the Program (or a work based on it,
|
||||
under Section 2) in object code or executable form under the terms of
|
||||
Sections 1 and 2 above provided that you also do one of the following:
|
||||
|
||||
a) Accompany it with the complete corresponding machine-readable
|
||||
source code, which must be distributed under the terms of Sections
|
||||
1 and 2 above on a medium customarily used for software interchange; or,
|
||||
|
||||
b) Accompany it with a written offer, valid for at least three
|
||||
years, to give any third party, for a charge no more than your
|
||||
cost of physically performing source distribution, a complete
|
||||
machine-readable copy of the corresponding source code, to be
|
||||
distributed under the terms of Sections 1 and 2 above on a medium
|
||||
customarily used for software interchange; or,
|
||||
|
||||
c) Accompany it with the information you received as to the offer
|
||||
to distribute corresponding source code. (This alternative is
|
||||
allowed only for noncommercial distribution and only if you
|
||||
received the program in object code or executable form with such
|
||||
an offer, in accord with Subsection b above.)
|
||||
|
||||
The source code for a work means the preferred form of the work for
|
||||
making modifications to it. For an executable work, complete source
|
||||
code means all the source code for all modules it contains, plus any
|
||||
associated interface definition files, plus the scripts used to
|
||||
control compilation and installation of the executable. However, as a
|
||||
special exception, the source code distributed need not include
|
||||
anything that is normally distributed (in either source or binary
|
||||
form) with the major components (compiler, kernel, and so on) of the
|
||||
operating system on which the executable runs, unless that component
|
||||
itself accompanies the executable.
|
||||
|
||||
If distribution of executable or object code is made by offering
|
||||
access to copy from a designated place, then offering equivalent
|
||||
access to copy the source code from the same place counts as
|
||||
distribution of the source code, even though third parties are not
|
||||
compelled to copy the source along with the object code.
|
||||
|
||||
4. You may not copy, modify, sublicense, or distribute the Program
|
||||
except as expressly provided under this License. Any attempt
|
||||
otherwise to copy, modify, sublicense or distribute the Program is
|
||||
void, and will automatically terminate your rights under this License.
|
||||
However, parties who have received copies, or rights, from you under
|
||||
this License will not have their licenses terminated so long as such
|
||||
parties remain in full compliance.
|
||||
|
||||
5. You are not required to accept this License, since you have not
|
||||
signed it. However, nothing else grants you permission to modify or
|
||||
distribute the Program or its derivative works. These actions are
|
||||
prohibited by law if you do not accept this License. Therefore, by
|
||||
modifying or distributing the Program (or any work based on the
|
||||
Program), you indicate your acceptance of this License to do so, and
|
||||
all its terms and conditions for copying, distributing or modifying
|
||||
the Program or works based on it.
|
||||
|
||||
6. Each time you redistribute the Program (or any work based on the
|
||||
Program), the recipient automatically receives a license from the
|
||||
original licensor to copy, distribute or modify the Program subject to
|
||||
these terms and conditions. You may not impose any further
|
||||
restrictions on the recipients' exercise of the rights granted herein.
|
||||
You are not responsible for enforcing compliance by third parties to
|
||||
this License.
|
||||
|
||||
7. If, as a consequence of a court judgment or allegation of patent
|
||||
infringement or for any other reason (not limited to patent issues),
|
||||
conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot
|
||||
distribute so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you
|
||||
may not distribute the Program at all. For example, if a patent
|
||||
license would not permit royalty-free redistribution of the Program by
|
||||
all those who receive copies directly or indirectly through you, then
|
||||
the only way you could satisfy both it and this License would be to
|
||||
refrain entirely from distribution of the Program.
|
||||
|
||||
If any portion of this section is held invalid or unenforceable under
|
||||
any particular circumstance, the balance of the section is intended to
|
||||
apply and the section as a whole is intended to apply in other
|
||||
circumstances.
|
||||
|
||||
It is not the purpose of this section to induce you to infringe any
|
||||
patents or other property right claims or to contest validity of any
|
||||
such claims; this section has the sole purpose of protecting the
|
||||
integrity of the free software distribution system, which is
|
||||
implemented by public license practices. Many people have made
|
||||
generous contributions to the wide range of software distributed
|
||||
through that system in reliance on consistent application of that
|
||||
system; it is up to the author/donor to decide if he or she is willing
|
||||
to distribute software through any other system and a licensee cannot
|
||||
impose that choice.
|
||||
|
||||
This section is intended to make thoroughly clear what is believed to
|
||||
be a consequence of the rest of this License.
|
||||
|
||||
8. If the distribution and/or use of the Program is restricted in
|
||||
certain countries either by patents or by copyrighted interfaces, the
|
||||
original copyright holder who places the Program under this License
|
||||
may add an explicit geographical distribution limitation excluding
|
||||
those countries, so that distribution is permitted only in or among
|
||||
countries not thus excluded. In such case, this License incorporates
|
||||
the limitation as if written in the body of this License.
|
||||
|
||||
9. The Free Software Foundation may publish revised and/or new versions
|
||||
of the General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the Program
|
||||
specifies a version number of this License which applies to it and "any
|
||||
later version", you have the option of following the terms and conditions
|
||||
either of that version or of any later version published by the Free
|
||||
Software Foundation. If the Program does not specify a version number of
|
||||
this License, you may choose any version ever published by the Free Software
|
||||
Foundation.
|
||||
|
||||
10. If you wish to incorporate parts of the Program into other free
|
||||
programs whose distribution conditions are different, write to the author
|
||||
to ask for permission. For software which is copyrighted by the Free
|
||||
Software Foundation, write to the Free Software Foundation; we sometimes
|
||||
make exceptions for this. Our decision will be guided by the two goals
|
||||
of preserving the free status of all derivatives of our free software and
|
||||
of promoting the sharing and reuse of software generally.
|
||||
|
||||
NO WARRANTY
|
||||
|
||||
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
|
||||
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
|
||||
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
|
||||
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
|
||||
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
|
||||
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
|
||||
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
|
||||
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
|
||||
REPAIR OR CORRECTION.
|
||||
|
||||
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
|
||||
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
|
||||
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
|
||||
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
|
||||
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
|
||||
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
|
||||
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
|
||||
POSSIBILITY OF SUCH DAMAGES.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
convey the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software; you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation; either version 2 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License along
|
||||
with this program; if not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program is interactive, make it output a short notice like this
|
||||
when it starts in an interactive mode:
|
||||
|
||||
Gnomovision version 69, Copyright (C) year name of author
|
||||
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, the commands you use may
|
||||
be called something other than `show w' and `show c'; they could even be
|
||||
mouse-clicks or menu items--whatever suits your program.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or your
|
||||
school, if any, to sign a "copyright disclaimer" for the program, if
|
||||
necessary. Here is a sample; alter the names:
|
||||
|
||||
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
|
||||
`Gnomovision' (which makes passes at compilers) written by James Hacker.
|
||||
|
||||
<signature of Moe Ghoul>, 1 April 1989
|
||||
Moe Ghoul, President of Vice
|
||||
|
||||
This General Public License does not permit incorporating your program into
|
||||
proprietary programs. If your program is a subroutine library, you may
|
||||
consider it more useful to permit linking proprietary applications with the
|
||||
library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License.
|
||||
@@ -0,0 +1,674 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
||||
@@ -0,0 +1,501 @@
|
||||
GNU LESSER GENERAL PUBLIC LICENSE
|
||||
Version 2.1, February 1999
|
||||
|
||||
Copyright (C) 1991, 1999 Free Software Foundation, Inc.
|
||||
<https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
[This is the first released version of the Lesser GPL. It also counts
|
||||
as the successor of the GNU Library Public License, version 2, hence
|
||||
the version number 2.1.]
|
||||
|
||||
Preamble
|
||||
|
||||
The licenses for most software are designed to take away your
|
||||
freedom to share and change it. By contrast, the GNU General Public
|
||||
Licenses are intended to guarantee your freedom to share and change
|
||||
free software--to make sure the software is free for all its users.
|
||||
|
||||
This license, the Lesser General Public License, applies to some
|
||||
specially designated software packages--typically libraries--of the
|
||||
Free Software Foundation and other authors who decide to use it. You
|
||||
can use it too, but we suggest you first think carefully about whether
|
||||
this license or the ordinary General Public License is the better
|
||||
strategy to use in any particular case, based on the explanations below.
|
||||
|
||||
When we speak of free software, we are referring to freedom of use,
|
||||
not price. Our General Public Licenses are designed to make sure that
|
||||
you have the freedom to distribute copies of free software (and charge
|
||||
for this service if you wish); that you receive source code or can get
|
||||
it if you want it; that you can change the software and use pieces of
|
||||
it in new free programs; and that you are informed that you can do
|
||||
these things.
|
||||
|
||||
To protect your rights, we need to make restrictions that forbid
|
||||
distributors to deny you these rights or to ask you to surrender these
|
||||
rights. These restrictions translate to certain responsibilities for
|
||||
you if you distribute copies of the library or if you modify it.
|
||||
|
||||
For example, if you distribute copies of the library, whether gratis
|
||||
or for a fee, you must give the recipients all the rights that we gave
|
||||
you. You must make sure that they, too, receive or can get the source
|
||||
code. If you link other code with the library, you must provide
|
||||
complete object files to the recipients, so that they can relink them
|
||||
with the library after making changes to the library and recompiling
|
||||
it. And you must show them these terms so they know their rights.
|
||||
|
||||
We protect your rights with a two-step method: (1) we copyright the
|
||||
library, and (2) we offer you this license, which gives you legal
|
||||
permission to copy, distribute and/or modify the library.
|
||||
|
||||
To protect each distributor, we want to make it very clear that
|
||||
there is no warranty for the free library. Also, if the library is
|
||||
modified by someone else and passed on, the recipients should know
|
||||
that what they have is not the original version, so that the original
|
||||
author's reputation will not be affected by problems that might be
|
||||
introduced by others.
|
||||
|
||||
Finally, software patents pose a constant threat to the existence of
|
||||
any free program. We wish to make sure that a company cannot
|
||||
effectively restrict the users of a free program by obtaining a
|
||||
restrictive license from a patent holder. Therefore, we insist that
|
||||
any patent license obtained for a version of the library must be
|
||||
consistent with the full freedom of use specified in this license.
|
||||
|
||||
Most GNU software, including some libraries, is covered by the
|
||||
ordinary GNU General Public License. This license, the GNU Lesser
|
||||
General Public License, applies to certain designated libraries, and
|
||||
is quite different from the ordinary General Public License. We use
|
||||
this license for certain libraries in order to permit linking those
|
||||
libraries into non-free programs.
|
||||
|
||||
When a program is linked with a library, whether statically or using
|
||||
a shared library, the combination of the two is legally speaking a
|
||||
combined work, a derivative of the original library. The ordinary
|
||||
General Public License therefore permits such linking only if the
|
||||
entire combination fits its criteria of freedom. The Lesser General
|
||||
Public License permits more lax criteria for linking other code with
|
||||
the library.
|
||||
|
||||
We call this license the "Lesser" General Public License because it
|
||||
does Less to protect the user's freedom than the ordinary General
|
||||
Public License. It also provides other free software developers Less
|
||||
of an advantage over competing non-free programs. These disadvantages
|
||||
are the reason we use the ordinary General Public License for many
|
||||
libraries. However, the Lesser license provides advantages in certain
|
||||
special circumstances.
|
||||
|
||||
For example, on rare occasions, there may be a special need to
|
||||
encourage the widest possible use of a certain library, so that it becomes
|
||||
a de-facto standard. To achieve this, non-free programs must be
|
||||
allowed to use the library. A more frequent case is that a free
|
||||
library does the same job as widely used non-free libraries. In this
|
||||
case, there is little to gain by limiting the free library to free
|
||||
software only, so we use the Lesser General Public License.
|
||||
|
||||
In other cases, permission to use a particular library in non-free
|
||||
programs enables a greater number of people to use a large body of
|
||||
free software. For example, permission to use the GNU C Library in
|
||||
non-free programs enables many more people to use the whole GNU
|
||||
operating system, as well as its variant, the GNU/Linux operating
|
||||
system.
|
||||
|
||||
Although the Lesser General Public License is Less protective of the
|
||||
users' freedom, it does ensure that the user of a program that is
|
||||
linked with the Library has the freedom and the wherewithal to run
|
||||
that program using a modified version of the Library.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow. Pay close attention to the difference between a
|
||||
"work based on the library" and a "work that uses the library". The
|
||||
former contains code derived from the library, whereas the latter must
|
||||
be combined with the library in order to run.
|
||||
|
||||
GNU LESSER GENERAL PUBLIC LICENSE
|
||||
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
|
||||
|
||||
0. This License Agreement applies to any software library or other
|
||||
program which contains a notice placed by the copyright holder or
|
||||
other authorized party saying it may be distributed under the terms of
|
||||
this Lesser General Public License (also called "this License").
|
||||
Each licensee is addressed as "you".
|
||||
|
||||
A "library" means a collection of software functions and/or data
|
||||
prepared so as to be conveniently linked with application programs
|
||||
(which use some of those functions and data) to form executables.
|
||||
|
||||
The "Library", below, refers to any such software library or work
|
||||
which has been distributed under these terms. A "work based on the
|
||||
Library" means either the Library or any derivative work under
|
||||
copyright law: that is to say, a work containing the Library or a
|
||||
portion of it, either verbatim or with modifications and/or translated
|
||||
straightforwardly into another language. (Hereinafter, translation is
|
||||
included without limitation in the term "modification".)
|
||||
|
||||
"Source code" for a work means the preferred form of the work for
|
||||
making modifications to it. For a library, complete source code means
|
||||
all the source code for all modules it contains, plus any associated
|
||||
interface definition files, plus the scripts used to control compilation
|
||||
and installation of the library.
|
||||
|
||||
Activities other than copying, distribution and modification are not
|
||||
covered by this License; they are outside its scope. The act of
|
||||
running a program using the Library is not restricted, and output from
|
||||
such a program is covered only if its contents constitute a work based
|
||||
on the Library (independent of the use of the Library in a tool for
|
||||
writing it). Whether that is true depends on what the Library does
|
||||
and what the program that uses the Library does.
|
||||
|
||||
1. You may copy and distribute verbatim copies of the Library's
|
||||
complete source code as you receive it, in any medium, provided that
|
||||
you conspicuously and appropriately publish on each copy an
|
||||
appropriate copyright notice and disclaimer of warranty; keep intact
|
||||
all the notices that refer to this License and to the absence of any
|
||||
warranty; and distribute a copy of this License along with the
|
||||
Library.
|
||||
|
||||
You may charge a fee for the physical act of transferring a copy,
|
||||
and you may at your option offer warranty protection in exchange for a
|
||||
fee.
|
||||
|
||||
2. You may modify your copy or copies of the Library or any portion
|
||||
of it, thus forming a work based on the Library, and copy and
|
||||
distribute such modifications or work under the terms of Section 1
|
||||
above, provided that you also meet all of these conditions:
|
||||
|
||||
a) The modified work must itself be a software library.
|
||||
|
||||
b) You must cause the files modified to carry prominent notices
|
||||
stating that you changed the files and the date of any change.
|
||||
|
||||
c) You must cause the whole of the work to be licensed at no
|
||||
charge to all third parties under the terms of this License.
|
||||
|
||||
d) If a facility in the modified Library refers to a function or a
|
||||
table of data to be supplied by an application program that uses
|
||||
the facility, other than as an argument passed when the facility
|
||||
is invoked, then you must make a good faith effort to ensure that,
|
||||
in the event an application does not supply such function or
|
||||
table, the facility still operates, and performs whatever part of
|
||||
its purpose remains meaningful.
|
||||
|
||||
(For example, a function in a library to compute square roots has
|
||||
a purpose that is entirely well-defined independent of the
|
||||
application. Therefore, Subsection 2d requires that any
|
||||
application-supplied function or table used by this function must
|
||||
be optional: if the application does not supply it, the square
|
||||
root function must still compute square roots.)
|
||||
|
||||
These requirements apply to the modified work as a whole. If
|
||||
identifiable sections of that work are not derived from the Library,
|
||||
and can be reasonably considered independent and separate works in
|
||||
themselves, then this License, and its terms, do not apply to those
|
||||
sections when you distribute them as separate works. But when you
|
||||
distribute the same sections as part of a whole which is a work based
|
||||
on the Library, the distribution of the whole must be on the terms of
|
||||
this License, whose permissions for other licensees extend to the
|
||||
entire whole, and thus to each and every part regardless of who wrote
|
||||
it.
|
||||
|
||||
Thus, it is not the intent of this section to claim rights or contest
|
||||
your rights to work written entirely by you; rather, the intent is to
|
||||
exercise the right to control the distribution of derivative or
|
||||
collective works based on the Library.
|
||||
|
||||
In addition, mere aggregation of another work not based on the Library
|
||||
with the Library (or with a work based on the Library) on a volume of
|
||||
a storage or distribution medium does not bring the other work under
|
||||
the scope of this License.
|
||||
|
||||
3. You may opt to apply the terms of the ordinary GNU General Public
|
||||
License instead of this License to a given copy of the Library. To do
|
||||
this, you must alter all the notices that refer to this License, so
|
||||
that they refer to the ordinary GNU General Public License, version 2,
|
||||
instead of to this License. (If a newer version than version 2 of the
|
||||
ordinary GNU General Public License has appeared, then you can specify
|
||||
that version instead if you wish.) Do not make any other change in
|
||||
these notices.
|
||||
|
||||
Once this change is made in a given copy, it is irreversible for
|
||||
that copy, so the ordinary GNU General Public License applies to all
|
||||
subsequent copies and derivative works made from that copy.
|
||||
|
||||
This option is useful when you wish to copy part of the code of
|
||||
the Library into a program that is not a library.
|
||||
|
||||
4. You may copy and distribute the Library (or a portion or
|
||||
derivative of it, under Section 2) in object code or executable form
|
||||
under the terms of Sections 1 and 2 above provided that you accompany
|
||||
it with the complete corresponding machine-readable source code, which
|
||||
must be distributed under the terms of Sections 1 and 2 above on a
|
||||
medium customarily used for software interchange.
|
||||
|
||||
If distribution of object code is made by offering access to copy
|
||||
from a designated place, then offering equivalent access to copy the
|
||||
source code from the same place satisfies the requirement to
|
||||
distribute the source code, even though third parties are not
|
||||
compelled to copy the source along with the object code.
|
||||
|
||||
5. A program that contains no derivative of any portion of the
|
||||
Library, but is designed to work with the Library by being compiled or
|
||||
linked with it, is called a "work that uses the Library". Such a
|
||||
work, in isolation, is not a derivative work of the Library, and
|
||||
therefore falls outside the scope of this License.
|
||||
|
||||
However, linking a "work that uses the Library" with the Library
|
||||
creates an executable that is a derivative of the Library (because it
|
||||
contains portions of the Library), rather than a "work that uses the
|
||||
library". The executable is therefore covered by this License.
|
||||
Section 6 states terms for distribution of such executables.
|
||||
|
||||
When a "work that uses the Library" uses material from a header file
|
||||
that is part of the Library, the object code for the work may be a
|
||||
derivative work of the Library even though the source code is not.
|
||||
Whether this is true is especially significant if the work can be
|
||||
linked without the Library, or if the work is itself a library. The
|
||||
threshold for this to be true is not precisely defined by law.
|
||||
|
||||
If such an object file uses only numerical parameters, data
|
||||
structure layouts and accessors, and small macros and small inline
|
||||
functions (ten lines or less in length), then the use of the object
|
||||
file is unrestricted, regardless of whether it is legally a derivative
|
||||
work. (Executables containing this object code plus portions of the
|
||||
Library will still fall under Section 6.)
|
||||
|
||||
Otherwise, if the work is a derivative of the Library, you may
|
||||
distribute the object code for the work under the terms of Section 6.
|
||||
Any executables containing that work also fall under Section 6,
|
||||
whether or not they are linked directly with the Library itself.
|
||||
|
||||
6. As an exception to the Sections above, you may also combine or
|
||||
link a "work that uses the Library" with the Library to produce a
|
||||
work containing portions of the Library, and distribute that work
|
||||
under terms of your choice, provided that the terms permit
|
||||
modification of the work for the customer's own use and reverse
|
||||
engineering for debugging such modifications.
|
||||
|
||||
You must give prominent notice with each copy of the work that the
|
||||
Library is used in it and that the Library and its use are covered by
|
||||
this License. You must supply a copy of this License. If the work
|
||||
during execution displays copyright notices, you must include the
|
||||
copyright notice for the Library among them, as well as a reference
|
||||
directing the user to the copy of this License. Also, you must do one
|
||||
of these things:
|
||||
|
||||
a) Accompany the work with the complete corresponding
|
||||
machine-readable source code for the Library including whatever
|
||||
changes were used in the work (which must be distributed under
|
||||
Sections 1 and 2 above); and, if the work is an executable linked
|
||||
with the Library, with the complete machine-readable "work that
|
||||
uses the Library", as object code and/or source code, so that the
|
||||
user can modify the Library and then relink to produce a modified
|
||||
executable containing the modified Library. (It is understood
|
||||
that the user who changes the contents of definitions files in the
|
||||
Library will not necessarily be able to recompile the application
|
||||
to use the modified definitions.)
|
||||
|
||||
b) Use a suitable shared library mechanism for linking with the
|
||||
Library. A suitable mechanism is one that (1) uses at run time a
|
||||
copy of the library already present on the user's computer system,
|
||||
rather than copying library functions into the executable, and (2)
|
||||
will operate properly with a modified version of the library, if
|
||||
the user installs one, as long as the modified version is
|
||||
interface-compatible with the version that the work was made with.
|
||||
|
||||
c) Accompany the work with a written offer, valid for at
|
||||
least three years, to give the same user the materials
|
||||
specified in Subsection 6a, above, for a charge no more
|
||||
than the cost of performing this distribution.
|
||||
|
||||
d) If distribution of the work is made by offering access to copy
|
||||
from a designated place, offer equivalent access to copy the above
|
||||
specified materials from the same place.
|
||||
|
||||
e) Verify that the user has already received a copy of these
|
||||
materials or that you have already sent this user a copy.
|
||||
|
||||
For an executable, the required form of the "work that uses the
|
||||
Library" must include any data and utility programs needed for
|
||||
reproducing the executable from it. However, as a special exception,
|
||||
the materials to be distributed need not include anything that is
|
||||
normally distributed (in either source or binary form) with the major
|
||||
components (compiler, kernel, and so on) of the operating system on
|
||||
which the executable runs, unless that component itself accompanies
|
||||
the executable.
|
||||
|
||||
It may happen that this requirement contradicts the license
|
||||
restrictions of other proprietary libraries that do not normally
|
||||
accompany the operating system. Such a contradiction means you cannot
|
||||
use both them and the Library together in an executable that you
|
||||
distribute.
|
||||
|
||||
7. You may place library facilities that are a work based on the
|
||||
Library side-by-side in a single library together with other library
|
||||
facilities not covered by this License, and distribute such a combined
|
||||
library, provided that the separate distribution of the work based on
|
||||
the Library and of the other library facilities is otherwise
|
||||
permitted, and provided that you do these two things:
|
||||
|
||||
a) Accompany the combined library with a copy of the same work
|
||||
based on the Library, uncombined with any other library
|
||||
facilities. This must be distributed under the terms of the
|
||||
Sections above.
|
||||
|
||||
b) Give prominent notice with the combined library of the fact
|
||||
that part of it is a work based on the Library, and explaining
|
||||
where to find the accompanying uncombined form of the same work.
|
||||
|
||||
8. You may not copy, modify, sublicense, link with, or distribute
|
||||
the Library except as expressly provided under this License. Any
|
||||
attempt otherwise to copy, modify, sublicense, link with, or
|
||||
distribute the Library is void, and will automatically terminate your
|
||||
rights under this License. However, parties who have received copies,
|
||||
or rights, from you under this License will not have their licenses
|
||||
terminated so long as such parties remain in full compliance.
|
||||
|
||||
9. You are not required to accept this License, since you have not
|
||||
signed it. However, nothing else grants you permission to modify or
|
||||
distribute the Library or its derivative works. These actions are
|
||||
prohibited by law if you do not accept this License. Therefore, by
|
||||
modifying or distributing the Library (or any work based on the
|
||||
Library), you indicate your acceptance of this License to do so, and
|
||||
all its terms and conditions for copying, distributing or modifying
|
||||
the Library or works based on it.
|
||||
|
||||
10. Each time you redistribute the Library (or any work based on the
|
||||
Library), the recipient automatically receives a license from the
|
||||
original licensor to copy, distribute, link with or modify the Library
|
||||
subject to these terms and conditions. You may not impose any further
|
||||
restrictions on the recipients' exercise of the rights granted herein.
|
||||
You are not responsible for enforcing compliance by third parties with
|
||||
this License.
|
||||
|
||||
11. If, as a consequence of a court judgment or allegation of patent
|
||||
infringement or for any other reason (not limited to patent issues),
|
||||
conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot
|
||||
distribute so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you
|
||||
may not distribute the Library at all. For example, if a patent
|
||||
license would not permit royalty-free redistribution of the Library by
|
||||
all those who receive copies directly or indirectly through you, then
|
||||
the only way you could satisfy both it and this License would be to
|
||||
refrain entirely from distribution of the Library.
|
||||
|
||||
If any portion of this section is held invalid or unenforceable under any
|
||||
particular circumstance, the balance of the section is intended to apply,
|
||||
and the section as a whole is intended to apply in other circumstances.
|
||||
|
||||
It is not the purpose of this section to induce you to infringe any
|
||||
patents or other property right claims or to contest validity of any
|
||||
such claims; this section has the sole purpose of protecting the
|
||||
integrity of the free software distribution system which is
|
||||
implemented by public license practices. Many people have made
|
||||
generous contributions to the wide range of software distributed
|
||||
through that system in reliance on consistent application of that
|
||||
system; it is up to the author/donor to decide if he or she is willing
|
||||
to distribute software through any other system and a licensee cannot
|
||||
impose that choice.
|
||||
|
||||
This section is intended to make thoroughly clear what is believed to
|
||||
be a consequence of the rest of this License.
|
||||
|
||||
12. If the distribution and/or use of the Library is restricted in
|
||||
certain countries either by patents or by copyrighted interfaces, the
|
||||
original copyright holder who places the Library under this License may add
|
||||
an explicit geographical distribution limitation excluding those countries,
|
||||
so that distribution is permitted only in or among countries not thus
|
||||
excluded. In such case, this License incorporates the limitation as if
|
||||
written in the body of this License.
|
||||
|
||||
13. The Free Software Foundation may publish revised and/or new
|
||||
versions of the Lesser General Public License from time to time.
|
||||
Such new versions will be similar in spirit to the present version,
|
||||
but may differ in detail to address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the Library
|
||||
specifies a version number of this License which applies to it and
|
||||
"any later version", you have the option of following the terms and
|
||||
conditions either of that version or of any later version published by
|
||||
the Free Software Foundation. If the Library does not specify a
|
||||
license version number, you may choose any version ever published by
|
||||
the Free Software Foundation.
|
||||
|
||||
14. If you wish to incorporate parts of the Library into other free
|
||||
programs whose distribution conditions are incompatible with these,
|
||||
write to the author to ask for permission. For software which is
|
||||
copyrighted by the Free Software Foundation, write to the Free
|
||||
Software Foundation; we sometimes make exceptions for this. Our
|
||||
decision will be guided by the two goals of preserving the free status
|
||||
of all derivatives of our free software and of promoting the sharing
|
||||
and reuse of software generally.
|
||||
|
||||
NO WARRANTY
|
||||
|
||||
15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
|
||||
WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
|
||||
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
|
||||
OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
|
||||
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
|
||||
LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
|
||||
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
|
||||
WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
|
||||
AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
|
||||
FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
|
||||
CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
|
||||
LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
|
||||
RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
|
||||
FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
|
||||
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
|
||||
DAMAGES.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Libraries
|
||||
|
||||
If you develop a new library, and you want it to be of the greatest
|
||||
possible use to the public, we recommend making it free software that
|
||||
everyone can redistribute and change. You can do so by permitting
|
||||
redistribution under these terms (or, alternatively, under the terms of the
|
||||
ordinary General Public License).
|
||||
|
||||
To apply these terms, attach the following notices to the library. It is
|
||||
safest to attach them to the start of each source file to most effectively
|
||||
convey the exclusion of warranty; and each file should have at least the
|
||||
"copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the library's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2.1 of the License, or (at your option) any later version.
|
||||
|
||||
This library is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public
|
||||
License along with this library; if not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or your
|
||||
school, if any, to sign a "copyright disclaimer" for the library, if
|
||||
necessary. Here is a sample; alter the names:
|
||||
|
||||
Yoyodyne, Inc., hereby disclaims all copyright interest in the
|
||||
library `Frob' (a library for tweaking knobs) written by James Random Hacker.
|
||||
|
||||
<signature of Moe Ghoul>, 1 April 1990
|
||||
Moe Ghoul, President of Vice
|
||||
|
||||
That's all there is to it!
|
||||
@@ -0,0 +1,14 @@
|
||||
Windows components installer tools (usr/local/lib/droiddeck-msitools), Arch Linux ARM's aarch64
|
||||
builds, unchanged:
|
||||
|
||||
msiinfo, libmsi-1.0.so.0 msitools 0.106 GPL-2.0-or-later / LGPL-2.1-or-later
|
||||
https://gitlab.gnome.org/GNOME/msitools
|
||||
libgsf-1.so.114 libgsf 1.14.60 LGPL-2.1-only
|
||||
https://gitlab.gnome.org/GNOME/libgsf
|
||||
libgcab-1.0.so.0 gcab 1.6 LGPL-2.1-or-later
|
||||
https://gitlab.gnome.org/GNOME/gcab
|
||||
cabextract cabextract 1.11 GPL-3.0-or-later
|
||||
https://www.cabextract.org.uk/
|
||||
|
||||
The packages and their sources: https://github.com/Droid-Deck/DroidDeck/releases/tag/msitools-0.106-r1,
|
||||
https://github.com/archlinuxarm/PKGBUILDs. The licence texts are beside this file.
|
||||
@@ -0,0 +1,12 @@
|
||||
# What droiddeck-msi-install runs: msitools' msiinfo reads a Windows Installer package's tables
|
||||
# and streams, cabextract unpacks its cabinets (every compression a cabinet can use, which gcab
|
||||
# alone cannot). Arch Linux ARM's aarch64 packages, hosted unchanged on this repo's
|
||||
# msitools-0.106-r1 release because the mirror keeps only the newest of each. CI fetches each,
|
||||
# checks the sha256 and stages the files below into the apk under usr/local/lib/droiddeck-msitools;
|
||||
# SessionFiles copies them into the runtime at every launch. Everything else they need (glib, gio,
|
||||
# libxml2.so.16, zlib, bzip2, libgcc_s) is in the runtime already.
|
||||
# sha256 url
|
||||
4ab93d800b320d19c6c1090e21b69e5764ee241b6370012459e0c5df03739a8d https://github.com/Droid-Deck/DroidDeck/releases/download/msitools-0.106-r1/msitools-0.106-3-aarch64.pkg.tar.xz
|
||||
4028f44d83b2956ba2931d32aee8cceecbd6481e2febf86a3b6bfed69ef403d5 https://github.com/Droid-Deck/DroidDeck/releases/download/msitools-0.106-r1/libgsf-1.14.60-1-aarch64.pkg.tar.xz
|
||||
3d7bd103313cb36d6cb703a5e583363e56ff255f105bcc0727916d195967976d https://github.com/Droid-Deck/DroidDeck/releases/download/msitools-0.106-r1/gcab-1.6-2-aarch64.pkg.tar.xz
|
||||
87fe375a22de1519982234ce99f909ae13c06500784baaa1e8d7a0c0be0d14ee https://github.com/Droid-Deck/DroidDeck/releases/download/msitools-0.106-r1/cabextract-1.11-3-aarch64.pkg.tar.xz
|
||||
@@ -48,7 +48,10 @@
|
||||
|
||||
#define FP_STUB_ADDR 0xffff00000UL /* must match FASTPATH_STUB_ADDR in proot's seccomp.c */
|
||||
#define FP_STUB_SIZE 4096UL
|
||||
#define MAX_BINDS 64
|
||||
/* A session binds 80-odd paths (devices, the Steam libraries, each Games folder...). More than fit,
|
||||
* or one that cannot be held, turns the fast path off: a bind it did not know would map that
|
||||
* guest path into the rootfs instead (an empty mount point), which proot never does. */
|
||||
#define MAX_BINDS 256
|
||||
#define FP_SLOW (-100000L)
|
||||
|
||||
typedef long (*stub_fn)(long nr, long a, long b, long c, long d, long e, long f);
|
||||
@@ -162,7 +165,9 @@ static void fp_init(void) {
|
||||
snprintf(root, sizeof root, "%s", r);
|
||||
canonical(root, sizeof root);
|
||||
rootlen = strlen(root);
|
||||
for (const char *s = b; s && *s && nbinds < MAX_BINDS;) {
|
||||
const char *s = b;
|
||||
int unheld = 0;
|
||||
for (; s && *s && nbinds < MAX_BINDS;) {
|
||||
const char *end = strchr(s, '|');
|
||||
size_t len = end ? (size_t)(end - s) : strlen(s);
|
||||
char spec[2 * PATH_MAX];
|
||||
@@ -176,7 +181,7 @@ static void fp_init(void) {
|
||||
* Static storage: malloc here would grow the heap with brk(2), which proot traps. */
|
||||
static char hosts[MAX_BINDS][PATH_MAX], guests[MAX_BINDS][512];
|
||||
const char *g = colon ? colon + 1 : spec;
|
||||
if (strlen(g) >= sizeof guests[0]) { s = end ? end + 1 : NULL; continue; }
|
||||
if (strlen(g) >= sizeof guests[0]) { unheld = 1; break; }
|
||||
bd->host = hosts[nbinds];
|
||||
bd->guest = guests[nbinds];
|
||||
snprintf(bd->guest, sizeof guests[0], "%s", g);
|
||||
@@ -184,9 +189,13 @@ static void fp_init(void) {
|
||||
bd->hlen = strlen(bd->host);
|
||||
bd->glen = strlen(bd->guest);
|
||||
if (bd->guest[0] == '/' && bd->glen > 1 && bd->hlen > 0) nbinds++;
|
||||
} else if (len > 0) {
|
||||
unheld = 1;
|
||||
break;
|
||||
}
|
||||
s = end ? end + 1 : NULL;
|
||||
}
|
||||
if (unheld || (s && *s)) { fp_sys = NULL; return; }
|
||||
pthread_atfork(NULL, NULL, after_fork); /* registered once per exec */
|
||||
fp_on = 1;
|
||||
if (getenv("PROOT_FP_STATS")) atexit(stats);
|
||||
|
||||
@@ -26,6 +26,25 @@ def config_text(entries):
|
||||
|
||||
|
||||
class GameEnvironmentTest(unittest.TestCase):
|
||||
def test_the_install_script_evaluator_gets_its_scripts_marked_first(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
script = root / "legacycompat/evaluatorscript_409710.vdf"
|
||||
script.parent.mkdir(parents=True)
|
||||
script.write_text("{}")
|
||||
calls = []
|
||||
run = MODULE["mark_install_scripts"].__globals__["subprocess"].run
|
||||
MODULE["mark_install_scripts"].__globals__["subprocess"].run = lambda args, **kw: calls.append((args, kw["env"]))
|
||||
try:
|
||||
env = {"STEAM_COMPAT_CLIENT_INSTALL_PATH": str(root)}
|
||||
MODULE["mark_install_scripts"](["/proton", "run", str(root / "legacycompat/iscriptevaluator.exe"), "legacycompat\\evaluatorscript_409710.vdf"], env)
|
||||
MODULE["mark_install_scripts"](["/proton", "waitforexitandrun", "/game/Game.exe"], env)
|
||||
finally:
|
||||
MODULE["mark_install_scripts"].__globals__["subprocess"].run = run
|
||||
self.assertEqual(len(calls), 1)
|
||||
self.assertEqual(calls[0][0][1], str(root))
|
||||
self.assertEqual(calls[0][1]["DROIDDECK_SEED_SCRIPTS"], str(script))
|
||||
|
||||
def test_profile_precedence_and_unset(self):
|
||||
env = {"KEEP": "inherited", "REMOVE": "inherited", "CUSTOM": "launch option"}
|
||||
config = {"version": 1, "shared": {"CUSTOM": "shared"}, "games": {"42": {"REMOVE": None, "CUSTOM": "game", "EMPTY": ""}}}
|
||||
@@ -461,3 +480,27 @@ class DirectAudioPrefixTest(unittest.TestCase):
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
|
||||
class ForceSsbsTest(unittest.TestCase):
|
||||
def test_libssbs_is_preloaded_only_when_asked_and_only_into_arm64_proton(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
arm = Path(tmp) / "arm"
|
||||
(arm / "files/lib/wine/aarch64-unix").mkdir(parents=True)
|
||||
x86 = Path(tmp) / "x86"
|
||||
(x86 / "files/lib/wine/x86_64-unix").mkdir(parents=True)
|
||||
lib = Path(tmp) / "libssbs.so"
|
||||
lib.write_bytes(b"\x7fELF")
|
||||
g = MODULE["force_ssbs"].__globals__
|
||||
old = g["SSBS_LIB"]
|
||||
g["SSBS_LIB"] = str(lib)
|
||||
try:
|
||||
env = {"LD_PRELOAD": "/usr/local/lib/libblsession.so"}
|
||||
self.assertEqual(MODULE["force_ssbs"]([str(arm / "proton"), "waitforexitandrun"], env), env)
|
||||
on = dict(env, DROIDDECK_FORCE_SSBS="1")
|
||||
got = MODULE["force_ssbs"]([str(arm / "proton"), "waitforexitandrun"], on)
|
||||
self.assertEqual(got["LD_PRELOAD"], "/usr/local/lib/libblsession.so:" + str(lib))
|
||||
self.assertEqual(MODULE["force_ssbs"]([str(arm / "proton")], got)["LD_PRELOAD"], got["LD_PRELOAD"])
|
||||
self.assertEqual(MODULE["force_ssbs"]([str(x86 / "proton")], on), on)
|
||||
finally:
|
||||
g["SSBS_LIB"] = old
|
||||
@@ -140,23 +140,15 @@ class SleepHandshakeTest(unittest.TestCase):
|
||||
staged.replace(self.dir / "steam-native-sleep")
|
||||
return token
|
||||
|
||||
def inhibitor(self, who="Steam", mode="delay", what="sleep"):
|
||||
result, descriptors = self.bus.call_with_unix_fd_list_sync(
|
||||
NAME, ROOT, IFACE, "Inhibit", GLib.Variant("(ssss)", (what, who, "Preparing sleep", mode)),
|
||||
GLib.VariantType.new("(h)"), Gio.DBusCallFlags.NONE, 2000, None, None)
|
||||
return descriptors.get(result.unpack()[0])
|
||||
|
||||
def test_native_sleep_prepares_before_host_can_freeze(self):
|
||||
descriptor = self.inhibitor()
|
||||
started = time.monotonic()
|
||||
token = self.request_native()
|
||||
self.wait_for(lambda: self.signals == [True])
|
||||
self.assertTrue(self.preparing())
|
||||
self.assertFalse((self.dir / "steam-native-ready").exists())
|
||||
self.assertFalse((self.dir / "steam-sleep").exists())
|
||||
time.sleep(1.7)
|
||||
self.assertFalse((self.dir / "steam-native-ready").exists())
|
||||
os.close(descriptor)
|
||||
self.wait_for(lambda: (self.dir / "steam-native-ready").exists())
|
||||
self.assertGreaterEqual(time.monotonic() - started, 1.4)
|
||||
self.assertEqual((self.dir / "steam-native-ready").read_text().strip(), token)
|
||||
self.state(token, "paused")
|
||||
self.state(token, "awake")
|
||||
@@ -164,12 +156,10 @@ class SleepHandshakeTest(unittest.TestCase):
|
||||
self.assertFalse(self.preparing())
|
||||
|
||||
def test_return_during_native_preparation_cancels_late_pause(self):
|
||||
descriptor = self.inhibitor()
|
||||
token = self.request_native()
|
||||
self.wait_for(lambda: self.signals == [True])
|
||||
self.state(token, "awake")
|
||||
self.wait_for(lambda: self.signals == [True, False])
|
||||
os.close(descriptor)
|
||||
time.sleep(1.7)
|
||||
self.assertFalse((self.dir / "steam-native-ready").exists())
|
||||
self.assertFalse(self.preparing())
|
||||
@@ -186,19 +176,12 @@ class SleepHandshakeTest(unittest.TestCase):
|
||||
self.assertEqual(self.signals, [])
|
||||
|
||||
def test_second_native_sleep_cannot_receive_first_preparation_callback(self):
|
||||
stale = self.inhibitor()
|
||||
first = self.request_native()
|
||||
self.wait_for(lambda: self.signals == [True])
|
||||
self.state(first, "awake")
|
||||
self.wait_for(lambda: self.signals == [True, False])
|
||||
current = self.inhibitor()
|
||||
self.signals.clear()
|
||||
second = self.request_native("2" * 32)
|
||||
self.wait_for(lambda: self.signals == [True])
|
||||
os.close(stale)
|
||||
time.sleep(0.1)
|
||||
self.assertFalse((self.dir / "steam-native-ready").exists())
|
||||
os.close(current)
|
||||
self.wait_for(lambda: (self.dir / "steam-native-ready").exists())
|
||||
self.assertEqual((self.dir / "steam-native-ready").read_text().strip(), second)
|
||||
self.state(second, "awake")
|
||||
@@ -206,62 +189,10 @@ class SleepHandshakeTest(unittest.TestCase):
|
||||
|
||||
def test_native_sleep_with_missing_host_recovers(self):
|
||||
self.request_native()
|
||||
self.wait_for(lambda: self.signals == [True, False], timeout=14)
|
||||
self.wait_for(lambda: self.signals == [True, False], timeout=9)
|
||||
self.assertFalse(self.preparing())
|
||||
self.assertFalse((self.dir / "steam-native-ready").exists())
|
||||
|
||||
def test_no_steam_acknowledgement_does_not_publish_ready(self):
|
||||
descriptor = self.inhibitor(who="Other client")
|
||||
token = self.request_native()
|
||||
self.wait_for(lambda: self.signals == [True])
|
||||
os.close(descriptor)
|
||||
time.sleep(1.7)
|
||||
self.assertFalse((self.dir / "steam-native-ready").exists())
|
||||
self.state(token, "paused") # host's ten-second fallback
|
||||
self.state(token, "awake")
|
||||
self.wait_for(lambda: self.signals == [True, False])
|
||||
|
||||
def test_block_inhibitor_is_not_a_steam_acknowledgement(self):
|
||||
descriptor = self.inhibitor(mode="block")
|
||||
token = self.request_native()
|
||||
self.wait_for(lambda: self.signals == [True])
|
||||
os.close(descriptor)
|
||||
time.sleep(0.1)
|
||||
self.assertFalse((self.dir / "steam-native-ready").exists())
|
||||
self.state(token, "awake")
|
||||
self.wait_for(lambda: self.signals == [True, False])
|
||||
|
||||
def test_delay_fd_duplicates_must_all_be_closed(self):
|
||||
descriptor = self.inhibitor()
|
||||
duplicate = os.dup(descriptor)
|
||||
token = self.request_native()
|
||||
self.wait_for(lambda: self.signals == [True])
|
||||
os.close(descriptor)
|
||||
time.sleep(0.1)
|
||||
self.assertFalse((self.dir / "steam-native-ready").exists())
|
||||
os.close(duplicate)
|
||||
self.wait_for(lambda: (self.dir / "steam-native-ready").exists())
|
||||
self.state(token, "awake")
|
||||
self.wait_for(lambda: self.signals == [True, False])
|
||||
|
||||
def test_disconnected_steam_client_does_not_confirm_preparation(self):
|
||||
original = self.bus
|
||||
client = Gio.DBusConnection.new_for_address_sync(
|
||||
os.environ["DBUS_SESSION_BUS_ADDRESS"],
|
||||
Gio.DBusConnectionFlags.AUTHENTICATION_CLIENT | Gio.DBusConnectionFlags.MESSAGE_BUS_CONNECTION,
|
||||
None, None)
|
||||
self.bus = client
|
||||
descriptor = self.inhibitor()
|
||||
self.bus = original
|
||||
token = self.request_native()
|
||||
self.wait_for(lambda: self.signals == [True])
|
||||
client.close_sync(None)
|
||||
os.close(descriptor)
|
||||
time.sleep(0.2)
|
||||
self.assertFalse((self.dir / "steam-native-ready").exists())
|
||||
self.state(token, "awake")
|
||||
self.wait_for(lambda: self.signals == [True, False])
|
||||
|
||||
def test_host_resume_recovers_without_a_sleep_request(self):
|
||||
self.assertFalse(self.preparing())
|
||||
self.request_wake()
|
||||
|
||||
@@ -0,0 +1,292 @@
|
||||
import json
|
||||
import runpy
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
BIN = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin"
|
||||
MSI = runpy.run_path(str(BIN / "droiddeck-msi-install"))
|
||||
COMPONENTS = runpy.run_path(str(BIN / "droiddeck-wincomponents"))
|
||||
|
||||
|
||||
class FakePackage:
|
||||
"""A package's tables in memory, as msiinfo would give them."""
|
||||
|
||||
def __init__(self, tables, summary=None):
|
||||
self.path = "fake.msi"
|
||||
self.tables = tables
|
||||
self.table_names = set(tables)
|
||||
self.summary = summary or {"template": "Intel;1033"}
|
||||
|
||||
def table(self, name):
|
||||
return self.tables.get(name, [])
|
||||
|
||||
def stream(self, name, target):
|
||||
raise AssertionError("no cabinets in a fake package")
|
||||
|
||||
|
||||
def rows(columns, *values):
|
||||
names = columns.split()
|
||||
return [dict(zip(names, value)) for value in values]
|
||||
|
||||
|
||||
def installer(tables, out="/tmp/unused", summary=None):
|
||||
return MSI["Installer"]("fake.msi", out, FakePackage(tables, summary))
|
||||
|
||||
|
||||
class ToolsTest(unittest.TestCase):
|
||||
def test_the_tools_find_their_own_libraries(self):
|
||||
paths = MSI["tool_env"]()["LD_LIBRARY_PATH"].split(":")
|
||||
self.assertEqual(paths[0], str(MSI["TOOLS"]))
|
||||
|
||||
|
||||
class ConditionsTest(unittest.TestCase):
|
||||
def evaluate(self, text, props=None, default="default"):
|
||||
return MSI["Conditions"](props or {"VersionNT": "603", "VersionNT64": "603"}).evaluate(text, default)
|
||||
|
||||
def test_windows_10_64_bit_passes_the_usual_checks(self):
|
||||
self.assertTrue(self.evaluate("(VersionNT > 501) OR (VersionNT = 501 AND ServicePackLevel >= 2)"))
|
||||
self.assertTrue(self.evaluate("VersionNT64"))
|
||||
self.assertTrue(self.evaluate("VersionNT AND (VersionNT >= 500)"))
|
||||
self.assertFalse(self.evaluate("(VersionNT < 501) or Version9X"))
|
||||
self.assertFalse(self.evaluate("(VersionNT < 600) or Version9X"))
|
||||
|
||||
def test_unset_properties_are_false_and_not_inverts(self):
|
||||
self.assertFalse(self.evaluate("NEWERVERSIONDETECTED"))
|
||||
self.assertTrue(self.evaluate("NOT Installed"))
|
||||
self.assertFalse(self.evaluate("Installed AND NOT REINSTALL"))
|
||||
|
||||
def test_strings_and_case_folding(self):
|
||||
props = {"A": "Hello"}
|
||||
self.assertTrue(self.evaluate('A = "Hello"', props))
|
||||
self.assertFalse(self.evaluate('A = "hello"', props))
|
||||
self.assertTrue(self.evaluate('A ~= "hello"', props))
|
||||
self.assertTrue(self.evaluate('A >< "ell"', props))
|
||||
|
||||
def test_component_and_feature_states(self):
|
||||
conditions = MSI["Conditions"]({}, lambda f: 3 if f == "Main" else None, lambda c: 3 if c == "Dll" else None)
|
||||
self.assertTrue(conditions.evaluate("&Main = 3"))
|
||||
self.assertTrue(conditions.evaluate("$Dll = 3"))
|
||||
self.assertFalse(conditions.evaluate("$Other = 3"))
|
||||
|
||||
def test_nonsense_gives_the_default(self):
|
||||
self.assertEqual(self.evaluate("(VersionNT >"), "default")
|
||||
|
||||
|
||||
class LayoutTest(unittest.TestCase):
|
||||
def test_folders_resolve_as_on_64_bit_windows(self):
|
||||
inst = installer({
|
||||
"Directory": rows("Directory Directory_Parent DefaultDir",
|
||||
("TARGETDIR", "", "SourceDir"),
|
||||
("ProgramFilesFolder", "TARGETDIR", "PFiles"),
|
||||
("INSTALLDIR", "ProgramFilesFolder", "xendvbfk|Microsoft XNA"),
|
||||
("Same", "INSTALLDIR", "."),
|
||||
("SystemFolder", "TARGETDIR", "SysFldr"),
|
||||
("TempFolder", "TARGETDIR", "TmpFldr"),
|
||||
("Temp2", "TempFolder", "x")),
|
||||
})
|
||||
self.assertEqual(inst.directory("INSTALLDIR"), "drive_c/Program Files (x86)/Microsoft XNA")
|
||||
self.assertEqual(inst.directory("Same"), "drive_c/Program Files (x86)/Microsoft XNA")
|
||||
self.assertEqual(inst.directory("SystemFolder"), "drive_c/windows/syswow64")
|
||||
self.assertIsNone(inst.directory("Temp2"))
|
||||
|
||||
def test_a_folder_set_by_a_custom_action_wins(self):
|
||||
inst = installer({
|
||||
"Directory": rows("Directory Directory_Parent DefaultDir",
|
||||
("TARGETDIR", "", "SourceDir"),
|
||||
("WinVC", "TARGETDIR", "Win"),
|
||||
("SysVC", "WinVC", "System")),
|
||||
"CustomAction": rows("Action Type Source Target",
|
||||
("SetSys", "51", "SysVC", "[SystemFolder]"),
|
||||
("RunIt", "3154", "File", "/silent")),
|
||||
"InstallExecuteSequence": rows("Action Condition Sequence", ("SetSys", "", "2"), ("RunIt", "NOT Installed", "6000")),
|
||||
})
|
||||
inst.run_set_actions()
|
||||
self.assertEqual(inst.directory("SysVC"), "drive_c/windows/syswow64")
|
||||
self.assertIn("RunIt", inst.notes[0])
|
||||
|
||||
def test_conditions_pick_components_and_features(self):
|
||||
inst = installer({
|
||||
"Feature": rows("Feature Feature_Parent Level", ("Main", "", "1"), ("X64", "", "0"), ("Off", "", "0")),
|
||||
"Condition": rows("Feature_ Level Condition", ("X64", "1", "VersionNT64")),
|
||||
"Component": rows("Component Directory_ Attributes Condition",
|
||||
("Up", "TARGETDIR", "0", "(VersionNT >= 600)"),
|
||||
("Down", "TARGETDIR", "0", "(VersionNT < 600) or Version9X"),
|
||||
("Wide", "TARGETDIR", "256", ""),
|
||||
("Never", "TARGETDIR", "0", "")),
|
||||
"FeatureComponents": rows("Feature_ Component_", ("Main", "Up"), ("Main", "Down"), ("X64", "Wide"), ("Off", "Never")),
|
||||
})
|
||||
inst.select()
|
||||
self.assertEqual(inst.included_components, {"Up", "Wide"})
|
||||
|
||||
def test_global_assembly_paths(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
dll = Path(tmp) / "a.dll"
|
||||
dll.write_bytes(b"MZ....BSJB" + b"\0" * 8 + (12).to_bytes(4, "little") + b"v4.0.30319\0\0")
|
||||
inst = installer({})
|
||||
folder = inst.gac_folder({"name": "Microsoft.Xna.Framework", "version": "4.0.0.00000", "culture": "neutral",
|
||||
"publickeytoken": "842CF8BE1DE50553", "processorarchitecture": "x86"}, dll)
|
||||
self.assertEqual(folder, "drive_c/windows/Microsoft.NET/assembly/GAC_32/Microsoft.Xna.Framework/v4.0_4.0.0.0__842cf8be1de50553")
|
||||
dll.write_bytes(b"MZ....BSJB" + b"\0" * 8 + (12).to_bytes(4, "little") + b"v2.0.50727\0\0")
|
||||
folder = inst.gac_folder({"name": "Old", "version": "1.0.0.0", "publickeytoken": "AB", "processorarchitecture": "MSIL"}, dll)
|
||||
self.assertEqual(folder, "drive_c/windows/assembly/GAC_MSIL/Old/1.0.0.0__ab")
|
||||
|
||||
def test_side_by_side_names_follow_wines_winsxs(self):
|
||||
names = MSI["Installer"].sxs_names
|
||||
ident = {"name": "Microsoft.VC80.CRT", "publickeytoken": "1fc8b3b9a1e18e3b", "version": "8.0.50727.762",
|
||||
"processorarchitecture": "x86", "type": "win32"}
|
||||
self.assertEqual(names(ident), ("assembly", "x86_microsoft.vc80.crt_1fc8b3b9a1e18e3b_8.0.50727.762_none_deadbeef", "8.0.50727.762"))
|
||||
policy = dict(ident, name="policy.8.0.Microsoft.VC80.CRT", type="win32-policy")
|
||||
self.assertEqual(names(policy)[1], "drive_c/windows/winsxs/policies/x86_microsoft.vc80.crt_1fc8b3b9a1e18e3b_none_deadbeef")
|
||||
|
||||
def test_registry_values_go_to_the_32_bit_view_for_32_bit_components(self):
|
||||
inst = installer({
|
||||
"Directory": rows("Directory Directory_Parent DefaultDir", ("TARGETDIR", "", "SourceDir"),
|
||||
("CommonV2Dir", "TARGETDIR", "XNA")),
|
||||
"Component": rows("Component Directory_ Attributes Condition", ("C32", "TARGETDIR", "0", ""),
|
||||
("C64", "TARGETDIR", "256", "")),
|
||||
"Registry": rows("Registry Root Key Name Value Component_",
|
||||
("r1", "2", "Software\\Microsoft\\XNA\\Framework\\v4.0", "Installed", "#1", "C32"),
|
||||
("r2", "2", "Software\\Microsoft\\XNA\\Framework\\v4.0", "NativeLibraryPath", "[CommonV2Dir]", "C32"),
|
||||
("r3", "0", "CLSID\\{X}\\InprocServer32", "", "a[~]b", "C32"),
|
||||
("r4", "2", "SOFTWARE\\AGEIA", "Bin", "#x0A0b", "C64"),
|
||||
("r5", "2", "Software\\Keys", "+", "", "C64")),
|
||||
"Environment": rows("Environment Name Value Component_", ("e", "=-*PATH", "[CommonV2Dir];[~]", "C32")),
|
||||
})
|
||||
inst.select()
|
||||
inst.install_registry()
|
||||
got = {(v["key"], v["name"]): (v["type"], v["data"]) for v in inst.registry}
|
||||
self.assertEqual(got[("Software\\Wow6432Node\\Microsoft\\XNA\\Framework\\v4.0", "Installed")], ("dword", 1))
|
||||
self.assertEqual(got[("Software\\Wow6432Node\\Microsoft\\XNA\\Framework\\v4.0", "NativeLibraryPath")], ("sz", "C:\\XNA\\"))
|
||||
self.assertEqual(got[("Software\\Wow6432Node\\Classes\\CLSID\\{X}\\InprocServer32", "")], ("multi_sz", ["a", "b"]))
|
||||
self.assertEqual(got[("SOFTWARE\\AGEIA", "Bin")], ("binary", "0a0b"))
|
||||
self.assertEqual(got[("Software\\Keys", None)], ("key", None))
|
||||
env = [v for v in inst.registry if v["name"] == "PATH"][0]
|
||||
self.assertEqual((env["key"], env["type"], env["data"]),
|
||||
("System\\CurrentControlSet\\Control\\Session Manager\\Environment", "prepend", "C:\\XNA\\"))
|
||||
|
||||
|
||||
SYSTEM_REG = '''WINE REGISTRY Version 2
|
||||
;; All keys relative to REGISTRY\\\\Machine
|
||||
|
||||
#arch=win64
|
||||
|
||||
[Software\\\\Classes\\\\Wow6432Node\\\\CLSID] 1791145014
|
||||
#time=1dd543d4c84d0a2
|
||||
|
||||
[Software\\\\Wow6432Node\\\\Classes] 1791145014
|
||||
#time=1dd543d4c84d0a2
|
||||
#link
|
||||
"SymbolicLinkValue"=hex(6):5c,00,52,00,65,00,67,00,69,00,73,00,74,00,72,00,79,00,\\
|
||||
5c,00,4d,00,61,00,63,00,68,00,69,00,6e,00,65,00,5c,00,53,00,6f,00,66,00,74,00,\\
|
||||
77,00,61,00,72,00,65,00,5c,00,43,00,6c,00,61,00,73,00,73,00,65,00,73,00,5c,00,\\
|
||||
57,00,6f,00,77,00,36,00,34,00,33,00,32,00,4e,00,6f,00,64,00,65,00
|
||||
|
||||
[Software\\\\Wow6432Node\\\\Old] 1791145014
|
||||
#time=1dd543d4c84d0a2
|
||||
"Kept"="mine"
|
||||
"Version"="1.0"
|
||||
|
||||
[System\\\\ControlSet001\\\\Control\\\\Session Manager\\\\Environment] 1791169864
|
||||
#time=1dd547728528ad2
|
||||
"PATH"=str(2):"%SystemRoot%\\\\system32;%SystemRoot%"
|
||||
|
||||
[System\\\\CurrentControlSet] 1791145014
|
||||
#time=1dd543d4c84d0a2
|
||||
#link
|
||||
"SymbolicLinkValue"=hex(6):5c,00,52,00,65,00,67,00,69,00,73,00,74,00,72,00,79,00,\\
|
||||
5c,00,4d,00,61,00,63,00,68,00,69,00,6e,00,65,00,5c,00,53,00,79,00,73,00,74,00,\\
|
||||
65,00,6d,00,5c,00,43,00,6f,00,6e,00,74,00,72,00,6f,00,6c,00,53,00,65,00,74,00,\\
|
||||
30,00,30,00,31,00
|
||||
'''
|
||||
|
||||
|
||||
class RegistryApplyTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
root = Path(self.tmp.name)
|
||||
self.store = root / "store"
|
||||
self.compat = root / "compatdata/42"
|
||||
self.pfx = self.compat / "pfx"
|
||||
self.selection = root / "sel.json"
|
||||
folder = self.store / "xna40"
|
||||
(folder / "drive_c/Program Files (x86)/Microsoft XNA").mkdir(parents=True)
|
||||
(folder / "drive_c/Program Files (x86)/Microsoft XNA/xna.dll").write_bytes(b"xna")
|
||||
(folder / "component.json").write_text(json.dumps({"id": "xna40", "overrides": []}))
|
||||
(folder / "registry.json").write_text(json.dumps({"version": 1, "values": [
|
||||
{"hive": "HKLM", "key": "Software\\Wow6432Node\\Old", "name": "Version", "type": "sz", "data": "4.0"},
|
||||
{"hive": "HKLM", "key": "Software\\Wow6432Node\\Classes\\CLSID\\{X}", "name": "", "type": "sz", "data": "Thing"},
|
||||
{"hive": "HKLM", "key": "Software\\Wow6432Node\\New", "name": "Installed", "type": "dword", "data": 1},
|
||||
{"hive": "HKLM", "key": "System\\CurrentControlSet\\Control\\Session Manager\\Environment", "name": "PATH",
|
||||
"type": "prepend", "data": "C:\\PhysX", "separator": ";"},
|
||||
{"hive": "HKCU", "key": "Software\\Game", "name": "Opt", "type": "dword", "data": 2},
|
||||
]}))
|
||||
|
||||
def tearDown(self):
|
||||
self.tmp.cleanup()
|
||||
|
||||
def make_prefix(self):
|
||||
(self.pfx / "drive_c/program files (x86)").mkdir(parents=True)
|
||||
(self.pfx / "system.reg").write_text(SYSTEM_REG)
|
||||
(self.pfx / "user.reg").write_text("WINE REGISTRY Version 2\n;; All keys relative to REGISTRY\\\\User\\\\S-1-5-21\n\n#arch=win64\n")
|
||||
|
||||
def apply(self, *ids):
|
||||
self.selection.write_text(json.dumps({"version": 1, "games": {"42": list(ids)}}))
|
||||
return COMPONENTS["apply"](self.compat, "42", self.selection, self.store)
|
||||
|
||||
def test_values_follow_wines_links_and_come_out_again(self):
|
||||
self.make_prefix()
|
||||
self.apply("xna40")
|
||||
text = (self.pfx / "system.reg").read_text()
|
||||
self.assertIn('"Version"="4.0"', text)
|
||||
self.assertIn('"Kept"="mine"', text)
|
||||
# Through the Wow6432Node\Classes link into the shared Classes\Wow6432Node key, never under the link.
|
||||
self.assertIn('[Software\\\\Classes\\\\Wow6432Node\\\\CLSID\\\\{X}]', text)
|
||||
self.assertNotIn('[Software\\\\Wow6432Node\\\\Classes\\\\CLSID', text)
|
||||
self.assertIn('"PATH"=str(2):"C:\\\\PhysX;%SystemRoot%\\\\system32;%SystemRoot%"', text)
|
||||
self.assertNotIn("[System\\\\CurrentControlSet\\\\", text)
|
||||
self.assertIn('"Opt"=dword:00000002', (self.pfx / "user.reg").read_text())
|
||||
# The prefix's own spelling of Program Files (x86) is kept.
|
||||
self.assertTrue((self.pfx / "drive_c/program files (x86)/Microsoft XNA/xna.dll").is_file())
|
||||
self.assertFalse((self.pfx / "drive_c/Program Files (x86)").exists())
|
||||
|
||||
before = (self.pfx / "system.reg").read_text()
|
||||
_, notes = self.apply("xna40")
|
||||
self.assertEqual((self.pfx / "system.reg").read_text(), before)
|
||||
self.assertEqual(notes, [])
|
||||
|
||||
self.apply()
|
||||
text = (self.pfx / "system.reg").read_text()
|
||||
self.assertIn('"Version"="1.0"', text)
|
||||
self.assertNotIn('"Installed"=dword:00000001', text)
|
||||
self.assertNotIn("Thing", text)
|
||||
self.assertIn('"PATH"=str(2):"%SystemRoot%\\\\system32;%SystemRoot%"', text)
|
||||
self.assertNotIn('"Opt"', (self.pfx / "user.reg").read_text())
|
||||
self.assertFalse((self.pfx / "drive_c/program files (x86)/Microsoft XNA/xna.dll").exists())
|
||||
|
||||
def test_turning_off_keeps_what_others_added_to_path_since(self):
|
||||
self.make_prefix()
|
||||
self.apply("xna40")
|
||||
reg = self.pfx / "system.reg"
|
||||
reg.write_text(reg.read_text().replace("C:\\\\PhysX;", "C:\\\\PhysX;C:\\\\Other;"))
|
||||
self.apply()
|
||||
self.assertIn('"PATH"=str(2):"C:\\\\Other;%SystemRoot%\\\\system32;%SystemRoot%"', reg.read_text())
|
||||
|
||||
def test_values_wait_for_a_prefix_proton_has_not_made(self):
|
||||
_, notes = self.apply("xna40")
|
||||
self.assertTrue(any("wait for the prefix" in note for note in notes))
|
||||
self.assertFalse((self.pfx / "system.reg").exists())
|
||||
self.make_prefix()
|
||||
self.apply("xna40")
|
||||
self.assertIn('"Version"="4.0"', (self.pfx / "system.reg").read_text())
|
||||
|
||||
def test_registry_lines_round_trip(self):
|
||||
line = COMPONENTS["reg_value_line"]('we"ird\\', "sz", 'a"b\\c\u00e9')
|
||||
self.assertEqual(line, '"we\\"ird\\\\"="a\\"b\\\\c\\x00e9"')
|
||||
self.assertEqual(COMPONENTS["reg_string"](line), 'a"b\\c\u00e9')
|
||||
self.assertEqual(COMPONENTS["reg_value_line"]("m", "multi_sz", ["a", "b"]), '"m"=str(7):"a\\0b\\0"')
|
||||
self.assertEqual(COMPONENTS["reg_value_line"]("", "binary", "0a0b"), "@=hex:0a,0b")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,96 @@
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
SCRIPT = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-seed-redists"
|
||||
|
||||
GAME_SCRIPT = r'''"InstallScript"
|
||||
{
|
||||
"Run Process"
|
||||
{
|
||||
"VCRedist2022"
|
||||
{
|
||||
"HasRunKey" "HKEY_LOCAL_MACHINE\\Software\\Valve\\Steam\\Apps\\CommonRedist\\vcredist\\2022"
|
||||
"process 1" "%INSTALLDIR%\\_CommonRedist\\vcredist\\2022\\VC_redist.x64.exe"
|
||||
"command 1" "/q /norestart"
|
||||
"NoCleanUp" "1"
|
||||
}
|
||||
}
|
||||
}
|
||||
'''
|
||||
|
||||
|
||||
class SeedRedistsTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tmp = Path(tempfile.mkdtemp())
|
||||
self.addCleanup(shutil.rmtree, self.tmp, True)
|
||||
self.steam = self.tmp / "Steam"
|
||||
self.reg = self.steam / "steamapps/compatdata/1234/pfx/system.reg"
|
||||
self.reg.parent.mkdir(parents=True)
|
||||
self.reg.write_text("WINE REGISTRY Version 2\n")
|
||||
|
||||
def game(self, name="Some Game", script=GAME_SCRIPT, library=None):
|
||||
root = Path(library or self.steam)
|
||||
path = root / "steamapps/common" / name / "_CommonRedist/vcredist/2022/installscript.vdf"
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(script)
|
||||
manifest = root / "steamapps" / ("appmanifest_%d.acf" % (abs(hash(name)) % 100000))
|
||||
manifest.write_text('"AppState" { "installdir" "%s" }' % name)
|
||||
return path
|
||||
|
||||
def run_seed(self, libraries=""):
|
||||
env = dict(os.environ, DROIDDECK_LIBRARIES=libraries)
|
||||
return subprocess.run(["bash", str(SCRIPT), str(self.steam)], env=env, capture_output=True, text=True, check=True)
|
||||
|
||||
def test_a_games_own_install_script_is_marked_as_run(self):
|
||||
self.game()
|
||||
self.run_seed()
|
||||
reg = self.reg.read_text()
|
||||
self.assertIn("[Software\\\\Valve\\\\Steam\\\\Apps\\\\CommonRedist\\\\vcredist\\\\2022]", reg)
|
||||
self.assertIn("[Software\\\\Wow6432Node\\\\Valve\\\\Steam\\\\Apps\\\\CommonRedist\\\\vcredist\\\\2022]", reg)
|
||||
self.assertIn('"VCRedist2022"=dword:00000001', reg)
|
||||
|
||||
def test_games_in_other_libraries_are_read(self):
|
||||
sd = self.tmp / "sd"
|
||||
self.game(library=sd)
|
||||
self.run_seed(str(sd))
|
||||
self.assertIn('"VCRedist2022"=dword:00000001', self.reg.read_text())
|
||||
|
||||
def test_the_vc_runtime_is_recorded_for_every_architecture_and_view(self):
|
||||
self.run_seed()
|
||||
reg = self.reg.read_text()
|
||||
for view in ("Software", "Software\\\\Wow6432Node"):
|
||||
for arch in ("x86", "x64", "arm64"):
|
||||
self.assertIn("[%s\\\\Microsoft\\\\VisualStudio\\\\14.0\\\\VC\\\\Runtimes\\\\%s]" % (view, arch), reg)
|
||||
self.assertIn('"Installed"=dword:00000001', reg)
|
||||
self.assertIn('"Major"=dword:0000000e', reg)
|
||||
self.assertIn('"Version"="v14.51.36247.00"', reg)
|
||||
|
||||
def test_a_seeded_prefix_is_left_alone_until_a_game_changes(self):
|
||||
self.run_seed()
|
||||
once = self.reg.read_text()
|
||||
self.run_seed()
|
||||
self.assertEqual(once, self.reg.read_text())
|
||||
self.game()
|
||||
self.run_seed()
|
||||
self.assertIn('"VCRedist2022"=dword:00000001', self.reg.read_text())
|
||||
|
||||
def test_an_evaluator_script_nested_deeper_is_read(self):
|
||||
script = self.tmp / "legacycompat/evaluatorscript_409710.vdf"
|
||||
script.parent.mkdir(parents=True)
|
||||
script.write_text('"evaluatorscript"\n{\n\t"1"\n' + "\n".join("\t" + line for line in GAME_SCRIPT.replace("VCRedist2022", "x64 14.99.1.0").splitlines()) + "\n}\n")
|
||||
env = dict(os.environ, DROIDDECK_LIBRARIES="", DROIDDECK_SEED_SCRIPTS=str(script))
|
||||
subprocess.run(["bash", str(SCRIPT), str(self.steam)], env=env, capture_output=True, text=True, check=True)
|
||||
self.assertIn('"x64 14.99.1.0"=dword:00000001', self.reg.read_text())
|
||||
|
||||
def test_the_prefix_date_is_kept(self):
|
||||
os.utime(self.reg, (1_000_000_000, 1_000_000_000))
|
||||
self.run_seed()
|
||||
self.assertEqual(int(self.reg.stat().st_mtime), 1_000_000_000)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,170 @@
|
||||
import json
|
||||
import os
|
||||
import runpy
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from unittest import mock
|
||||
|
||||
BIN = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin"
|
||||
MODULE = runpy.run_path(str(BIN / "droiddeck-wincomponents"))
|
||||
GAME_ENV = runpy.run_path(str(BIN / "droiddeck-game-env"))
|
||||
|
||||
|
||||
class WinComponentsTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
root = Path(self.tmp.name)
|
||||
self.store = root / "store"
|
||||
self.compat = root / "compatdata/2571976725"
|
||||
self.selection = root / "wincomponents.json"
|
||||
self.pfx = self.compat / "pfx/drive_c/windows"
|
||||
|
||||
def tearDown(self):
|
||||
self.tmp.cleanup()
|
||||
|
||||
def component(self, cid, overrides, files):
|
||||
folder = self.store / cid
|
||||
for rel, data in files.items():
|
||||
path = folder / rel
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_bytes(data)
|
||||
(folder / "component.json").write_text(json.dumps({"id": cid, "overrides": overrides}))
|
||||
|
||||
def pick(self, *ids):
|
||||
self.selection.write_text(json.dumps({"version": 1, "games": {"2571976725": list(ids)}}))
|
||||
|
||||
def apply(self):
|
||||
return MODULE["apply"](self.compat, "2571976725", self.selection, self.store)
|
||||
|
||||
def test_places_files_before_the_prefix_exists_and_returns_overrides(self):
|
||||
self.component("openal", ["openal32"], {"syswow64/OpenAL32.dll": b"x86", "system32/OpenAL32.dll": b"x64"})
|
||||
self.pick("openal")
|
||||
names, notes = self.apply()
|
||||
self.assertEqual(names, ["openal32"])
|
||||
self.assertEqual((self.pfx / "syswow64/openal32.dll").read_bytes(), b"x86")
|
||||
self.assertEqual((self.pfx / "system32/openal32.dll").read_bytes(), b"x64")
|
||||
self.assertIn("2 file(s) placed", notes[-1])
|
||||
self.assertEqual(MODULE["overrides_value"](names + names), "openal32=n,b")
|
||||
|
||||
def test_second_launch_copies_nothing(self):
|
||||
self.component("openal", ["openal32"], {"syswow64/OpenAL32.dll": b"x86"})
|
||||
self.pick("openal")
|
||||
self.apply()
|
||||
_, notes = self.apply()
|
||||
self.assertEqual(notes, [])
|
||||
|
||||
def test_replaces_a_proton_builtin_symlink_and_keeps_the_prefix_spelling(self):
|
||||
self.component("xaudio", ["xaudio2_7"], {"syswow64/xaudio2_7.dll": b"native"})
|
||||
builtin = Path(self.tmp.name) / "proton/lib/wine/i386-windows/xaudio2_7.dll"
|
||||
builtin.parent.mkdir(parents=True)
|
||||
builtin.write_bytes(b"builtin")
|
||||
(self.pfx / "syswow64").mkdir(parents=True)
|
||||
(self.pfx / "syswow64/XAudio2_7.dll").symlink_to(builtin)
|
||||
self.pick("xaudio")
|
||||
self.apply()
|
||||
placed = self.pfx / "syswow64/XAudio2_7.dll"
|
||||
self.assertFalse(placed.is_symlink())
|
||||
self.assertEqual(placed.read_bytes(), b"native")
|
||||
self.assertEqual(builtin.read_bytes(), b"builtin")
|
||||
self.assertEqual(os.listdir(self.pfx / "syswow64"), ["XAudio2_7.dll"])
|
||||
|
||||
def test_restores_a_file_an_older_proton_deleted(self):
|
||||
self.component("openal", ["openal32"], {"syswow64/OpenAL32.dll": b"x86"})
|
||||
self.pick("openal")
|
||||
self.apply()
|
||||
(self.pfx / "syswow64/openal32.dll").unlink()
|
||||
_, notes = self.apply()
|
||||
self.assertTrue((self.pfx / "syswow64/openal32.dll").is_file())
|
||||
self.assertIn("1 file(s) placed", notes[-1])
|
||||
|
||||
def test_turning_a_component_off_removes_its_files_and_forgets_protons_config(self):
|
||||
self.component("openal", ["openal32"], {"syswow64/OpenAL32.dll": b"x86"})
|
||||
self.pick("openal")
|
||||
self.apply()
|
||||
(self.compat / "config_info").write_text("cached")
|
||||
self.pick()
|
||||
names, notes = self.apply()
|
||||
self.assertEqual(names, [])
|
||||
self.assertFalse((self.pfx / "syswow64/openal32.dll").exists())
|
||||
self.assertFalse((self.compat / "config_info").exists())
|
||||
self.assertIn("1 removed", notes[-1])
|
||||
|
||||
def test_a_file_of_someone_elses_is_kept_and_put_back_when_turned_off(self):
|
||||
self.component("vc", ["msvcp100"], {"syswow64/msvcp100.dll": b"ours"})
|
||||
installer = self.pfx / "syswow64/MSVCP100.dll"
|
||||
installer.parent.mkdir(parents=True)
|
||||
installer.write_bytes(b"from a real installer")
|
||||
self.pick("vc")
|
||||
self.apply()
|
||||
self.assertEqual(installer.read_bytes(), b"ours")
|
||||
self.apply() # a second launch keeps the first backup, not ours
|
||||
self.pick()
|
||||
names, notes = self.apply()
|
||||
self.assertEqual(installer.read_bytes(), b"from a real installer")
|
||||
self.assertIn("1 put back as they were", notes[-1])
|
||||
self.assertFalse((self.compat / ".droiddeck-wincomponents-backup/drive_c/windows/syswow64/msvcp100.dll").exists())
|
||||
|
||||
def test_protons_own_dlls_and_our_earlier_copy_get_no_backup(self):
|
||||
self.component("vc", ["msvcp100"], {"syswow64/msvcp100.dll": b"ours v1", "system32/msvcp100.dll": b"ours 64"})
|
||||
builtin = self.pfx / "system32/msvcp100.dll"
|
||||
builtin.parent.mkdir(parents=True)
|
||||
builtin.write_bytes(b"MZ" + b"\0" * 62 + b"Wine builtin DLL")
|
||||
self.pick("vc")
|
||||
self.apply()
|
||||
(self.store / "vc/syswow64/msvcp100.dll").write_bytes(b"ours v2")
|
||||
os.utime(self.store / "vc/syswow64/msvcp100.dll", (1, 1))
|
||||
self.apply()
|
||||
self.assertFalse((self.compat / ".droiddeck-wincomponents-backup").exists())
|
||||
|
||||
def test_missing_component_is_skipped(self):
|
||||
self.pick("physx")
|
||||
names, notes = self.apply()
|
||||
self.assertEqual(names, [])
|
||||
self.assertEqual(notes, ["physx is not installed; skipped"])
|
||||
|
||||
def test_no_selection_touches_nothing(self):
|
||||
self.assertEqual(self.apply(), ([], []))
|
||||
self.assertFalse(self.compat.exists())
|
||||
|
||||
def test_bad_selection_is_refused(self):
|
||||
self.selection.write_text(json.dumps({"version": 1, "games": {"2571976725": ["a/../etc"]}}))
|
||||
with self.assertRaises(ValueError):
|
||||
self.apply()
|
||||
|
||||
def test_game_env_puts_component_overrides_before_the_games_own(self):
|
||||
self.component("openal", ["openal32"], {"syswow64/OpenAL32.dll": b"x86"})
|
||||
self.pick("openal")
|
||||
globals_ = GAME_ENV["win_components"].__globals__
|
||||
real = runpy.run_path(str(BIN / "droiddeck-wincomponents"))
|
||||
real["apply"].__defaults__ = (self.selection, self.store)
|
||||
with mock.patch.dict(globals_, {"runpy": mock.Mock(run_path=lambda _path: real)}):
|
||||
self.assertEqual(GAME_ENV["win_components"](str(self.compat) + "/", "2571976725"), "openal32=n,b")
|
||||
self.assertEqual(GAME_ENV["win_components"]("", "2571976725"), "")
|
||||
|
||||
def test_bundle_brings_its_parts_and_catalog_names_with_dots_work(self):
|
||||
self.component("dmband", ["dmband"], {"syswow64/dmband.dll": b"band"})
|
||||
self.component("dsound", ["dsound=n"], {"syswow64/dsound.dll": b"ds"})
|
||||
meta = self.store / "directmusic"
|
||||
meta.mkdir(parents=True)
|
||||
(meta / "component.json").write_text(json.dumps({"id": "directmusic", "overrides": [], "requires": ["dmband", "dsound"]}))
|
||||
self.component("xaudio2.7", ["xaudio2_7"], {"system32/xaudio2_7.dll": b"xa"})
|
||||
self.pick("directmusic", "xaudio2.7")
|
||||
names, _ = self.apply()
|
||||
self.assertEqual(MODULE["overrides_value"](names), "dmband=n,b;dsound=n;xaudio2_7=n,b")
|
||||
self.assertEqual((self.pfx / "syswow64/dmband.dll").read_bytes(), b"band")
|
||||
self.assertEqual(json.loads((self.compat / ".droiddeck-wincomponents.json").read_text())["components"],
|
||||
["dmband", "dsound", "directmusic", "xaudio2.7"])
|
||||
|
||||
def test_files_one_level_down_are_placed(self):
|
||||
self.component("gmdls", [], {"system32/drivers/GM.DLS": b"dls"})
|
||||
self.pick("gmdls")
|
||||
self.apply()
|
||||
self.assertEqual((self.pfx / "system32/drivers/gm.dls").read_bytes(), b"dls")
|
||||
|
||||
def test_overrides_value_last_word_wins_and_refuses_junk(self):
|
||||
self.assertEqual(MODULE["overrides_value"](["a", "b=n", "a=b", "bad;name", "c=x"]), "b=n;a=b")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user