mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-12-05 12:35:42 +00:00
Compare commits
46
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4dc30f0293 | ||
|
|
8ab0c1041e | ||
|
|
de84fda5cf | ||
|
|
b81f4a0cfa | ||
|
|
5ae646bae8 | ||
|
|
ed7f532db4 | ||
|
|
ba59724632 | ||
|
|
705a5e7b2a | ||
|
|
e60eae3646 | ||
|
|
b04900b1b2 | ||
|
|
6357543b44 | ||
|
|
67fb338e5d | ||
|
|
ba140c4ab5 | ||
|
|
f5fdbc7941 | ||
|
|
90ae85da4d | ||
|
|
f3600fa618 | ||
|
|
2d8befe1cb | ||
|
|
f982ffcaf7 | ||
|
|
255c64551e | ||
|
|
746f28c1b2 | ||
|
|
2b481ba250 | ||
|
|
49622623de | ||
|
|
69f99ade42 | ||
|
|
c236e9711f | ||
|
|
4c2efb6688 | ||
|
|
7eb2d1cf1a | ||
|
|
b4ff83cf9f | ||
|
|
7b20b70c6b | ||
|
|
86207f9d0e | ||
|
|
eda5ece382 | ||
|
|
3404bbc128 | ||
|
|
b5a431aa3c | ||
|
|
49249f6541 | ||
|
|
5614621d6e | ||
|
|
0816562065 | ||
|
|
39618e6862 | ||
|
|
c66e4ba4b3 | ||
|
|
e4b033861f | ||
|
|
85a07a556c | ||
|
|
8dfc48d58b | ||
|
|
82ebdaa0b5 | ||
|
|
cbd4ce6636 | ||
|
|
d4130181e7 | ||
|
|
4e90e03536 | ||
|
|
454193da9b | ||
|
|
38d658abf5 |
No files matched your search
@@ -0,0 +1,2 @@
|
||||
# Patch context includes the indentation and blank lines of the source being patched.
|
||||
tools/gamescope/patches/*.patch -whitespace
|
||||
@@ -1,49 +0,0 @@
|
||||
name: Build FEX (x86-64 Steam client experiment)
|
||||
|
||||
# FEX built for the runtime in an Arch Linux ARM container on an arm64 runner (tools/fex), for the
|
||||
# opt-in x86-64 Steam client (bannerlator-steam-x64). Published as a release asset that script
|
||||
# fetches; the runtime image and the default arm64 client are untouched.
|
||||
on:
|
||||
push:
|
||||
paths:
|
||||
- 'tools/fex/**'
|
||||
- '.github/workflows/build-fex.yml'
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
tag:
|
||||
description: 'Release tag to publish as (e.g. fex-2609-r1); empty = artifact only'
|
||||
required: false
|
||||
default: ''
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-24.04-arm
|
||||
timeout-minutes: 120
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Build in Arch Linux ARM
|
||||
run: |
|
||||
set -euo pipefail
|
||||
docker run --rm -v "$PWD:/work" -w /work menci/archlinuxarm:base-devel bash tools/fex/build-in-arch.sh
|
||||
sudo chown -R "$(id -u):$(id -g)" .
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: fex
|
||||
path: |
|
||||
fex.tzst
|
||||
fex.tzst.sha256
|
||||
fex-needed.txt
|
||||
fex-files.txt
|
||||
- name: Publish
|
||||
if: github.event_name == 'workflow_dispatch' && inputs.tag != ''
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
gh release create "${{ inputs.tag }}" --latest=false --prerelease=false --title "${{ inputs.tag }}" --notes "FEX for the runtime (tools/fex/build-in-arch.sh); fetched by bannerlator-steam-x64. sha256 $(cut -d' ' -f1 fex.tzst.sha256)" fex.tzst fex.tzst.sha256 || gh release upload "${{ inputs.tag }}" fex.tzst fex.tzst.sha256 --clobber
|
||||
# A component the apk fetches by tag, never something users install: it must not
|
||||
# become the repo's Latest release or appear as a pre-release, also when re-uploaded.
|
||||
gh release edit "${{ inputs.tag }}" --latest=false --prerelease=false
|
||||
@@ -157,7 +157,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/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/mangoapp/*') }}
|
||||
key: preloads-${{ env.PRELOAD_CACHE_VERSION }}-${{ hashFiles('app/src/main/cpp/fakeinput_steam.cpp', 'tools/linuxfs/preload/*.c', '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/mangoapp/*') }}
|
||||
|
||||
- name: Build libfakeinput.so and libblsession.so (glibc aarch64)
|
||||
if: steps.preloads.outputs.cache-hit != 'true'
|
||||
@@ -179,6 +179,9 @@ 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"
|
||||
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"
|
||||
for script in tools/linuxfs/overlay/usr/local/bin/bannerlator-*; do
|
||||
install -Dm644 "$script" "$D/usr/local/bin/$(basename "$script")"
|
||||
done
|
||||
|
||||
@@ -73,6 +73,7 @@ class AgentBridgeProvider : ContentProvider() {
|
||||
.put("steamUi", SessionState.steamUi ?: JSONObject.NULL)
|
||||
.put("steamUrl", SessionState.steamUrl ?: JSONObject.NULL)
|
||||
.put("suspended", SessionState.suspended)
|
||||
.put("pip", SessionState.pipActive)
|
||||
.put("firstFrame", SessionState.firstFrameSeen)
|
||||
.put("output", JSONArray().put(SessionState.outputSize.first).put(SessionState.outputSize.second))
|
||||
.put("refreshHz", SessionState.refreshHz.toDouble())
|
||||
|
||||
@@ -13,6 +13,10 @@
|
||||
download from being throttled to nothing by the radio's power-save. -->
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
||||
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
|
||||
<!-- Optional Wi-Fi discovery: requested only from Steam settings after an explanation. -->
|
||||
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
|
||||
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
|
||||
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
|
||||
<uses-permission android:name="android.permission.VIBRATE" />
|
||||
<!-- Ends background processes of another app that holds the Steam login. GameHub starts
|
||||
itself with the phone via boot receivers and signs this client out seconds after every
|
||||
@@ -57,6 +61,16 @@
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent-filter>
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.VIEW" />
|
||||
<category android:name="android.intent.category.DEFAULT" />
|
||||
<category android:name="android.intent.category.BROWSABLE" />
|
||||
<data android:scheme="droiddeck" android:host="game" />
|
||||
</intent-filter>
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.CREATE_SHORTCUT" />
|
||||
<category android:name="android.intent.category.DEFAULT" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
|
||||
<!-- Android owns the Home key. This small translucent Home handler routes the resulting
|
||||
@@ -112,7 +126,8 @@
|
||||
<activity
|
||||
android:name=".SessionActivity"
|
||||
android:exported="false"
|
||||
android:launchMode="singleTop"
|
||||
android:supportsPictureInPicture="true"
|
||||
android:launchMode="singleTask"
|
||||
android:theme="@style/SessionTheme"
|
||||
android:preferMinimalPostProcessing="true"
|
||||
android:screenOrientation="sensorLandscape"
|
||||
|
||||
@@ -1717,6 +1717,80 @@ __attribute__((visibility("hidden"))) static std::string deck_listing_for(const
|
||||
return std::string(listing) + "/" + names[which];
|
||||
}
|
||||
|
||||
#ifdef __GLIBC__
|
||||
// sd-device's path chase now requires a mount ID, which statx only supplies from Linux 5.8.
|
||||
// Older handheld kernels still publish the real ID in fdinfo. Scope this compatibility path to
|
||||
// libudev/libsystemd in the Deck-reading Steam client, and never invent a unique mount ID.
|
||||
__attribute__((visibility("hidden"))) static bool deck_device_library(void *caller) {
|
||||
Dl_info info;
|
||||
if (!dladdr(caller, &info) || !info.dli_fname) return false;
|
||||
const char *name = strrchr(info.dli_fname, '/');
|
||||
name = name ? name + 1 : info.dli_fname;
|
||||
return !strncmp(name, "libudev.so", 10) || !strncmp(name, "libsystemd.so", 13);
|
||||
}
|
||||
|
||||
__attribute__((visibility("hidden"))) static bool deck_mount_id_from_fdinfo(
|
||||
int dirfd, const char *path, int flags, struct statx *buf) {
|
||||
static auto real_openat = reinterpret_cast<decltype(&::openat)>(dlsym(RTLD_NEXT, "openat"));
|
||||
static auto real_fstat = reinterpret_cast<decltype(&::fstat)>(dlsym(RTLD_NEXT, "fstat"));
|
||||
int target;
|
||||
if (!path || !*path) {
|
||||
if (!(flags & AT_EMPTY_PATH)) return false;
|
||||
target = dirfd == AT_FDCWD ? real_openat(AT_FDCWD, ".", O_PATH | O_CLOEXEC) :
|
||||
syscall(SYS_fcntl, dirfd, F_DUPFD_CLOEXEC, 0);
|
||||
} else {
|
||||
target = real_openat(dirfd, path, O_PATH | O_CLOEXEC |
|
||||
((flags & AT_SYMLINK_NOFOLLOW) ? O_NOFOLLOW : 0));
|
||||
}
|
||||
if (target < 0) return false;
|
||||
struct stat st;
|
||||
// Pin the inode and check it still matches the successful statx before adding information.
|
||||
bool same = real_fstat(target, &st) == 0 && (buf->stx_mask & STATX_INO) &&
|
||||
st.st_ino == buf->stx_ino && major(st.st_dev) == buf->stx_dev_major &&
|
||||
minor(st.st_dev) == buf->stx_dev_minor;
|
||||
char name[64];
|
||||
snprintf(name, sizeof(name), "/proc/self/fdinfo/%d", target);
|
||||
int info = same ? real_openat(AT_FDCWD, name, O_RDONLY | O_CLOEXEC) : -1;
|
||||
char value[512];
|
||||
ssize_t length = info >= 0 ? syscall(SYS_read, info, value, sizeof(value) - 1) : -1;
|
||||
if (info >= 0) syscall(SYS_close, info);
|
||||
syscall(SYS_close, target);
|
||||
if (length < 0) return false;
|
||||
value[length] = '\0';
|
||||
for (const char *line = value; line && *line;) {
|
||||
unsigned long long id;
|
||||
if (sscanf(line, "mnt_id: %llu", &id) == 1 && id > 0) {
|
||||
buf->stx_mnt_id = id;
|
||||
buf->stx_mask |= STATX_MNT_ID;
|
||||
return true;
|
||||
}
|
||||
const char *next = strchr(line, '\n');
|
||||
line = next ? next + 1 : nullptr;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
EXPORT int statx(int dirfd, const char *path, int flags, unsigned mask, struct statx *buf) {
|
||||
static auto real = reinterpret_cast<decltype(&::statx)>(dlsym(RTLD_NEXT, "statx"));
|
||||
int result = real(dirfd, path, flags, mask, buf);
|
||||
int saved_errno = errno;
|
||||
constexpr unsigned unique_mount_id = 0x4000; // STATX_MNT_ID_UNIQUE, newer than build headers.
|
||||
if (result == 0 && (mask & STATX_MNT_ID) &&
|
||||
!(buf->stx_mask & (STATX_MNT_ID | unique_mount_id)) && fake_deck_enabled() &&
|
||||
process_is_steam_client() && deck_device_library(__builtin_return_address(0))) {
|
||||
bool recovered = deck_mount_id_from_fdinfo(dirfd, path, flags, buf);
|
||||
static std::atomic<bool> noted_success{false}, noted_failure{false};
|
||||
if (!(recovered ? noted_success : noted_failure).exchange(true))
|
||||
Logger::log("deck discovery: statx mount id %s for %s (returned mask=0x%x id=%llu)\n",
|
||||
recovered ? "recovered from fdinfo" : "unavailable in fdinfo",
|
||||
path && *path ? path : "(fd)", buf->stx_mask,
|
||||
static_cast<unsigned long long>(buf->stx_mnt_id));
|
||||
}
|
||||
errno = saved_errno;
|
||||
return result;
|
||||
}
|
||||
#endif
|
||||
|
||||
EXPORT DIR *opendir(const char *name) {
|
||||
static auto real = reinterpret_cast<DIR *(*)(const char *)>(dlsym(RTLD_NEXT, "opendir"));
|
||||
DIR *dir = real(name);
|
||||
|
||||
@@ -3478,7 +3478,8 @@ int banner_wayland_run(void) {
|
||||
/* libdecor binds wl_output at 4; a lower version is a protocol error for the client. */
|
||||
wl_global_create(display, &wl_output_interface, 4, NULL, bind_output);
|
||||
wl_global_create(display, &xdg_wm_base_interface, 1, NULL, bind_xdg_wm_base);
|
||||
wl_global_create(display, &zwp_linux_dmabuf_v1_interface, 4, NULL, bind_dmabuf);
|
||||
if (vkp_dmabuf_supported())
|
||||
wl_global_create(display, &zwp_linux_dmabuf_v1_interface, 4, NULL, bind_dmabuf);
|
||||
/* gamescope's Wayland backend refuses a seat older than 8. */
|
||||
wl_global_create(display, &wl_seat_interface, 9, NULL, bind_seat);
|
||||
wl_global_create(display, &banner_desktop_v1_interface, 1, NULL, bind_desktop);
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
#define VK_USE_PLATFORM_ANDROID_KHR
|
||||
#include <vulkan/vulkan.h>
|
||||
|
||||
#define VK_GLOBAL_FUNCS(X) X(CreateInstance) X(EnumerateInstanceExtensionProperties)
|
||||
#define VK_GLOBAL_FUNCS(X) X(CreateInstance) X(EnumerateInstanceExtensionProperties) X(EnumerateInstanceVersion)
|
||||
|
||||
#define VK_INSTANCE_FUNCS(X) \
|
||||
X(EnumeratePhysicalDevices) X(GetPhysicalDeviceProperties) \
|
||||
|
||||
@@ -40,6 +40,7 @@ struct vkp_image {
|
||||
static ANativeWindow *g_window; /* the window frames go to; compositor thread only */
|
||||
static char *g_driver_path, *g_library_name, *g_native_lib_dir;
|
||||
static int g_dev_state; /* 0 = not yet, 1 = ok, -1 = failed, -2 = lost (VK_ERROR_DEVICE_LOST) */
|
||||
static int g_dmabuf_import;
|
||||
static VkInstance g_inst;
|
||||
static VkPhysicalDevice g_pd;
|
||||
static VkDevice g_dev;
|
||||
@@ -411,11 +412,18 @@ static int dev_init(void) {
|
||||
"generation %s)", g_colorspace_ext ? "enables" : "has no",
|
||||
g_colorspace_ext ? "is possible where the screen surface offers one" : "is not possible: tone-mapped instead");
|
||||
}
|
||||
/* 1.3 like the X11 renderer's instance: the frame-generation probe (framegen_engine.cpp)
|
||||
* queries VkPhysicalDeviceVulkan12Features, and a 1.1 instance may be answered as 1.1. */
|
||||
/* Keep the existing 1.3 request unless the selected loader positively reports an
|
||||
* older usable API. Custom ICDs may omit this optional global entry point. */
|
||||
uint32_t loader_api = VK_API_VERSION_1_3;
|
||||
if (g_vk.EnumerateInstanceVersion) {
|
||||
uint32_t reported_api = VK_API_VERSION_1_3;
|
||||
if (g_vk.EnumerateInstanceVersion(&reported_api) == VK_SUCCESS &&
|
||||
reported_api >= VK_API_VERSION_1_1)
|
||||
loader_api = reported_api;
|
||||
}
|
||||
VkApplicationInfo app = {.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO,
|
||||
.pApplicationName = "banner-wayland-present",
|
||||
.apiVersion = VK_API_VERSION_1_3};
|
||||
.apiVersion = loader_api < VK_API_VERSION_1_3 ? loader_api : VK_API_VERSION_1_3};
|
||||
VkInstanceCreateInfo ici = {.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO,
|
||||
.pApplicationInfo = &app,
|
||||
.enabledExtensionCount = n_inst_exts,
|
||||
@@ -450,18 +458,26 @@ static int dev_init(void) {
|
||||
}
|
||||
g_vk.GetPhysicalDeviceMemoryProperties(g_pd, &g_memprops);
|
||||
|
||||
/* Verify the dmabuf-import extensions are present, and log any that are missing. */
|
||||
const char *dev_exts[7] = {VK_KHR_SWAPCHAIN_EXTENSION_NAME, "VK_KHR_external_memory_fd",
|
||||
"VK_EXT_external_memory_dma_buf", "VK_EXT_image_drm_format_modifier",
|
||||
"VK_KHR_image_format_list", NULL, NULL};
|
||||
uint32_t n_dev_exts = 5;
|
||||
/* Shared-memory clients need only a swapchain. Advertise dma-buf import only when its
|
||||
* complete extension set is available, rather than failing device creation on older GPUs. */
|
||||
const char *import_exts[] = {"VK_KHR_external_memory_fd", "VK_EXT_external_memory_dma_buf",
|
||||
"VK_EXT_image_drm_format_modifier", "VK_KHR_image_format_list"};
|
||||
const char *dev_exts[7] = {VK_KHR_SWAPCHAIN_EXTENSION_NAME};
|
||||
uint32_t n_dev_exts = 1;
|
||||
uint32_t ne = 0;
|
||||
g_vk.EnumerateDeviceExtensionProperties(g_pd, NULL, &ne, NULL);
|
||||
VkExtensionProperties *exts = calloc(ne ? ne : 1, sizeof(*exts));
|
||||
g_vk.EnumerateDeviceExtensionProperties(g_pd, NULL, &ne, exts);
|
||||
for (unsigned i = 0; i < 5; i++)
|
||||
if (!has_ext(exts, ne, dev_exts[i]))
|
||||
LOGE("present: driver MISSING %s (dmabuf import will fail)", dev_exts[i]);
|
||||
g_dmabuf_import = 1;
|
||||
for (unsigned i = 0; i < sizeof(import_exts) / sizeof(import_exts[0]); i++) {
|
||||
if (!has_ext(exts, ne, import_exts[i])) {
|
||||
g_dmabuf_import = 0;
|
||||
banner_log("gpu", "driver has no %s; shared-memory clients remain available", import_exts[i]);
|
||||
}
|
||||
}
|
||||
if (g_dmabuf_import)
|
||||
for (unsigned i = 0; i < sizeof(import_exts) / sizeof(import_exts[0]); i++)
|
||||
dev_exts[n_dev_exts++] = import_exts[i];
|
||||
/* HDR sessions only: the HDR10 swapchain (frame generation) can carry the game's metadata. */
|
||||
int want_hdr_md = 0;
|
||||
if (banner_color_requested()) {
|
||||
@@ -538,6 +554,7 @@ static int dev_init(void) {
|
||||
}
|
||||
|
||||
int vkp_ready(void) { return dev_init(); }
|
||||
int vkp_dmabuf_supported(void) { return dev_init() == 0 && g_dmabuf_import; }
|
||||
|
||||
static int swap_init_locked(void);
|
||||
|
||||
@@ -899,7 +916,7 @@ static int modifier_importable(VkFormat fmt, uint64_t modifier, VkImageUsageFlag
|
||||
}
|
||||
|
||||
int vkp_dmabuf_modifiers(uint32_t drm_format, uint64_t *out, int max) {
|
||||
if (max <= 0 || dev_init() != 0 || !g_vk.GetPhysicalDeviceFormatProperties2) return 0;
|
||||
if (max <= 0 || !vkp_dmabuf_supported() || !g_vk.GetPhysicalDeviceFormatProperties2) return 0;
|
||||
VkFormat fmt = drm_to_vk(drm_format);
|
||||
VkDrmFormatModifierPropertiesListEXT list = {
|
||||
.sType = VK_STRUCTURE_TYPE_DRM_FORMAT_MODIFIER_PROPERTIES_LIST_EXT};
|
||||
@@ -941,7 +958,7 @@ int vkp_image_is_dmabuf(const struct vkp_image *img) { return img && img->dmabuf
|
||||
struct vkp_image *vkp_image_import_dmabuf(int fd, uint32_t drm_format, uint64_t modifier, int w, int h,
|
||||
uint32_t stride, uint32_t offset, int as_blit_dst) {
|
||||
if (modifier == MOD_INVALID || w <= 0 || h <= 0) return NULL;
|
||||
if (dev_init() != 0) return NULL;
|
||||
if (!vkp_dmabuf_supported()) return NULL;
|
||||
|
||||
struct vkp_image *img = calloc(1, sizeof(*img));
|
||||
if (!img) return NULL;
|
||||
|
||||
@@ -87,6 +87,8 @@ const char *vkp_gpu_name(void);
|
||||
|
||||
// 0 if the renderer can create images (device up), -1 otherwise.
|
||||
int vkp_ready(void);
|
||||
/* Whether the selected driver supports the complete dma-buf import extension set. */
|
||||
int vkp_dmabuf_supported(void);
|
||||
/* Whether an output window is attached (or requested); without one vkp_render() draws nothing. */
|
||||
int vkp_has_window(void);
|
||||
/* 1 once the Vulkan device was lost: nothing is presented any more (the session must restart). */
|
||||
|
||||
@@ -47,6 +47,7 @@ import com.droiddeck.launcher.core.CpuCores
|
||||
import com.droiddeck.launcher.core.PhantomProcessLimit
|
||||
import com.droiddeck.launcher.core.PhantomProcessStatus
|
||||
import com.droiddeck.launcher.core.WirelessAdbFix
|
||||
import com.droiddeck.launcher.core.WifiDiscovery
|
||||
import com.droiddeck.launcher.core.WirelessAdbPairingService
|
||||
import com.droiddeck.launcher.ui.CoreRow
|
||||
import com.droiddeck.launcher.ui.PerformancePage
|
||||
@@ -149,6 +150,24 @@ class MainActivity : ComponentActivity() {
|
||||
private var launcherFullscreen by mutableStateOf(true)
|
||||
private var storeEnabled by mutableStateOf(false)
|
||||
private var mic by mutableStateOf(false)
|
||||
private var wifiDiscovery by mutableStateOf(false)
|
||||
private var wifiDiscoveryPermission by mutableStateOf(false)
|
||||
private var wifiDiscoveryLocation by mutableStateOf(false)
|
||||
private var wifiDiscoveryAsked by mutableStateOf(false)
|
||||
private var wifiDiscoveryBlocked by mutableStateOf(false)
|
||||
private val wifiLocationReceiver = object : android.content.BroadcastReceiver() {
|
||||
override fun onReceive(context: android.content.Context?, intent: Intent?) {
|
||||
refreshWifiDiscovery()
|
||||
}
|
||||
}
|
||||
private val wifiLocationPermission = registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) {
|
||||
SessionPrefs.setWifiDiscoveryEnabled(this, WifiDiscovery.permissionGranted(this))
|
||||
refreshWifiDiscovery()
|
||||
}
|
||||
private val wifiPermissionSettings = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
|
||||
SessionPrefs.setWifiDiscoveryEnabled(this, WifiDiscovery.permissionGranted(this))
|
||||
refreshWifiDiscovery()
|
||||
}
|
||||
|
||||
// The app's own picker (files/), once per kind of pick: the two driver lists validate
|
||||
// differently, and the reason a zip is refused names the list it belongs in.
|
||||
@@ -176,6 +195,28 @@ class MainActivity : ComponentActivity() {
|
||||
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedFile(r.data)?.let(then)
|
||||
}
|
||||
|
||||
private fun refreshWifiDiscovery() {
|
||||
wifiDiscoveryPermission = WifiDiscovery.permissionGranted(this)
|
||||
wifiDiscoveryLocation = WifiDiscovery.locationEnabled(this)
|
||||
wifiDiscoveryAsked = SessionPrefs.wifiDiscoveryAsked(this)
|
||||
wifiDiscoveryBlocked = !wifiDiscoveryPermission && wifiDiscoveryAsked &&
|
||||
WifiDiscovery.permissions.none { shouldShowRequestPermissionRationale(it) }
|
||||
// A revoked grant must not leave an enabled switch behind.
|
||||
if (!wifiDiscoveryPermission && SessionPrefs.wifiDiscoveryEnabled(this)) {
|
||||
SessionPrefs.setWifiDiscoveryEnabled(this, false)
|
||||
}
|
||||
wifiDiscovery = SessionPrefs.wifiDiscoveryEnabled(this)
|
||||
}
|
||||
|
||||
private fun openWifiDiscoverySettings() {
|
||||
if (!WifiDiscovery.permissionGranted(this)) {
|
||||
wifiPermissionSettings.launch(Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
|
||||
Uri.parse("package:$packageName")))
|
||||
} else {
|
||||
startActivity(Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS))
|
||||
}
|
||||
}
|
||||
|
||||
/** Takes a new or updated Lossless Scaling from Steam and shows what LSFG can use. */
|
||||
private fun syncLossless() {
|
||||
Thread({
|
||||
@@ -263,6 +304,8 @@ class MainActivity : ComponentActivity() {
|
||||
private var shapeMode by mutableStateOf(SessionPrefs.SHAPE_AUTO)
|
||||
private var hdrOn by mutableStateOf(false)
|
||||
private var fpsLimit by mutableStateOf(0)
|
||||
private var upscaler by mutableStateOf(0)
|
||||
private var upscaleSharpness by mutableStateOf(75)
|
||||
private var hdrReason by mutableStateOf<String?>(null)
|
||||
private var touchMode by mutableStateOf(SessionPrefs.TOUCH_AUTO)
|
||||
private var suspendPolicy by mutableStateOf(SessionPrefs.SUSPEND_MANUAL)
|
||||
@@ -279,7 +322,6 @@ class MainActivity : ComponentActivity() {
|
||||
private var emulatorList by mutableStateOf<List<Library.Emulator>>(emptyList())
|
||||
private var runningLabel by mutableStateOf<String?>(null)
|
||||
private var logsEnabled by mutableStateOf(true)
|
||||
private var vacDiagnostics by mutableStateOf(false)
|
||||
private var showRoms by mutableStateOf(false)
|
||||
private var homeAppSelected by mutableStateOf(false)
|
||||
private var homeScreenEnabled by mutableStateOf(false)
|
||||
@@ -333,13 +375,75 @@ class MainActivity : ComponentActivity() {
|
||||
overridePendingTransition(0, 0)
|
||||
}
|
||||
|
||||
private var shortcutPicker by mutableStateOf(false)
|
||||
private var shortcutLibraryScanning by mutableStateOf(false)
|
||||
@Volatile private var libraryScanGeneration = 0
|
||||
private var pendingGameLink: String? = null
|
||||
|
||||
private fun readGameIntent(request: Intent) {
|
||||
shortcutPicker = request.action == Intent.ACTION_CREATE_SHORTCUT
|
||||
if (shortcutPicker) {
|
||||
// The shortcut picker must only offer games from the scan started for this request.
|
||||
steamGames = emptyList()
|
||||
shortcutLibraryScanning = true
|
||||
} else shortcutLibraryScanning = false
|
||||
pendingGameLink = if (request.action == Intent.ACTION_VIEW)
|
||||
com.droiddeck.launcher.frontend.GameLaunchLink.parse(request.dataString) else null
|
||||
if (request.action == Intent.ACTION_VIEW && pendingGameLink == null) {
|
||||
android.widget.Toast.makeText(this, R.string.game_link_invalid, android.widget.Toast.LENGTH_LONG).show()
|
||||
}
|
||||
}
|
||||
|
||||
private fun launchGame(game: Library.SteamGame): 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
|
||||
}
|
||||
if (SessionState.running) {
|
||||
if (SessionState.mode != SessionService.MODE_STEAM || SessionState.stopRequested) {
|
||||
android.widget.Toast.makeText(this, R.string.game_link_session_busy, android.widget.Toast.LENGTH_LONG).show()
|
||||
return true
|
||||
}
|
||||
if (!SessionService.launchGame(this, game.gameIdString)) {
|
||||
android.widget.Toast.makeText(this, R.string.game_link_failed, android.widget.Toast.LENGTH_LONG).show()
|
||||
return false
|
||||
}
|
||||
startActivity(Intent(this, SessionActivity::class.java).setAction(SessionService.ACTION_RESUME)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP))
|
||||
return true
|
||||
}
|
||||
return startSession(Intent(this, SessionActivity::class.java)
|
||||
.putExtra(SessionService.EXTRA_STEAM_URL,
|
||||
com.droiddeck.launcher.frontend.GameLaunchLink.steamUrl(game.gameIdString)), steamSession = true)
|
||||
}
|
||||
|
||||
private fun handleGameLink(games: List<Library.SteamGame>) {
|
||||
if (!lifecycle.currentState.isAtLeast(androidx.lifecycle.Lifecycle.State.RESUMED)) return
|
||||
val id = pendingGameLink ?: return
|
||||
val game = games.firstOrNull { it.gameIdString == id }
|
||||
if (game == null) {
|
||||
pendingGameLink = null
|
||||
intent.data = null
|
||||
android.widget.Toast.makeText(this, R.string.game_link_missing, android.widget.Toast.LENGTH_LONG).show()
|
||||
} else if (launchGame(game)) {
|
||||
pendingGameLink = null
|
||||
intent.data = null
|
||||
}
|
||||
}
|
||||
|
||||
private fun chooseGameShortcut(game: Library.SteamGame) {
|
||||
setResult(RESULT_OK, com.droiddeck.launcher.frontend.GameShortcuts.result(this, game))
|
||||
finish()
|
||||
}
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
readGameIntent(intent)
|
||||
displayManager = getSystemService(DISPLAY_SERVICE) as DisplayManager
|
||||
refreshPhantomStatus()
|
||||
theme = SessionPrefs.theme(this)
|
||||
// Last start's game list, so the Steam wall is up on the first frame; refresh() replaces it.
|
||||
steamGames = com.droiddeck.launcher.frontend.LibraryCache.load(this)
|
||||
steamGames = if (shortcutPicker) emptyList() else com.droiddeck.launcher.frontend.LibraryCache.load(this)
|
||||
backActionsInverted = SessionPrefs.backActionsInverted(this)
|
||||
launcherFullscreen = SessionPrefs.launcherFullscreen(this)
|
||||
storeEnabled = SessionPrefs.storeEnabled(this)
|
||||
@@ -361,10 +465,12 @@ class MainActivity : ComponentActivity() {
|
||||
FrontEndScreen(
|
||||
FrontEndState(
|
||||
installed = installed, ready = ready, available = available?.version,
|
||||
shortcutPicker = shortcutPicker,
|
||||
shortcutLibraryScanning = shortcutLibraryScanning,
|
||||
busy = busy, stage = stage, percent = percent,
|
||||
desktopInstalled = desktopInstalled,
|
||||
offlineAccount = offlineAccount, offline = offline,
|
||||
frameGenLabel = frameGenLabel, romsDir = romsDir, logsEnabled = logsEnabled, vacDiagnostics = vacDiagnostics,
|
||||
frameGenLabel = frameGenLabel, romsDir = romsDir, logsEnabled = logsEnabled,
|
||||
steamGames = steamGames, emulators = emulatorList, running = runningLabel,
|
||||
frameGen = FrameGen.mode(this),
|
||||
lossless = lossless,
|
||||
@@ -400,9 +506,12 @@ class MainActivity : ComponentActivity() {
|
||||
.putExtra(SessionService.EXTRA_MODE, SessionService.MODE_DESKTOP)
|
||||
.putExtra(SessionService.EXTRA_STEAM_UI, "desktop"), steamSession = true)
|
||||
},
|
||||
onSteamGame = { g ->
|
||||
startSession(Intent(this, SessionActivity::class.java)
|
||||
.putExtra(SessionService.EXTRA_STEAM_URL, "steam://rungameid/${g.gameId}"), steamSession = true)
|
||||
onSteamGame = { g -> if (shortcutPicker) chooseGameShortcut(g) else launchGame(g) },
|
||||
onGameShortcut = { g -> com.droiddeck.launcher.frontend.GameShortcuts.pin(this, g) },
|
||||
onCopyGameLink = { g ->
|
||||
(getSystemService(CLIPBOARD_SERVICE) as ClipboardManager).setPrimaryClip(
|
||||
ClipData.newPlainText(g.name, com.droiddeck.launcher.frontend.GameLaunchLink.uri(g.gameIdString)))
|
||||
android.widget.Toast.makeText(this, R.string.game_link_copied, android.widget.Toast.LENGTH_SHORT).show()
|
||||
},
|
||||
onDesktop = {
|
||||
startSession(Intent(this, SessionActivity::class.java)
|
||||
@@ -462,10 +571,6 @@ class MainActivity : ComponentActivity() {
|
||||
SessionPrefs.setLogsEnabled(this, !SessionPrefs.logsEnabled(this))
|
||||
logsEnabled = SessionPrefs.logsEnabled(this)
|
||||
},
|
||||
onVacDiagnostics = {
|
||||
SessionPrefs.setVacDiagnostics(this, !SessionPrefs.vacDiagnostics(this))
|
||||
vacDiagnostics = SessionPrefs.vacDiagnostics(this)
|
||||
},
|
||||
onShareLogs = {
|
||||
Thread({
|
||||
val zip = runCatching { SessionLogShare.zipLatest(this) }.getOrNull()
|
||||
@@ -640,10 +745,13 @@ class MainActivity : ComponentActivity() {
|
||||
override fun onNewIntent(intent: Intent) {
|
||||
super.onNewIntent(intent)
|
||||
setIntent(intent)
|
||||
readGameIntent(intent)
|
||||
refresh()
|
||||
startSteamAtStartupIfEnabled()
|
||||
}
|
||||
|
||||
private fun startSteamAtStartupIfEnabled() {
|
||||
if (intent.action != Intent.ACTION_MAIN) return
|
||||
if (SessionPrefs.runSteamAtStartup(this) && !isFinishing && !isDestroyed) startSteamSession()
|
||||
}
|
||||
|
||||
@@ -685,6 +793,7 @@ class MainActivity : ComponentActivity() {
|
||||
|
||||
override fun onResume() {
|
||||
super.onResume()
|
||||
refreshWifiDiscovery()
|
||||
com.droiddeck.launcher.ui.Motion.refresh(this)
|
||||
// Back from a session stopped behind a flood: open on its blue, before the first frame.
|
||||
com.droiddeck.launcher.ui.QuitFlood.take()?.let { c ->
|
||||
@@ -722,6 +831,7 @@ class MainActivity : ComponentActivity() {
|
||||
|
||||
override fun onStart() {
|
||||
super.onStart()
|
||||
registerReceiver(wifiLocationReceiver, android.content.IntentFilter(android.location.LocationManager.MODE_CHANGED_ACTION))
|
||||
displayManager.registerDisplayListener(secondScreenDisplayListener, ui)
|
||||
refreshSecondScreenDisplays()
|
||||
}
|
||||
@@ -732,6 +842,7 @@ class MainActivity : ComponentActivity() {
|
||||
}
|
||||
|
||||
override fun onStop() {
|
||||
unregisterReceiver(wifiLocationReceiver)
|
||||
displayManager.unregisterDisplayListener(secondScreenDisplayListener)
|
||||
// The session covers the page by now; coming back finds it as it was.
|
||||
flood = null
|
||||
@@ -949,9 +1060,12 @@ class MainActivity : ComponentActivity() {
|
||||
ModeSettings(
|
||||
mode = mode, resolutionCap = resolutionCap, customResolution = customResolution, shapeMode = shapeMode,
|
||||
hdr = hdrOn, hdrReason = hdrReason, fpsLimit = fpsLimit,
|
||||
upscaler = upscaler, upscaleSharpness = upscaleSharpness,
|
||||
gpuDrivers = drivers.summary(),
|
||||
touchMode = touchMode,
|
||||
suspendPolicy = suspendPolicy,
|
||||
pipSupported = com.droiddeck.launcher.session.SessionPipController.supported(this),
|
||||
pipAutoEnter = pipAutoEnter,
|
||||
oscMode = if (mode == SessionService.MODE_STEAM) oscMode else null,
|
||||
backActionsInverted = backActionsInverted,
|
||||
directAudio = if (mode == SessionService.MODE_STEAM) directAudio else null,
|
||||
@@ -968,6 +1082,11 @@ class MainActivity : ComponentActivity() {
|
||||
mangoapp = mangoapp,
|
||||
steamController = if (mode == SessionService.MODE_STEAM) steamController else null,
|
||||
runSteamAtStartup = mode == SessionService.MODE_STEAM && runSteamAtStartup,
|
||||
wifiDiscovery = if (mode == SessionService.MODE_STEAM) wifiDiscovery else null,
|
||||
wifiDiscoveryPermission = wifiDiscoveryPermission,
|
||||
wifiDiscoveryLocation = wifiDiscoveryLocation,
|
||||
wifiDiscoveryAsked = wifiDiscoveryAsked,
|
||||
wifiDiscoveryBlocked = wifiDiscoveryBlocked,
|
||||
addedGamesDirs = if (mode == SessionService.MODE_STEAM) addedGamesDirs else null,
|
||||
addedGames = if (mode == SessionService.MODE_STEAM) addedGames else emptyList(),
|
||||
addedGamesArt = addedGamesArt,
|
||||
@@ -977,14 +1096,32 @@ class MainActivity : ComponentActivity() {
|
||||
deckyEnabled = decky.deckySupervisor, deckySessionRunning = SessionState.running,
|
||||
),
|
||||
ModeSettingsActions(
|
||||
onWifiDiscovery = { on ->
|
||||
if (!on) {
|
||||
SessionPrefs.setWifiDiscoveryEnabled(this, false)
|
||||
refreshWifiDiscovery()
|
||||
} else if (WifiDiscovery.permissionGranted(this)) {
|
||||
SessionPrefs.setWifiDiscoveryEnabled(this, true)
|
||||
refreshWifiDiscovery()
|
||||
} else if (wifiDiscoveryBlocked) {
|
||||
openWifiDiscoverySettings()
|
||||
} else {
|
||||
SessionPrefs.setWifiDiscoveryAsked(this)
|
||||
wifiLocationPermission.launch(WifiDiscovery.permissions)
|
||||
}
|
||||
},
|
||||
onWifiDiscoverySettings = { openWifiDiscoverySettings() },
|
||||
onResolution = { cap -> SessionPrefs.setResolutionCap(this, mode, cap); resolutionCap = cap },
|
||||
onCustomResolution = { size -> SessionPrefs.setCustomResolution(this, mode, size); customResolution = size },
|
||||
onShape = { shape -> SessionPrefs.setShapeMode(this, shape); shapeMode = shape },
|
||||
onHdr = { on -> SessionPrefs.setHdr(this, mode, on); hdrOn = on },
|
||||
onGpuDrivers = { openComponents(focusContent = true, tab = com.droiddeck.launcher.ui.GPU_TAB) },
|
||||
onFpsLimit = { fps -> SessionPrefs.setFpsLimit(this, mode, fps); fpsLimit = fps },
|
||||
onUpscaler = { m -> SessionPrefs.setUpscaler(this, m); upscaler = m },
|
||||
onUpscaleSharpness = { pct -> SessionPrefs.setUpscaleSharpness(this, pct); upscaleSharpness = pct },
|
||||
onTouch = { t -> SessionPrefs.setTouchMode(this, t); touchMode = t },
|
||||
onSuspendPolicy = { policy -> SessionPrefs.setSuspendPolicy(this, mode, policy); suspendPolicy = policy },
|
||||
onPipAutoEnter = { on -> SessionPrefs.setPipAutoEnter(this, on); pipAutoEnter = on },
|
||||
onOsc = { o -> SessionPrefs.setOscMode(this, o); oscMode = o },
|
||||
onBackActionsInverted = { inverted ->
|
||||
SessionPrefs.setBackActionsInverted(this, inverted)
|
||||
@@ -1104,7 +1241,10 @@ class MainActivity : ComponentActivity() {
|
||||
}
|
||||
}
|
||||
|
||||
private var pipAutoEnter by mutableStateOf(false)
|
||||
|
||||
private fun openModeSettings(mode: String) {
|
||||
pipAutoEnter = SessionPrefs.pipAutoEnter(this)
|
||||
showPerformance = false
|
||||
showProtons = false
|
||||
showComponents = false
|
||||
@@ -1121,6 +1261,8 @@ class MainActivity : ComponentActivity() {
|
||||
shapeMode = SessionPrefs.shapeMode(this)
|
||||
hdrOn = SessionPrefs.hdr(this, mode)
|
||||
fpsLimit = SessionPrefs.fpsLimit(this, mode)
|
||||
upscaler = SessionPrefs.upscaler(this)
|
||||
upscaleSharpness = SessionPrefs.upscaleSharpness(this)
|
||||
hdrReason = com.droiddeck.launcher.wayland.HdrSupport.probe(this).reason
|
||||
touchMode = SessionPrefs.touchMode(this)
|
||||
suspendPolicy = SessionPrefs.suspendPolicy(this, mode)
|
||||
@@ -1131,6 +1273,7 @@ class MainActivity : ComponentActivity() {
|
||||
forceFullscreen = SessionPrefs.forceFullscreen(this)
|
||||
stretch16x9 = SessionPrefs.stretch16x9(this)
|
||||
mic = SessionPrefs.micEnabled(this)
|
||||
refreshWifiDiscovery()
|
||||
renderer = SessionPrefs.desktopRenderer(this)
|
||||
gameStorage = SessionPrefs.gameStorage(this)
|
||||
settingsMode = mode
|
||||
@@ -1197,7 +1340,6 @@ class MainActivity : ComponentActivity() {
|
||||
frameGenLabel = FrameGen.label(this)
|
||||
romsDir = SessionPrefs.romsDir(this).takeIf { it.isNotEmpty() }
|
||||
logsEnabled = SessionPrefs.logsEnabled(this)
|
||||
vacDiagnostics = SessionPrefs.vacDiagnostics(this)
|
||||
runningLabel = if (SessionState.running) when (SessionState.mode) {
|
||||
SessionService.MODE_DESKTOP -> "Desktop"
|
||||
SessionService.MODE_RUN -> Library.nameForProgram(SessionState.program)
|
||||
@@ -1205,6 +1347,8 @@ class MainActivity : ComponentActivity() {
|
||||
else -> "Steam"
|
||||
} else null
|
||||
// The libraries, off the main thread: manifests and a folder scan.
|
||||
val scanGeneration = ++libraryScanGeneration
|
||||
if (shortcutPicker) shortcutLibraryScanning = true
|
||||
Thread({
|
||||
// One update with the whole list: the wall places games by their position in it, so a
|
||||
// partial list first would shuffle every capsule when the rest arrived. LibraryCache
|
||||
@@ -1221,7 +1365,14 @@ class MainActivity : ComponentActivity() {
|
||||
val emus = Library.emulators(this) { id -> DesktopCatalog.installed(this, id) != null }
|
||||
val all = games.distinctBy { it.gameId }
|
||||
if (ready) com.droiddeck.launcher.frontend.LibraryCache.save(this, all)
|
||||
ui.post { steamGames = all; emulatorList = emus }
|
||||
ui.post {
|
||||
if (scanGeneration == libraryScanGeneration) {
|
||||
steamGames = all
|
||||
emulatorList = emus
|
||||
shortcutLibraryScanning = false
|
||||
handleGameLink(all)
|
||||
}
|
||||
}
|
||||
// Box art for the games that have none, fetched after the list is up; the list is
|
||||
// rebuilt once if any was found.
|
||||
if (!OfflineMode.enabled(this) && CoverArt.fetchMissing(this, emus.flatMap { it.games })) {
|
||||
@@ -1251,15 +1402,16 @@ class MainActivity : ComponentActivity() {
|
||||
}
|
||||
|
||||
/** Starts a session; with no runtime on a non-Adreno, the same warning Setup gives comes first, before any download. */
|
||||
private fun startSession(intent: Intent, steamSession: Boolean = false) {
|
||||
private fun startSession(intent: Intent, steamSession: Boolean = false): Boolean {
|
||||
refreshPhantomStatus()
|
||||
if (steamSession && PhantomProcessLimit.blocksSteam(phantomProcessStatus)) {
|
||||
showPhantomGate = true
|
||||
return
|
||||
return false
|
||||
}
|
||||
val warn = installed == null && !com.droiddeck.launcher.core.DeviceSupport.adreno()
|
||||
if (warn && available != null) showNonAdreno = available
|
||||
else startActivity(intent)
|
||||
if (warn && available != null) { showNonAdreno = available; return false }
|
||||
startActivity(intent)
|
||||
return true
|
||||
}
|
||||
|
||||
private fun refreshPhantomStatus() {
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
package com.droiddeck.launcher
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import android.hardware.input.InputManager
|
||||
import android.hardware.display.DisplayManager
|
||||
@@ -41,6 +43,7 @@ import com.droiddeck.launcher.gpu.Lossless
|
||||
import com.droiddeck.launcher.gpu.TurnipDriver
|
||||
import com.droiddeck.launcher.input.EvdevKeys
|
||||
import com.droiddeck.launcher.input.KeyboardHost
|
||||
import com.droiddeck.launcher.input.SessionClipboard
|
||||
import com.droiddeck.launcher.input.OnScreenControls
|
||||
import com.droiddeck.launcher.input.PadBridge
|
||||
import com.droiddeck.launcher.input.PointerGestures
|
||||
@@ -89,6 +92,10 @@ import kotlin.math.abs
|
||||
* the HUD line, the loading overlay, the drawer and its dialogs.
|
||||
*/
|
||||
class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
private lateinit var pip: com.droiddeck.launcher.session.SessionPipController
|
||||
private var pipUi by mutableStateOf(false)
|
||||
private var pipAutoEnter by mutableStateOf(false)
|
||||
private val guestKeysDown = mutableSetOf<Int>()
|
||||
private lateinit var surfaceView: SurfaceView
|
||||
private lateinit var sessionOverlay: ComposeView
|
||||
private lateinit var loading: LoadingState
|
||||
@@ -121,10 +128,15 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
/** Motion is read while the session shows and only if the pad is a Deck controller - which
|
||||
* the service can decide after this activity has resumed (SessionState.deckPadListener). */
|
||||
private fun updatePadMotion() {
|
||||
if (resumed && SessionState.deckPad) padMotion?.start() else padMotion?.stop()
|
||||
if (resumed && !pipUi && SessionState.deckPad) padMotion?.start() else padMotion?.stop()
|
||||
}
|
||||
private var onScreenControls: OnScreenControls? = null
|
||||
private var keyboard: KeyboardHost? = null
|
||||
private val sessionClipboard by lazy {
|
||||
SessionClipboard(this) {
|
||||
window.decorView.hasWindowFocus() || secondScreenPresentation?.window?.decorView?.hasWindowFocus() == true
|
||||
}
|
||||
}
|
||||
private var watching = true
|
||||
private lateinit var touchpad: TouchpadGestures
|
||||
private var touchMode by mutableStateOf(SessionPrefs.TOUCH_AUTO)
|
||||
@@ -194,6 +206,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
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 lossless by mutableStateOf(Lossless.State.NONE)
|
||||
private val pickLossless = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
|
||||
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedFile(r.data)?.let { importLossless(it) }
|
||||
@@ -260,10 +274,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
SessionState.programArgs = intent.getStringArrayExtra(SessionService.EXTRA_PROGRAM_ARGS)?.toList().orEmpty()
|
||||
SessionEvents.begin(this, mode, SessionPaths.label(mode, intent.getStringExtra(SessionService.EXTRA_PROGRAM)))
|
||||
}
|
||||
SessionState.program = intent.getStringExtra(SessionService.EXTRA_PROGRAM)
|
||||
SessionState.programArgs = intent.getStringArrayExtra(SessionService.EXTRA_PROGRAM_ARGS)?.toList().orEmpty()
|
||||
SessionState.steamUi = intent.getStringExtra(SessionService.EXTRA_STEAM_UI)
|
||||
SessionState.steamUrl = intent.getStringExtra(SessionService.EXTRA_STEAM_URL)
|
||||
if (!SessionState.running && SessionState.phase in setOf(SessionPhase.IDLE, SessionPhase.FAILED)) {
|
||||
SessionState.program = intent.getStringExtra(SessionService.EXTRA_PROGRAM)
|
||||
SessionState.programArgs = intent.getStringArrayExtra(SessionService.EXTRA_PROGRAM_ARGS)?.toList().orEmpty()
|
||||
SessionState.steamUi = intent.getStringExtra(SessionService.EXTRA_STEAM_UI)
|
||||
SessionState.steamUrl = intent.getStringExtra(SessionService.EXTRA_STEAM_URL)
|
||||
}
|
||||
if (intent.action == SessionService.ACTION_AGENT_START) {
|
||||
SessionEvents.record("agent.start_requested", mapOf("mode" to SessionState.mode))
|
||||
}
|
||||
@@ -344,6 +360,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
sessionOverlay = createSessionOverlay()
|
||||
root.addView(sessionOverlay)
|
||||
setContentView(root)
|
||||
pip = com.droiddeck.launcher.session.SessionPipController(this, ::pipBounds, ::showPipUi)
|
||||
surfaceView.addOnLayoutChangeListener { _, _, _, _, _, _, _, _, _ -> pip.refresh() }
|
||||
pip.refresh()
|
||||
handleHomeGuideIntent(intent)
|
||||
|
||||
updateOnScreenControls()
|
||||
@@ -354,6 +373,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
// The single action waits out the double-press window so the two actions stay distinct.
|
||||
onBackPressedDispatcher.addCallback(this, object : OnBackPressedCallback(true) {
|
||||
override fun handleOnBackPressed() {
|
||||
if (pipUi) return
|
||||
// The PC keyboard closes first (B on a controller), then Back is the drawer again.
|
||||
when {
|
||||
::loading.isInitialized && loading.ended -> finish()
|
||||
@@ -378,6 +398,15 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
defaultFocusHighlightEnabled = false
|
||||
setContent {
|
||||
DroidDeckTheme {
|
||||
if (pipUi) {
|
||||
if (SessionState.suspended) androidx.compose.foundation.layout.Box(
|
||||
Modifier.fillMaxSize(), contentAlignment = androidx.compose.ui.Alignment.Center,
|
||||
) {
|
||||
androidx.compose.material3.Text(getString(R.string.pip_suspended),
|
||||
color = androidx.compose.ui.graphics.Color.White,
|
||||
modifier = Modifier.background(androidx.compose.ui.graphics.Color.Black.copy(alpha = 0.7f)).padding(6.dp))
|
||||
}
|
||||
} else {
|
||||
com.droiddeck.launcher.ui.FocusGlideHost(androidx.compose.ui.Modifier.fillMaxSize()) {
|
||||
CursorOverlay(cursorPos, cursorVisible, resources.displayMetrics.density,
|
||||
cursorImage, cursorHotX, cursorHotY, cursorImageScale)
|
||||
@@ -412,7 +441,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
// The PC keyboard takes it too, for moving over the keys; the drawer opens over it.
|
||||
androidx.compose.runtime.LaunchedEffect(pcKeyboardOpen) { if (pcKeyboardOpen) padBridge?.releaseAll() }
|
||||
if (pcKeyboardOpen) com.droiddeck.launcher.ui.PcKeyboard(
|
||||
sendKey = { code, down -> if (CompositorHost.isStarted) WaylandCompositor.nativeSendKey(code, if (down) 1 else 0) },
|
||||
sendKey = { code, down -> if (CompositorHost.isStarted) sendGuestKey(code, down) },
|
||||
onAndroidKeyboard = { pcKeyboardOpen = false; keyboard?.toggle() },
|
||||
onClose = { pcKeyboardOpen = false },
|
||||
)
|
||||
@@ -424,6 +453,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
androidApps = androidApps,
|
||||
hudOn = hudOn,
|
||||
fillScreen = if (SessionState.mode == SessionService.MODE_STEAM) fillScreen else null,
|
||||
upscaler = upscaler, upscaleSharpness = upscaleSharpness,
|
||||
frameGen = frameGen,
|
||||
lossless = lossless,
|
||||
oscMode = oscMode, suspendPolicy = suspendPolicy, touchMode = touchMode,
|
||||
@@ -434,6 +464,14 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
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)
|
||||
},
|
||||
onUpscaleSharpness = { pct ->
|
||||
SessionPrefs.setUpscaleSharpness(this@SessionActivity, pct); upscaleSharpness = pct
|
||||
WaylandCompositor.nativeSetUpscaleSharpness(pct)
|
||||
},
|
||||
onFrameGenPick = { mode ->
|
||||
FrameGen.set(this@SessionActivity, mode)
|
||||
readPrefs()
|
||||
@@ -483,7 +521,15 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
Toast.makeText(this@SessionActivity, "Could not open ${app.label} on $target", Toast.LENGTH_SHORT).show()
|
||||
}
|
||||
},
|
||||
onBackground = { drawerOpen = false; moveTaskToBack(true) },
|
||||
pipSupported = com.droiddeck.launcher.session.SessionPipController.supported(this@SessionActivity),
|
||||
pipAutoEnter = pipAutoEnter,
|
||||
onPip = { pip.enter() },
|
||||
onPipAutoEnter = { on ->
|
||||
SessionPrefs.setPipAutoEnter(this@SessionActivity, on)
|
||||
pipAutoEnter = on
|
||||
pip.refresh(true)
|
||||
},
|
||||
onBackground = { drawerOpen = false; pip.background(); moveTaskToBack(true) },
|
||||
onShareLogs = { drawerOpen = false; shareCurrentSessionLogs() },
|
||||
onStop = { drawerOpen = false; SessionService.stop(this@SessionActivity); finish() },
|
||||
onStopFrom = { onScreen ->
|
||||
@@ -519,6 +565,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun refreshHomeApp() {
|
||||
@@ -651,8 +698,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
}
|
||||
|
||||
private fun readPrefs() {
|
||||
pipAutoEnter = SessionPrefs.pipAutoEnter(this)
|
||||
hudOn = SessionPrefs.hudEnabled(this)
|
||||
fillScreen = SessionPrefs.forceFullscreen(this)
|
||||
upscaler = SessionPrefs.upscaler(this)
|
||||
upscaleSharpness = SessionPrefs.upscaleSharpness(this)
|
||||
touchMode = SessionPrefs.touchMode(this)
|
||||
frameGen = FrameGen.mode(this)
|
||||
fexPreset = SessionPrefs.fexPreset(this)
|
||||
@@ -809,6 +859,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
// Letterbox, never stretch or crop: the output can be a different shape from the panel,
|
||||
// and a game's picture must keep its proportions with bars, not lose its edges.
|
||||
WaylandCompositor.nativeSetScaleMode(SCALE_FIT, ALIGN_CENTER)
|
||||
WaylandCompositor.nativeSetUpscaler(SessionPrefs.upscaler(this))
|
||||
WaylandCompositor.nativeSetUpscaleSharpness(SessionPrefs.upscaleSharpness(this))
|
||||
// The session's folder, claimed here because the compositor starts before the service and
|
||||
// opens its log once. The compositor reads the path from its environment; setting it after
|
||||
// it has started changes nothing, which is why the service copies the file in at teardown.
|
||||
@@ -996,6 +1048,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
val poll = object : Runnable {
|
||||
override fun run() {
|
||||
if (!watching) return
|
||||
if (::pip.isInitialized) pip.refresh()
|
||||
if (SessionState.stopRequested && !SessionState.running && !installingRuntime) {
|
||||
SessionState.stopRequested = false
|
||||
SessionEvents.transition(SessionPhase.IDLE, "session.cancelled")
|
||||
@@ -1014,6 +1067,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
}
|
||||
|
||||
private fun onSessionEnded(status: Int) {
|
||||
if (isInPictureInPictureMode) {
|
||||
runOnUiThread { finish() }
|
||||
return
|
||||
}
|
||||
closeSecondScreen(reset = true)
|
||||
if (status == 0) {
|
||||
runOnUiThread {
|
||||
@@ -1115,6 +1172,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
KeyEvent.KEYCODE_VOLUME_UP, KeyEvent.KEYCODE_VOLUME_DOWN, KeyEvent.KEYCODE_VOLUME_MUTE ->
|
||||
return super.dispatchKeyEvent(event)
|
||||
}
|
||||
if (pipUi) return true
|
||||
val fromController = event.device != null && PadBridge.isFromController(event.device)
|
||||
if (fromController && event.action == KeyEvent.ACTION_DOWN) {
|
||||
if (drawerOpen && !drawerControllerActive) sessionOverlay.requestFocus()
|
||||
@@ -1154,7 +1212,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
}
|
||||
return true
|
||||
}
|
||||
val resumeKey = event.keyCode == KeyEvent.KEYCODE_BUTTON_A || event.keyCode == KeyEvent.KEYCODE_BUTTON_START
|
||||
val resumeKey = event.keyCode == KeyEvent.KEYCODE_BUTTON_A || event.keyCode == KeyEvent.KEYCODE_BUTTON_START ||
|
||||
event.keyCode == KeyEvent.KEYCODE_BUTTON_MODE || event.keyCode == KeyEvent.KEYCODE_HOME
|
||||
val resumeKeyId = event.deviceId to event.keyCode
|
||||
if (fromController && resumeKey && (SessionState.suspended || resumeKeyId in resumeKeysDown)) {
|
||||
if (event.action == KeyEvent.ACTION_DOWN) {
|
||||
@@ -1193,11 +1252,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
if (evdev <= 0 && event.scanCode > 0) evdev = event.scanCode
|
||||
if (evdev > 0) {
|
||||
if (down) {
|
||||
if (shiftEvdev != 0) WaylandCompositor.nativeSendKey(shiftEvdev, 1)
|
||||
WaylandCompositor.nativeSendKey(evdev, 1)
|
||||
if (shiftEvdev != 0) sendGuestKey(shiftEvdev, true)
|
||||
sendGuestKey(evdev, true)
|
||||
} else {
|
||||
WaylandCompositor.nativeSendKey(evdev, 0)
|
||||
if (shiftEvdev != 0) WaylandCompositor.nativeSendKey(shiftEvdev, 0)
|
||||
sendGuestKey(evdev, false)
|
||||
if (shiftEvdev != 0) sendGuestKey(shiftEvdev, false)
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -1207,6 +1266,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
}
|
||||
|
||||
override fun dispatchGenericMotionEvent(event: MotionEvent): Boolean {
|
||||
if (pipUi) return true
|
||||
if (drawerOpen && event.device != null && PadBridge.isFromController(event.device)) {
|
||||
if (!drawerControllerActive) sessionOverlay.requestFocus()
|
||||
drawerControllerActive = true
|
||||
@@ -1225,6 +1285,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
}
|
||||
|
||||
override fun dispatchTouchEvent(event: MotionEvent): Boolean {
|
||||
if (pipUi) return true
|
||||
if (event.actionMasked == MotionEvent.ACTION_DOWN && event.isFromSource(InputDevice.SOURCE_TOUCHSCREEN)) {
|
||||
drawerControllerActive = false
|
||||
}
|
||||
@@ -1426,6 +1487,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
}
|
||||
|
||||
private fun showSecondScreen(mode: SecondScreenMode) {
|
||||
if (pipUi || !started) return
|
||||
val target = displayManager.getDisplay(selectedSecondScreenDisplay)
|
||||
if (target == null || !target.isValid || (target.flags and Display.FLAG_PRESENTATION) == 0) {
|
||||
// Not there right now - a panel still waking, say. The choice is kept; the display
|
||||
@@ -1531,6 +1593,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
// the compositor still holds (an up lost to the drawer opening mid-touch) goes first.
|
||||
MotionEvent.ACTION_DOWN -> {
|
||||
WaylandCompositor.nativeSendTouch(3, -1, 0, 0)
|
||||
listOf(PointerGestures.BTN_LEFT, PointerGestures.BTN_RIGHT, PointerGestures.BTN_MIDDLE).forEach {
|
||||
WaylandCompositor.nativeSendSceneInput(3, it, 0)
|
||||
}
|
||||
sendTouch(0, event.actionIndex)
|
||||
}
|
||||
MotionEvent.ACTION_POINTER_DOWN -> sendTouch(0, event.actionIndex)
|
||||
@@ -1582,6 +1647,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
?.let { FileUtils.readString(it)?.trim()?.lowercase() }
|
||||
?: SessionPrefs.oscMode(this)
|
||||
val controls = onScreenControls ?: return
|
||||
if (pipUi) {
|
||||
controls.releaseAll()
|
||||
controls.visibility = View.GONE
|
||||
return
|
||||
}
|
||||
val buttonsOnly = forced == SessionPrefs.OSC_STEAM_QAM
|
||||
controls.setButtonsOnly(buttonsOnly)
|
||||
val show = when (forced) {
|
||||
@@ -1603,6 +1673,76 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
})
|
||||
}
|
||||
|
||||
private fun sendGuestKey(code: Int, down: Boolean) {
|
||||
if (down && pipUi) return
|
||||
if (down) guestKeysDown.add(code) else guestKeysDown.remove(code)
|
||||
WaylandCompositor.nativeSendKey(code, if (down) 1 else 0)
|
||||
}
|
||||
|
||||
private fun pipBounds(): android.graphics.Rect {
|
||||
val rect = android.graphics.Rect()
|
||||
if (!::surfaceView.isInitialized || !surfaceView.getGlobalVisibleRect(rect)) return rect
|
||||
val (w, h) = SessionState.outputSize
|
||||
if (w <= 0 || h <= 0) return rect
|
||||
val scale = minOf(rect.width().toFloat() / w, rect.height().toFloat() / h)
|
||||
val fittedW = (w * scale).toInt()
|
||||
val fittedH = (h * scale).toInt()
|
||||
rect.inset((rect.width() - fittedW) / 2, (rect.height() - fittedH) / 2)
|
||||
return rect
|
||||
}
|
||||
|
||||
private fun showPipUi(show: Boolean) {
|
||||
pipUi = show
|
||||
if (show) {
|
||||
drawerOpen = false
|
||||
pcKeyboardOpen = false
|
||||
pendingBackAction?.let(uiHandler::removeCallbacks)
|
||||
pendingBackAction = null
|
||||
releaseDrawerDirection()
|
||||
onScreenControls?.releaseAll()
|
||||
padBridge?.releaseAll()
|
||||
touchpad.cancel()
|
||||
guestKeysDown.toList().forEach { sendGuestKey(it, false) }
|
||||
keyboard?.hide()
|
||||
sessionClipboard.stop()
|
||||
padMotion?.stop()
|
||||
cursorVisible = false
|
||||
closeSecondScreen(reset = false)
|
||||
onScreenControls?.visibility = View.GONE
|
||||
window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
|
||||
if (CompositorHost.isStarted) {
|
||||
WaylandCompositor.nativeSendTouch(3, -1, 0, 0)
|
||||
listOf(PointerGestures.BTN_LEFT, PointerGestures.BTN_RIGHT, PointerGestures.BTN_MIDDLE).forEach {
|
||||
WaylandCompositor.nativeSendSceneInput(3, it, 0)
|
||||
}
|
||||
WaylandCompositor.nativeSetScaleMode(SCALE_FIT, ALIGN_CENTER)
|
||||
}
|
||||
} else if (!isFinishing && !isDestroyed) {
|
||||
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
|
||||
updateOnScreenControls()
|
||||
if (resumed) { sessionClipboard.start(); updatePadMotion() }
|
||||
if (started) refreshSecondScreenDisplays()
|
||||
if (CompositorHost.isStarted) applyFrameGen()
|
||||
}
|
||||
}
|
||||
|
||||
override fun onUserLeaveHint() {
|
||||
if (::pip.isInitialized) pip.leaving()
|
||||
super.onUserLeaveHint()
|
||||
}
|
||||
|
||||
override fun onPictureInPictureModeChanged(inPip: Boolean, newConfig: android.content.res.Configuration) {
|
||||
super.onPictureInPictureModeChanged(inPip, newConfig)
|
||||
if (::pip.isInitialized) pip.changed(inPip)
|
||||
}
|
||||
|
||||
override fun startActivityForResult(intent: Intent, requestCode: Int, options: Bundle?) {
|
||||
if (::pip.isInitialized && (requestCode >= 0 || intent.component?.packageName == packageName ||
|
||||
intent.action in setOf(Intent.ACTION_CHOOSER, Intent.ACTION_SEND, Intent.ACTION_OPEN_DOCUMENT,
|
||||
Intent.ACTION_GET_CONTENT, "android.settings.PICTURE_IN_PICTURE_SETTINGS"))) pip.background()
|
||||
super.startActivityForResult(intent, requestCode, options)
|
||||
}
|
||||
|
||||
// ── Lifecycle ───────────────────────────────────────────────────────────────────────────
|
||||
|
||||
override fun onStart() {
|
||||
@@ -1657,12 +1797,15 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
onScreenControls?.reload()
|
||||
updateOnScreenControls()
|
||||
resumed = true
|
||||
if (!pipUi) sessionClipboard.start()
|
||||
updatePadMotion()
|
||||
readPrefs()
|
||||
if (::pip.isInitialized) pip.resumed()
|
||||
if (CompositorHost.isStarted) applyFrameGen()
|
||||
}
|
||||
|
||||
override fun onPause() {
|
||||
sessionClipboard.stop()
|
||||
// Do not carry transient session UI across an app/display transition. In particular, the
|
||||
// drawer's dim layer can otherwise remain over Steam when this activity returns.
|
||||
drawerOpen = false
|
||||
@@ -1687,7 +1830,15 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
|
||||
override fun onWindowFocusChanged(hasFocus: Boolean) {
|
||||
super.onWindowFocusChanged(hasFocus)
|
||||
if (hasFocus) goFullscreen()
|
||||
if (hasFocus && !pipUi) {
|
||||
goFullscreen()
|
||||
refreshClipboard()
|
||||
}
|
||||
}
|
||||
|
||||
/** The keyboard/trackpad presentation can own focus instead of the main display. */
|
||||
fun refreshClipboard() {
|
||||
if (resumed) sessionClipboard.refresh()
|
||||
}
|
||||
|
||||
private fun goFullscreen() {
|
||||
@@ -1723,7 +1874,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
releaseDrawerDirection()
|
||||
pendingBackAction?.let(uiHandler::removeCallbacks)
|
||||
pendingBackAction = null
|
||||
closeSecondScreen(reset = true)
|
||||
if (::pip.isInitialized) pip.destroyed()
|
||||
closeSecondScreen(reset = false)
|
||||
if (::hud.isInitialized) hud.stop()
|
||||
padBridge?.stop()
|
||||
padMotion?.stop()
|
||||
|
||||
@@ -150,6 +150,8 @@ object DeviceReport {
|
||||
k("No GL error checks", SessionPrefs.noGlError(context))
|
||||
k("Steam Deck mode", SessionPrefs.steamDeckMode(context))
|
||||
k("Steam controller", SessionPrefs.steamController(context))
|
||||
k("Upscaler", (SessionPrefs.upscalerChoices.firstOrNull { it.first == SessionPrefs.upscaler(context) }?.second ?: "Off") +
|
||||
" (sharpness ${SessionPrefs.upscaleSharpness(context)}%)")
|
||||
k("FEX preset", SessionPrefs.fexPreset(context).ifEmpty { "FEX defaults" })
|
||||
k("Skip xalia", SessionPrefs.noXalia(context))
|
||||
k("gamescope realtime", SessionPrefs.gamescopeRealtime(context))
|
||||
|
||||
@@ -14,10 +14,8 @@ import java.net.Inet6Address
|
||||
* `network.txt`: what the session was given to work with, for the reports that say "the client
|
||||
* thinks WiFi is off" or "Firefox cannot resolve anything".
|
||||
*
|
||||
* The runtime has no NetworkManager, so the client's own network panel is blind by design and says
|
||||
* so in ways that read like a fault. What actually matters is further down: whether the phone had
|
||||
* a validated link, which DNS servers the app wrote into the runtime's `resolv.conf`, and whether
|
||||
* the session can reach a name and an address at all.
|
||||
* The runtime's NetworkManager bridge reports Android's active link. Include whether the phone
|
||||
* had a validated link and which DNS servers the app wrote into the runtime's `resolv.conf`.
|
||||
*
|
||||
* **No network names.** The SSID is identifying and is deliberately not collected; the transport
|
||||
* type, the addresses' families and the DNS servers are what a diagnosis needs.
|
||||
@@ -100,7 +98,7 @@ object NetworkReport {
|
||||
}
|
||||
append("\nproot makes no network namespace, so the session uses the phone's connection\n")
|
||||
append("directly: IPv4 and IPv6 both pass through, and there is nothing to forward.\n")
|
||||
append("The Steam client's own network panel drives NetworkManager over D-Bus, which this\n")
|
||||
append("runtime does not have - \"wifi is off\" there is cosmetic and not evidence.\n")
|
||||
append("Steam reads Android's transport, connectivity and metering through the runtime's\n")
|
||||
append("NetworkManager D-Bus bridge. Android settings manage Wi-Fi and cellular connections.\n")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.droiddeck.launcher.core
|
||||
|
||||
import android.Manifest
|
||||
import android.content.Context
|
||||
import android.content.pm.PackageManager
|
||||
import android.location.LocationManager
|
||||
import android.os.Build
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
|
||||
/** Location is used only for Android's Wi-Fi names and scan results, never coordinates. */
|
||||
object WifiDiscovery {
|
||||
val permissions = arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION)
|
||||
|
||||
// targetSdk 28 accepts either grant for Wi-Fi scanning.
|
||||
fun permissionGranted(context: Context): Boolean = permissions.any {
|
||||
context.checkSelfPermission(it) == PackageManager.PERMISSION_GRANTED
|
||||
}
|
||||
|
||||
fun locationEnabled(context: Context): Boolean = Build.VERSION.SDK_INT < Build.VERSION_CODES.P ||
|
||||
(context.getSystemService(Context.LOCATION_SERVICE) as? LocationManager)?.isLocationEnabled == true
|
||||
|
||||
fun available(context: Context): Boolean = SessionPrefs.wifiDiscoveryEnabled(context) &&
|
||||
permissionGranted(context) && locationEnabled(context)
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.droiddeck.launcher.frontend
|
||||
|
||||
/** External callers can select a game, never a guest path or arbitrary Steam command. */
|
||||
object GameLaunchLink {
|
||||
private val idPattern = Regex("[1-9][0-9]{0,19}")
|
||||
private val linkPattern = Regex("droiddeck://game/([1-9][0-9]{0,19})")
|
||||
|
||||
fun validId(id: String): Boolean = idPattern.matches(id) && id.toULongOrNull() != null
|
||||
fun parse(link: String?): String? = link?.let { linkPattern.matchEntire(it)?.groupValues?.get(1) }
|
||||
?.takeIf(::validId)
|
||||
fun uri(id: String): String { require(validId(id)); return "droiddeck://game/$id" }
|
||||
fun steamUrl(id: String): String { require(validId(id)); return "steam://rungameid/$id" }
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package com.droiddeck.launcher.frontend
|
||||
|
||||
import android.app.Activity
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.ShortcutInfo
|
||||
import android.content.pm.ShortcutManager
|
||||
import android.graphics.BitmapFactory
|
||||
import android.graphics.drawable.Icon
|
||||
import android.net.Uri
|
||||
import android.widget.Toast
|
||||
import com.droiddeck.launcher.MainActivity
|
||||
import com.droiddeck.launcher.R
|
||||
|
||||
object GameShortcuts {
|
||||
fun launchIntent(context: Context, gameId: String) = Intent(Intent.ACTION_VIEW,
|
||||
Uri.parse(GameLaunchLink.uri(gameId)), context, MainActivity::class.java)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP)
|
||||
|
||||
private fun info(context: Context, game: Library.SteamGame): ShortcutInfo {
|
||||
val name = game.name.ifBlank { context.getString(R.string.app_name) }
|
||||
val icon = game.art?.takeIf { it.isFile }?.let { file -> runCatching {
|
||||
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
|
||||
BitmapFactory.decodeFile(file.path, bounds)
|
||||
if (bounds.outWidth <= 0 || bounds.outHeight <= 0) return@runCatching null
|
||||
val options = BitmapFactory.Options().apply {
|
||||
inSampleSize = 1
|
||||
while (maxOf(bounds.outWidth, bounds.outHeight) / inSampleSize > 256) inSampleSize *= 2
|
||||
}
|
||||
BitmapFactory.decodeFile(file.path, options)?.let(Icon::createWithBitmap)
|
||||
}.getOrNull() } ?: Icon.createWithResource(context, R.mipmap.ic_launcher)
|
||||
return ShortcutInfo.Builder(context, "game:${game.gameIdString}")
|
||||
.setActivity(android.content.ComponentName(context, MainActivity::class.java))
|
||||
.setShortLabel(name.take(40)).setLongLabel(name).setIcon(icon)
|
||||
.setIntent(launchIntent(context, game.gameIdString)).build()
|
||||
}
|
||||
|
||||
fun pin(activity: Activity, game: Library.SteamGame) {
|
||||
val manager = activity.getSystemService(ShortcutManager::class.java)
|
||||
val requested = runCatching { manager.isRequestPinShortcutSupported &&
|
||||
manager.requestPinShortcut(info(activity, game), null) }.getOrDefault(false)
|
||||
if (!requested) Toast.makeText(activity, R.string.game_shortcut_unsupported, Toast.LENGTH_LONG).show()
|
||||
}
|
||||
|
||||
/** Standard shortcut picker result, understood by launchers that import Android shortcuts. */
|
||||
fun result(activity: Activity, game: Library.SteamGame): Intent =
|
||||
activity.getSystemService(ShortcutManager::class.java).createShortcutResultIntent(info(activity, game))
|
||||
}
|
||||
@@ -23,7 +23,10 @@ object Library {
|
||||
val appId: Int, val name: String, val art: File?, val library: String, val gameId: Long = appId.toLong(),
|
||||
val hero: File? = null, val lastPlayed: Long = 0L,
|
||||
val gameFiles: File? = null, val protonPrefix: File? = null,
|
||||
)
|
||||
) {
|
||||
/** Decimal form used by Steam links and Android shortcuts, including unsigned shortcut ids. */
|
||||
val gameIdString: String get() = java.lang.Long.toUnsignedString(gameId)
|
||||
}
|
||||
/** The [SteamGame.library] of a game added to the library rather than installed by Steam. */
|
||||
const val ADDED = "added"
|
||||
|
||||
|
||||
@@ -24,11 +24,12 @@ import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipInputStream;
|
||||
|
||||
/**
|
||||
* The Vulkan driver the in-app compositor runs on. It has to be Turnip: the system Adreno driver
|
||||
* The Vulkan driver the in-app compositor runs on. Adreno needs Turnip: its system driver
|
||||
* does not implement VK_EXT_image_drm_format_modifier, so importing the dma-bufs gamescope hands
|
||||
* over fails and the session renders nothing. Two builds ship in the apk, one per Adreno
|
||||
* generation, and the GPU decides which is unpacked - unless the user has imported an AdrenoTools
|
||||
* zip of their own and chosen it, which then wins.
|
||||
* zip of their own and chosen it, which then wins. A positively identified Mali kbase GPU
|
||||
* instead uses system Vulkan for shared-memory presentation; this does not supply a Linux ICD.
|
||||
*
|
||||
* <p>The guest's own Turnip is a different copy entirely - a glibc build inside the rootfs, or an
|
||||
* imported one ({@link LinuxVulkanDriverManager}). This one is the bionic build the app process
|
||||
@@ -338,6 +339,12 @@ public final class TurnipDriver {
|
||||
if (forced.startsWith("a7")) return DRIVER_A7XX;
|
||||
}
|
||||
String model = gpuModel();
|
||||
// A Mali kbase node is positive evidence. Unknown hardware keeps the existing default.
|
||||
if (model == null && new File("/dev/mali0").exists()
|
||||
&& !com.droiddeck.launcher.core.DeviceSupport.INSTANCE.adreno()) {
|
||||
Log.i(TAG, "Mali kbase GPU: using system Vulkan for the compositor");
|
||||
return null;
|
||||
}
|
||||
Log.i(TAG, "gpu model: " + (model == null ? "unknown" : model));
|
||||
if (model != null) {
|
||||
// "Adreno750", "adreno_830" - the generation is the first digit of the three.
|
||||
|
||||
@@ -86,6 +86,8 @@ class OnScreenControls(context: Context, private val pad: PadBridge?, private va
|
||||
private val groups = controls.map { it.group }.distinct()
|
||||
|
||||
private var buttonsOnly = false
|
||||
private var quickHidden = false
|
||||
private var quickPressedBy = -1
|
||||
private var settings = ControllerPrefs.read(context)
|
||||
private var safe = Rect()
|
||||
private var selected: String? = null
|
||||
@@ -159,9 +161,18 @@ class OnScreenControls(context: Context, private val pad: PadBridge?, private va
|
||||
if (buttonsOnly == enabled) return
|
||||
releaseAll()
|
||||
buttonsOnly = enabled
|
||||
quickHidden = false
|
||||
relayout()
|
||||
}
|
||||
|
||||
/** Hide the full touch pad for an unobstructed screen while keeping its quick toggle available. */
|
||||
fun setQuickHidden(hidden: Boolean) {
|
||||
if (buttonsOnly || editing || quickHidden == hidden) return
|
||||
if (hidden) releaseAll()
|
||||
quickHidden = hidden
|
||||
invalidate()
|
||||
}
|
||||
|
||||
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
|
||||
super.onSizeChanged(w, h, oldw, oldh)
|
||||
relayout()
|
||||
@@ -348,7 +359,7 @@ class OnScreenControls(context: Context, private val pad: PadBridge?, private va
|
||||
}
|
||||
|
||||
override fun onDraw(canvas: Canvas) {
|
||||
for (control in controls) {
|
||||
if (!quickHidden) for (control in controls) {
|
||||
if (!isVisible(control)) continue
|
||||
if (control.stick >= 0 && settings.adaptiveSticks && !editing && control.pressedBy == -1) continue
|
||||
val held = control.pressedBy != -1
|
||||
@@ -394,15 +405,37 @@ class OnScreenControls(context: Context, private val pad: PadBridge?, private va
|
||||
canvas.drawText(name, control.cx, control.cy + text.textSize * 0.35f, text)
|
||||
}
|
||||
}
|
||||
val group = selected ?: return
|
||||
val (x, y) = centre(group)
|
||||
stroke.color = heldStroke
|
||||
val single = members(group).singleOrNull()
|
||||
if (single?.wide == true) {
|
||||
val pad = dp(6f)
|
||||
box.set(x - single.halfW - pad, y - single.halfH - pad, x + single.halfW + pad, y + single.halfH + pad)
|
||||
canvas.drawRoundRect(box, single.halfH, single.halfH, stroke)
|
||||
} else canvas.drawCircle(x, y, extent(group) + dp(6f), stroke)
|
||||
if (editing) {
|
||||
val group = selected ?: return
|
||||
val (x, y) = centre(group)
|
||||
stroke.color = heldStroke
|
||||
val single = members(group).singleOrNull()
|
||||
if (single?.wide == true) {
|
||||
val pad = dp(6f)
|
||||
box.set(x - single.halfW - pad, y - single.halfH - pad, x + single.halfW + pad, y + single.halfH + pad)
|
||||
canvas.drawRoundRect(box, single.halfH, single.halfH, stroke)
|
||||
} else canvas.drawCircle(x, y, extent(group) + dp(6f), stroke)
|
||||
} else if (!buttonsOnly) {
|
||||
val (x, y) = quickCenter()
|
||||
val radius = dp(18f)
|
||||
fill.color = Color.argb(190, Color.red(idleFill), Color.green(idleFill), Color.blue(idleFill))
|
||||
canvas.drawCircle(x, y, radius, fill)
|
||||
stroke.color = idleStroke
|
||||
canvas.drawCircle(x, y, radius, stroke)
|
||||
text.color = idleText
|
||||
text.textSize = dp(22f)
|
||||
canvas.drawText(if (quickHidden) "+" else "−", x, y + text.textSize * 0.35f, text)
|
||||
}
|
||||
}
|
||||
|
||||
private fun quickCenter() = (safe.left + dp(34f)) to (height - safe.bottom - dp(34f))
|
||||
|
||||
private fun quickContains(x: Float, y: Float): Boolean {
|
||||
val (cx, cy) = quickCenter()
|
||||
val radius = dp(26f)
|
||||
val dx = x - cx
|
||||
val dy = y - cy
|
||||
return dx * dx + dy * dy <= radius * radius
|
||||
}
|
||||
|
||||
private fun drawArrow(canvas: Canvas, x: Float, y: Float, size: Float, direction: Int) {
|
||||
@@ -429,6 +462,12 @@ class OnScreenControls(context: Context, private val pad: PadBridge?, private va
|
||||
val index = event.actionIndex
|
||||
val x = event.getX(index)
|
||||
val y = event.getY(index)
|
||||
if (!buttonsOnly && event.actionMasked == MotionEvent.ACTION_DOWN && quickContains(x, y)) {
|
||||
quickPressedBy = event.getPointerId(index)
|
||||
return true
|
||||
}
|
||||
if (quickPressedBy != -1) return true
|
||||
if (quickHidden) return false
|
||||
val control = controlAt(x, y) ?: adaptiveStickAt(x, y) ?: return false
|
||||
if (control.pressedBy != -1) return true
|
||||
control.pressedBy = event.getPointerId(index)
|
||||
@@ -444,6 +483,7 @@ class OnScreenControls(context: Context, private val pad: PadBridge?, private va
|
||||
return true
|
||||
}
|
||||
MotionEvent.ACTION_MOVE -> {
|
||||
if (quickPressedBy != -1) return true
|
||||
var changed = false
|
||||
for (index in 0 until event.pointerCount) {
|
||||
val pointer = event.getPointerId(index)
|
||||
@@ -468,6 +508,18 @@ class OnScreenControls(context: Context, private val pad: PadBridge?, private va
|
||||
}
|
||||
MotionEvent.ACTION_UP, MotionEvent.ACTION_POINTER_UP, MotionEvent.ACTION_CANCEL -> {
|
||||
val pointer = event.getPointerId(event.actionIndex)
|
||||
if (event.actionMasked == MotionEvent.ACTION_CANCEL) {
|
||||
quickPressedBy = -1
|
||||
releaseAll()
|
||||
return true
|
||||
}
|
||||
if (quickPressedBy == pointer) {
|
||||
val toggled = event.actionMasked == MotionEvent.ACTION_UP && quickContains(event.x, event.y)
|
||||
quickPressedBy = -1
|
||||
if (toggled) setQuickHidden(!quickHidden)
|
||||
return true
|
||||
}
|
||||
if (quickHidden) return false
|
||||
var changed = false
|
||||
for (control in controls) {
|
||||
if (control.pressedBy == pointer || event.actionMasked == MotionEvent.ACTION_CANCEL) {
|
||||
@@ -510,11 +562,11 @@ class OnScreenControls(context: Context, private val pad: PadBridge?, private va
|
||||
|
||||
private fun controlAt(x: Float, y: Float): Control? =
|
||||
controls.firstOrNull {
|
||||
isVisible(it) && (editing || !settings.adaptiveSticks || it.stick < 0) && it.contains(x, y, it.radius)
|
||||
!quickHidden && isVisible(it) && (editing || !settings.adaptiveSticks || it.stick < 0) && it.contains(x, y, it.radius)
|
||||
}
|
||||
|
||||
private fun adaptiveStickAt(x: Float, y: Float): Control? {
|
||||
if (!settings.adaptiveSticks || editing || buttonsOnly) return null
|
||||
if (!settings.adaptiveSticks || editing || buttonsOnly || quickHidden) return null
|
||||
if (x < safe.left || x >= width - safe.right || y < safe.top || y >= height - safe.bottom) return null
|
||||
if (controls.any { it.stick < 0 && isVisible(it) && it.contains(x, y, it.radius, 5f) }) return null
|
||||
return controls.filter {
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
package com.droiddeck.launcher.input
|
||||
|
||||
import android.content.ClipData
|
||||
import android.content.ClipboardManager
|
||||
import android.content.Context
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.system.Os
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.wayland.WaylandCompositor
|
||||
import java.io.File
|
||||
import java.io.IOException
|
||||
|
||||
/** Text selections shared by Android and the guest while the session is visible. */
|
||||
class SessionClipboard(context: Context, private val hasFocus: () -> Boolean) {
|
||||
private val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
|
||||
private val handler = Handler(Looper.getMainLooper())
|
||||
private val hostFile = File(context.filesDir, "session/android-clipboard")
|
||||
private var active = false
|
||||
private val androidListener = ClipboardManager.OnPrimaryClipChangedListener { refresh() }
|
||||
private val guestListener = object : WaylandCompositor.ClipboardListener {
|
||||
override fun onGuestClipboardText(text: String) {
|
||||
// Native callbacks arrive on the compositor thread. Do not publish a delayed callback
|
||||
// after this activity has paused or been replaced.
|
||||
handler.post {
|
||||
if (active && hasFocus() && WaylandCompositor.isClipboardListener(this)) {
|
||||
val current = clipboard.primaryClip?.takeIf { it.itemCount > 0 }?.getItemAt(0)?.text
|
||||
if (current?.toString() != text) {
|
||||
clipboard.setPrimaryClip(ClipData.newPlainText("DroidDeck", text))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun start() {
|
||||
if (active) return
|
||||
active = true
|
||||
clipboard.addPrimaryClipChangedListener(androidListener)
|
||||
WaylandCompositor.setClipboardListener(guestListener)
|
||||
refresh()
|
||||
}
|
||||
|
||||
fun stop() {
|
||||
if (!active) return
|
||||
active = false
|
||||
clipboard.removePrimaryClipChangedListener(androidListener)
|
||||
WaylandCompositor.clearClipboardListener(guestListener)
|
||||
handler.removeCallbacksAndMessages(null)
|
||||
}
|
||||
|
||||
/** Android 10+ permits clipboard reads only with window focus. Resume can precede focus. */
|
||||
fun refresh() {
|
||||
if (!active || !hasFocus()) return
|
||||
val clip = clipboard.primaryClip
|
||||
// Only share literal text, never resolve content URIs or load copied files.
|
||||
if (clip == null) {
|
||||
publish(null)
|
||||
} else if (clip.itemCount > 0) {
|
||||
publish(clip.getItemAt(0).text?.toString())
|
||||
}
|
||||
}
|
||||
|
||||
private fun publish(text: String?) {
|
||||
WaylandCompositor.setClipboardText(text)
|
||||
// Gamescope needs the same selection in its own Xwayland. Rename complete UTF-8 text
|
||||
// into place so its helper never sees half a launch command. Kept in private app data.
|
||||
val pending = File(hostFile.parentFile, "android-clipboard.pending")
|
||||
try {
|
||||
hostFile.parentFile?.mkdirs()
|
||||
pending.writeText(text.orEmpty(), Charsets.UTF_8)
|
||||
Os.rename(pending.path, hostFile.path)
|
||||
} catch (e: IOException) {
|
||||
Log.w("SessionClipboard", "Could not share text with Xwayland", e)
|
||||
} catch (e: android.system.ErrnoException) {
|
||||
Log.w("SessionClipboard", "Could not publish text for Xwayland", e)
|
||||
} finally {
|
||||
pending.delete()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -66,6 +66,17 @@ class TouchpadGestures(
|
||||
listener.onButton(PointerGestures.BTN_LEFT, true, x, y)
|
||||
}
|
||||
|
||||
fun cancel() {
|
||||
handler.removeCallbacks(longPress)
|
||||
if (dragging) listener.onButton(PointerGestures.BTN_LEFT, false, x, y)
|
||||
dragging = false
|
||||
held = false
|
||||
holdDrag = false
|
||||
anchorId = -1
|
||||
moverId = -1
|
||||
lastTapAt = 0L
|
||||
}
|
||||
|
||||
fun place(px: Float, py: Float) {
|
||||
x = px.coerceIn(bounds.left, bounds.right)
|
||||
y = py.coerceIn(bounds.top, bounds.bottom)
|
||||
|
||||
@@ -1,17 +1,30 @@
|
||||
package com.droiddeck.launcher.runtime
|
||||
|
||||
import android.content.BroadcastReceiver
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.IntentFilter
|
||||
import android.location.LocationManager
|
||||
import android.net.ConnectivityManager
|
||||
import android.net.LinkProperties
|
||||
import android.net.Network
|
||||
import android.net.NetworkCapabilities
|
||||
import android.net.wifi.WifiInfo
|
||||
import android.net.wifi.WifiManager
|
||||
import android.os.Build
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.os.SystemClock
|
||||
import android.provider.Settings
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.core.SessionPart
|
||||
import com.droiddeck.launcher.core.WifiDiscovery
|
||||
import java.io.File
|
||||
import java.io.IOException
|
||||
import java.net.Inet4Address
|
||||
import java.net.Inet6Address
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
|
||||
/**
|
||||
* The device's network link, published for the Linux runtime's processes.
|
||||
@@ -34,20 +47,94 @@ class LinuxNetworkLinkComponent(
|
||||
appContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
|
||||
private val lock = Any()
|
||||
private var callback: ConnectivityManager.NetworkCallback? = null
|
||||
private var currentNetwork: Network? = null
|
||||
private var currentProperties: LinkProperties? = null
|
||||
private var currentCapabilities: NetworkCapabilities? = null
|
||||
private val wifiManager = appContext.getSystemService(Context.WIFI_SERVICE) as? WifiManager
|
||||
private val scanHandler = Handler(Looper.getMainLooper())
|
||||
private var wifiReceiver: BroadcastReceiver? = null
|
||||
private var scanRequestStamp = 0L
|
||||
private var lastScanRequest = -SCAN_INTERVAL_MS
|
||||
@Volatile private var lastNamesAllowed = false
|
||||
private val scanRequests = object : Runnable {
|
||||
override fun run() {
|
||||
if (canReadWifiNames() != lastNamesAllowed) {
|
||||
synchronized(lock) { writeNetworkState(currentProperties, currentCapabilities) }
|
||||
requestWifiScan()
|
||||
}
|
||||
val stamp = File(rootDir, "etc/bannerlator-wifi-scan-request").lastModified()
|
||||
if (stamp != 0L && stamp != scanRequestStamp) {
|
||||
scanRequestStamp = stamp
|
||||
requestWifiScan()
|
||||
}
|
||||
if (wifiReceiver != null) scanHandler.postDelayed(this, 1000)
|
||||
}
|
||||
}
|
||||
|
||||
/** Called before the session starts, so its first process already sees the link. */
|
||||
fun publish() = write(connectivity.activeNetwork?.let(connectivity::getLinkProperties))
|
||||
fun publish() = synchronized(lock) {
|
||||
currentNetwork = connectivity.activeNetwork
|
||||
currentProperties = currentNetwork?.let(connectivity::getLinkProperties)
|
||||
currentCapabilities = currentNetwork?.let(connectivity::getNetworkCapabilities)
|
||||
write(currentProperties, currentCapabilities)
|
||||
}
|
||||
|
||||
override fun start() {
|
||||
val registered = object : ConnectivityManager.NetworkCallback() {
|
||||
override fun onLinkPropertiesChanged(network: Network, properties: LinkProperties) = write(properties)
|
||||
override fun onLost(network: Network) = write(null)
|
||||
override fun onAvailable(network: Network) = synchronized(lock) {
|
||||
currentNetwork = network
|
||||
currentProperties = null
|
||||
currentCapabilities = null
|
||||
}
|
||||
|
||||
override fun onCapabilitiesChanged(network: Network, capabilities: NetworkCapabilities) = synchronized(lock) {
|
||||
if (network == currentNetwork) {
|
||||
currentCapabilities = capabilities
|
||||
if (currentProperties != null) write(currentProperties, capabilities)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onLinkPropertiesChanged(network: Network, properties: LinkProperties) = synchronized(lock) {
|
||||
if (network == currentNetwork) {
|
||||
currentProperties = properties
|
||||
write(properties, currentCapabilities)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onLost(network: Network) = synchronized(lock) {
|
||||
// A handover can report the old link lost after the new default arrived.
|
||||
if (network == currentNetwork) {
|
||||
currentNetwork = null
|
||||
currentProperties = null
|
||||
currentCapabilities = null
|
||||
write(null, null)
|
||||
}
|
||||
}
|
||||
}
|
||||
synchronized(lock) { callback = registered }
|
||||
connectivity.registerDefaultNetworkCallback(registered)
|
||||
val receiver = object : BroadcastReceiver() {
|
||||
override fun onReceive(context: Context?, intent: Intent?) {
|
||||
synchronized(lock) { writeNetworkState(currentProperties, currentCapabilities) }
|
||||
}
|
||||
}
|
||||
wifiReceiver = receiver
|
||||
appContext.registerReceiver(receiver, IntentFilter().apply {
|
||||
addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)
|
||||
addAction(WifiManager.RSSI_CHANGED_ACTION)
|
||||
addAction(WifiManager.WIFI_STATE_CHANGED_ACTION)
|
||||
addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION)
|
||||
addAction(LocationManager.MODE_CHANGED_ACTION)
|
||||
})
|
||||
scanRequestStamp = File(rootDir, "etc/bannerlator-wifi-scan-request").lastModified()
|
||||
scanHandler.post(scanRequests)
|
||||
requestWifiScan()
|
||||
}
|
||||
|
||||
override fun stop() {
|
||||
scanHandler.removeCallbacks(scanRequests)
|
||||
wifiReceiver?.let { appContext.unregisterReceiver(it) }
|
||||
wifiReceiver = null
|
||||
val registered = synchronized(lock) { callback.also { callback = null } } ?: return
|
||||
try {
|
||||
connectivity.unregisterNetworkCallback(registered)
|
||||
@@ -56,7 +143,22 @@ class LinuxNetworkLinkComponent(
|
||||
}
|
||||
}
|
||||
|
||||
private fun write(properties: LinkProperties?) {
|
||||
private fun canReadWifiNames(): Boolean = WifiDiscovery.available(appContext)
|
||||
|
||||
@Suppress("DEPRECATION")
|
||||
private fun requestWifiScan() {
|
||||
val now = SystemClock.elapsedRealtime()
|
||||
if (!canReadWifiNames() || wifiManager?.isWifiEnabled != true || now - lastScanRequest < SCAN_INTERVAL_MS) return
|
||||
lastScanRequest = now
|
||||
try {
|
||||
Log.i(TAG, "Wi-Fi scan requested: accepted=${wifiManager.startScan()}")
|
||||
} catch (e: SecurityException) {
|
||||
Log.w(TAG, "Wi-Fi scan permission unavailable")
|
||||
}
|
||||
synchronized(lock) { writeNetworkState(currentProperties, currentCapabilities) }
|
||||
}
|
||||
|
||||
private fun write(properties: LinkProperties?, capabilities: NetworkCapabilities?) {
|
||||
val file = File(rootDir, LINK_FILE)
|
||||
synchronized(lock) {
|
||||
try {
|
||||
@@ -67,10 +169,99 @@ class LinuxNetworkLinkComponent(
|
||||
} catch (e: IOException) {
|
||||
Log.w(TAG, "Could not publish the network link", e)
|
||||
}
|
||||
writeNetworkState(properties, capabilities)
|
||||
writeResolver(properties)
|
||||
}
|
||||
}
|
||||
|
||||
/** NetworkManager's view of Android. Kept separate from netif.c's legacy adapter format. */
|
||||
@Suppress("DEPRECATION")
|
||||
private fun writeNetworkState(properties: LinkProperties?, capabilities: NetworkCapabilities?) {
|
||||
val namesAllowed = canReadWifiNames()
|
||||
lastNamesAllowed = namesAllowed
|
||||
val scans = if (namesAllowed && wifiManager?.isWifiEnabled == true) {
|
||||
try { wifiManager.scanResults.orEmpty() } catch (e: SecurityException) { emptyList() }
|
||||
} else emptyList()
|
||||
val transport = when {
|
||||
capabilities == null -> "none"
|
||||
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> "wifi"
|
||||
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> "cellular"
|
||||
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) -> "ethernet"
|
||||
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_VPN) -> "vpn"
|
||||
else -> "other"
|
||||
}
|
||||
val state = JSONObject().apply {
|
||||
put("transport", transport)
|
||||
put("interface", properties?.interfaceName ?: "android")
|
||||
put("mtu", properties?.mtu?.takeIf { it > 0 } ?: DEFAULT_MTU)
|
||||
put("connected", properties != null && capabilities != null)
|
||||
put("validated", capabilities?.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED) == true)
|
||||
put("captivePortal", capabilities?.hasCapability(NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL) == true)
|
||||
put("metered", capabilities?.let { !it.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED) })
|
||||
put("wifiEnabled", wifiManager?.isWifiEnabled == true)
|
||||
put("scanAllowed", namesAllowed)
|
||||
put("lastScan", scans.maxOfOrNull { it.timestamp / 1000 } ?: -1L)
|
||||
put("accessPoints", JSONArray().apply {
|
||||
scans.filter { it.SSID.isNotEmpty() }.forEach {
|
||||
put(JSONObject().apply {
|
||||
put("ssid", it.SSID)
|
||||
put("bssid", it.BSSID)
|
||||
put("strength", WifiManager.calculateSignalLevel(it.level, 101))
|
||||
put("frequency", it.frequency)
|
||||
put("capabilities", it.capabilities)
|
||||
put("lastSeen", it.timestamp / 1_000_000)
|
||||
})
|
||||
}
|
||||
})
|
||||
put("addresses", JSONArray().apply {
|
||||
properties?.linkAddresses.orEmpty().forEach {
|
||||
put(JSONObject().put("address", it.address.hostAddress?.substringBefore('%')).put("prefix", it.prefixLength))
|
||||
}
|
||||
})
|
||||
put("gateways", JSONArray().apply {
|
||||
properties?.routes.orEmpty().filter { it.isDefaultRoute }.forEach {
|
||||
it.gateway?.takeUnless { address -> address.isAnyLocalAddress }?.let { address ->
|
||||
put(address.hostAddress?.substringBefore('%'))
|
||||
}
|
||||
}
|
||||
})
|
||||
put("dns", JSONArray().apply {
|
||||
properties?.dnsServers.orEmpty().filter { !it.isLinkLocalAddress }.forEach {
|
||||
put(it.hostAddress?.substringBefore('%'))
|
||||
}
|
||||
})
|
||||
if (transport == "wifi") {
|
||||
val connectionInfo = try { wifiManager?.connectionInfo } catch (e: SecurityException) { null }
|
||||
val info = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
||||
(capabilities?.transportInfo as? WifiInfo) ?: connectionInfo
|
||||
} else {
|
||||
connectionInfo
|
||||
}
|
||||
if (info != null) {
|
||||
// SSIDs can be redacted by Android. No location permission is needed to
|
||||
// report the transport; a hidden name simply displays as Wi-Fi in Steam.
|
||||
if (namesAllowed) {
|
||||
val namedInfo = connectionInfo ?: info
|
||||
namedInfo.ssid?.takeUnless { it == WifiManager.UNKNOWN_SSID || it.isEmpty() }
|
||||
?.removeSurrounding("\"")?.let { put("ssid", it) }
|
||||
namedInfo.bssid?.takeUnless { it == "02:00:00:00:00:00" }?.let { put("bssid", it) }
|
||||
}
|
||||
put("strength", WifiManager.calculateSignalLevel(info.rssi, 101))
|
||||
put("frequency", info.frequency.coerceAtLeast(0))
|
||||
put("bitrate", info.linkSpeed.coerceAtLeast(0) * 1000)
|
||||
}
|
||||
}
|
||||
}
|
||||
try {
|
||||
val file = File(rootDir, "etc/bannerlator-network.json")
|
||||
val staged = File(file.path + ".staged")
|
||||
staged.writeText(state.toString())
|
||||
if (!staged.renameTo(file)) throw IOException("Could not replace network state")
|
||||
} catch (e: IOException) {
|
||||
Log.w(TAG, "Could not publish the network state", e)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The guest's resolver, from the network it is actually on. glibc reads /etc/resolv.conf,
|
||||
* and the image ships two public servers there, which is why Steam resolves at all - but a
|
||||
@@ -149,5 +340,6 @@ class LinuxNetworkLinkComponent(
|
||||
private const val DEFAULT_MTU = 1500
|
||||
private const val OFFLINE_NAME = "eth0"
|
||||
private const val OFFLINE_ADDRESS = "10.0.0.2 24"
|
||||
private const val SCAN_INTERVAL_MS = 30_000L
|
||||
}
|
||||
}
|
||||
@@ -229,6 +229,17 @@ public final class LinuxRuntime {
|
||||
// It then fails the isFile() test below and the session runs as it did before.
|
||||
}
|
||||
}
|
||||
// protonfixes, which GE-Proton and proton-cachyos run before every game, opens this to
|
||||
// check the esync file limit and dies on the PermissionError, so no game starts with them.
|
||||
// The value is the 64-bit kernel default.
|
||||
File fileMax = new File(fakeProc, "file-max");
|
||||
if (!fileMax.isFile()) {
|
||||
try {
|
||||
Files.write(fileMax.toPath(), "9223372036854775807\n".getBytes(StandardCharsets.US_ASCII));
|
||||
} catch (IOException e) {
|
||||
// Left unbound, as above.
|
||||
}
|
||||
}
|
||||
String[][] procFiles = {
|
||||
{"pci_devices", "/proc/bus/pci/devices"},
|
||||
{"stat", "/proc/stat"},
|
||||
@@ -239,6 +250,7 @@ public final class LinuxRuntime {
|
||||
{"cap_last_cap", "/proc/sys/kernel/cap_last_cap"},
|
||||
{"overflowuid", "/proc/sys/kernel/overflowuid"},
|
||||
{"overflowgid", "/proc/sys/kernel/overflowgid"},
|
||||
{"file-max", "/proc/sys/fs/file-max"},
|
||||
};
|
||||
for (String[] entry : procFiles) {
|
||||
File fake = new File(fakeProc, entry[0]);
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
/** Platform-independent eligibility; a service existing alone does not mean it has a picture. */
|
||||
object PipPolicy {
|
||||
fun eligible(running: Boolean, frameSeen: Boolean, phase: SessionPhase, suspended: Boolean, automatic: Boolean): Boolean =
|
||||
running && frameSeen && phase in setOf(SessionPhase.READY, SessionPhase.SUSPENDED) &&
|
||||
(!automatic || !suspended)
|
||||
|
||||
fun aspect(width: Int, height: Int): Pair<Int, Int> = when {
|
||||
width <= 0 || height <= 0 -> 16 to 9
|
||||
width.toDouble() / height > 2.39 -> 239 to 100
|
||||
height.toDouble() / width > 2.39 -> 100 to 239
|
||||
else -> width to height
|
||||
}
|
||||
}
|
||||
@@ -45,7 +45,6 @@ object SessionArtifacts {
|
||||
}
|
||||
LogRedactor.learnFromRuntime(LinuxRuntime.rootDir(context))
|
||||
copySteamLogs(context, dir)
|
||||
VacDiagnostics.collect(context, dir)
|
||||
// A session the system killed leaves its trace here and nowhere else.
|
||||
SessionLogCapture.dumpCrashBuffer(File(dir, "crash.log"))
|
||||
scrubFolder(dir)
|
||||
@@ -146,7 +145,6 @@ object SessionArtifacts {
|
||||
)
|
||||
if (newest) {
|
||||
copySteamLogs(context, dir)
|
||||
VacDiagnostics.collect(context, dir)
|
||||
}
|
||||
SessionLogCapture.dumpCrashBuffer(File(dir, "crash.log"))
|
||||
SessionEvents.record("session.artifacts_recovered", mapOf("newest" to newest), dir)
|
||||
|
||||
@@ -32,12 +32,14 @@ object SessionFiles {
|
||||
"libfakeinput.so" to "usr/local/lib/libfakeinput.so",
|
||||
"libblfastpath.so" to "usr/local/lib/libblfastpath.so",
|
||||
"usr/local/bin/bannerlator-session" to "usr/local/bin/bannerlator-session",
|
||||
"usr/local/bin/droiddeck-clipboard" to "usr/local/bin/droiddeck-clipboard",
|
||||
"usr/local/bin/bannerlator-steam-compat" to "usr/local/bin/bannerlator-steam-compat",
|
||||
"usr/local/bin/bannerlator-steam-install" to "usr/local/bin/bannerlator-steam-install",
|
||||
"usr/local/bin/bannerlator-steam-library" to "usr/local/bin/bannerlator-steam-library",
|
||||
"usr/local/bin/bannerlator-seed-redists" to "usr/local/bin/bannerlator-seed-redists",
|
||||
"usr/local/bin/bannerlator-proton-extra" to "usr/local/bin/bannerlator-proton-extra",
|
||||
"usr/local/bin/bannerlator-netmanager" to "usr/local/bin/bannerlator-netmanager",
|
||||
"usr/local/bin/bannerlator-login1" to "usr/local/bin/bannerlator-login1",
|
||||
"usr/local/bin/bannerlator-steam-launch" to "usr/local/bin/bannerlator-steam-launch",
|
||||
"usr/local/bin/bannerlator-desktop-games" to "usr/local/bin/bannerlator-desktop-games",
|
||||
"usr/local/bin/bannerlator-steam-shim" to "usr/local/bin/bannerlator-steam-shim",
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.app.AppOpsManager
|
||||
import android.app.PictureInPictureParams
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
import android.graphics.Rect
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
import android.util.Rational
|
||||
import android.widget.Toast
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.SessionActivity
|
||||
|
||||
/** Owns Android's PiP parameters, while the service continues to own the session. */
|
||||
class SessionPipController(
|
||||
private val activity: SessionActivity,
|
||||
private val bounds: () -> Rect,
|
||||
private val showPipUi: (Boolean) -> Unit,
|
||||
) {
|
||||
var transitioning = false
|
||||
private set
|
||||
private var suppressAuto = false
|
||||
private var visit = false
|
||||
private var lastParams = ""
|
||||
val floating get() = transitioning || activity.isInPictureInPictureMode
|
||||
|
||||
fun eligible(automatic: Boolean = false) = supported(activity) && !activity.isFinishing &&
|
||||
PipPolicy.eligible(SessionState.running, SessionState.firstFrameSeen, SessionState.phase,
|
||||
SessionState.suspended, automatic)
|
||||
|
||||
fun automatic() = !suppressAuto && SessionPrefs.pipAutoEnter(activity) && eligible(true)
|
||||
|
||||
fun refresh(force: Boolean = false) {
|
||||
if (!supported(activity)) return
|
||||
val rect = bounds()
|
||||
val key = "$rect:${SessionState.outputSize}:${automatic()}:${SessionState.suspended}"
|
||||
if (!force && key == lastParams) return
|
||||
lastParams = key
|
||||
runCatching { activity.setPictureInPictureParams(params(rect)) }
|
||||
}
|
||||
|
||||
private fun params(rect: Rect): PictureInPictureParams {
|
||||
val (w, h) = PipPolicy.aspect(SessionState.outputSize.first, SessionState.outputSize.second)
|
||||
val builder = PictureInPictureParams.Builder().setAspectRatio(Rational(w, h))
|
||||
if (!rect.isEmpty) builder.setSourceRectHint(rect)
|
||||
if (Build.VERSION.SDK_INT >= 31) builder.setAutoEnterEnabled(automatic()).setSeamlessResizeEnabled(false)
|
||||
return builder.build()
|
||||
}
|
||||
|
||||
fun enter() {
|
||||
if (!eligible()) {
|
||||
Toast.makeText(activity, R.string.pip_not_ready, Toast.LENGTH_SHORT).show()
|
||||
return
|
||||
}
|
||||
if (!allowed()) {
|
||||
Toast.makeText(activity, R.string.pip_permission, Toast.LENGTH_SHORT).show()
|
||||
runCatching { activity.startActivity(Intent("android.settings.PICTURE_IN_PICTURE_SETTINGS",
|
||||
Uri.parse("package:${activity.packageName}"))) }
|
||||
return
|
||||
}
|
||||
prepare()
|
||||
val entered = runCatching { activity.enterPictureInPictureMode(params(bounds())) }.getOrDefault(false)
|
||||
if (!entered) {
|
||||
restore()
|
||||
Toast.makeText(activity, R.string.pip_unavailable, Toast.LENGTH_SHORT).show()
|
||||
}
|
||||
}
|
||||
|
||||
fun leaving() {
|
||||
if (!automatic() || !allowed()) return
|
||||
if (Build.VERSION.SDK_INT < 31) enter() else prepare()
|
||||
}
|
||||
|
||||
private fun prepare() {
|
||||
if (floating) return
|
||||
transitioning = true
|
||||
showPipUi(true)
|
||||
}
|
||||
|
||||
fun changed(inPip: Boolean) {
|
||||
if (inPip) {
|
||||
transitioning = false
|
||||
visit = true
|
||||
SessionState.pipActive = true
|
||||
showPipUi(true)
|
||||
SessionService.beginPip(activity)
|
||||
SessionService.setActivityVisible(activity, true)
|
||||
} else restore()
|
||||
refresh(true)
|
||||
}
|
||||
|
||||
private fun restore() {
|
||||
val needsRestore = transitioning || visit
|
||||
transitioning = false
|
||||
if (visit) {
|
||||
SessionState.pipActive = false
|
||||
visit = false
|
||||
}
|
||||
if (needsRestore) showPipUi(false)
|
||||
}
|
||||
|
||||
fun resumed() {
|
||||
suppressAuto = false
|
||||
if (!activity.isInPictureInPictureMode) {
|
||||
restore()
|
||||
if (SessionState.running) SessionService.setActivityVisible(activity, true)
|
||||
}
|
||||
refresh(true)
|
||||
}
|
||||
|
||||
fun background() { suppressAuto = true; refresh(true) }
|
||||
fun destroyed() { if (visit) restore() }
|
||||
|
||||
private fun allowed(): Boolean {
|
||||
val ops = activity.getSystemService(AppOpsManager::class.java)
|
||||
@Suppress("DEPRECATION")
|
||||
return ops.checkOpNoThrow(AppOpsManager.OPSTR_PICTURE_IN_PICTURE,
|
||||
android.os.Process.myUid(), activity.packageName) == AppOpsManager.MODE_ALLOWED
|
||||
}
|
||||
|
||||
companion object {
|
||||
fun supported(context: android.content.Context) = context.packageManager
|
||||
.hasSystemFeature(PackageManager.FEATURE_PICTURE_IN_PICTURE)
|
||||
}
|
||||
}
|
||||
@@ -220,6 +220,19 @@ object SessionPrefs {
|
||||
prefs(context).edit().putBoolean("mic", on).apply()
|
||||
}
|
||||
|
||||
/** Optional SSID reporting and scans. A Location grant alone never opts the user in. */
|
||||
fun wifiDiscoveryEnabled(context: Context): Boolean = prefs(context).getBoolean("wifiDiscovery", false)
|
||||
|
||||
fun setWifiDiscoveryEnabled(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("wifiDiscovery", on).apply()
|
||||
}
|
||||
|
||||
fun wifiDiscoveryAsked(context: Context): Boolean = prefs(context).getBoolean("wifiDiscoveryAsked", false)
|
||||
|
||||
fun setWifiDiscoveryAsked(context: Context) {
|
||||
prefs(context).edit().putBoolean("wifiDiscoveryAsked", true).apply()
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the client's own core pick is overridden. When on, BL_CLIENT_CPUS is sent even when
|
||||
* it names every core - unlike a game mask, the point here is to undo a pin Steam applies to
|
||||
@@ -424,18 +437,6 @@ object SessionPrefs {
|
||||
prefs(context).edit().putBoolean("logs", on).apply()
|
||||
}
|
||||
|
||||
/**
|
||||
* VAC diagnostics (see [VacDiagnostics]): Source-engine games launched with -condebug and their
|
||||
* console plus the client's VAC lines summarised into vac.txt. Off by default: it changes a
|
||||
* game's command line.
|
||||
*/
|
||||
fun vacDiagnostics(context: Context): Boolean =
|
||||
prefs(context).getBoolean("vac_diagnostics", false)
|
||||
|
||||
fun setVacDiagnostics(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("vac_diagnostics", on).apply()
|
||||
}
|
||||
|
||||
// ── Per-mode display ────────────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
@@ -600,12 +601,38 @@ object SessionPrefs {
|
||||
|
||||
val fpsLimitChoices = listOf(0 to "Off", 30 to "30", 40 to "40", 45 to "45", 60 to "60", 90 to "90", 120 to "120")
|
||||
|
||||
val upscalerChoices = listOf(
|
||||
0 to "Off", 4 to "AMD FSR 1", 3 to "Snapdragon GSR", 8 to "Snapdragon GSR (quality)",
|
||||
7 to "NVIDIA NIS", 6 to "Sharpen only",
|
||||
)
|
||||
|
||||
fun upscaler(context: Context): Int =
|
||||
prefs(context).getInt("upscaler", 0).takeIf { m -> upscalerChoices.any { it.first == m } } ?: 0
|
||||
|
||||
fun setUpscaler(context: Context, mode: Int) {
|
||||
prefs(context).edit().putInt("upscaler", mode).apply()
|
||||
}
|
||||
|
||||
val upscaleSharpnessChoices = listOf(0 to "0%", 25 to "25%", 50 to "50%", 75 to "75%", 100 to "100%")
|
||||
|
||||
fun upscaleSharpness(context: Context): Int = prefs(context).getInt("upscaleSharpness", 75).coerceIn(0, 100)
|
||||
|
||||
fun setUpscaleSharpness(context: Context, pct: Int) {
|
||||
prefs(context).edit().putInt("upscaleSharpness", pct.coerceIn(0, 100)).apply()
|
||||
}
|
||||
|
||||
/**
|
||||
* The mode whose per-mode settings apply: a program run under gamescope (MODE_RUN) is a
|
||||
* fullscreen session like Steam's, so it takes Steam's display, driver and HDR choices.
|
||||
*/
|
||||
fun prefMode(mode: String): String = if (mode == SessionService.MODE_RUN) SessionService.MODE_STEAM else mode
|
||||
|
||||
fun pipAutoEnter(context: Context): Boolean = prefs(context).getBoolean("pipAutoEnter", false)
|
||||
|
||||
fun setPipAutoEnter(context: Context, enabled: Boolean) {
|
||||
prefs(context).edit().putBoolean("pipAutoEnter", enabled).apply()
|
||||
}
|
||||
|
||||
fun suspendPolicy(context: Context, mode: String): String =
|
||||
prefs(context).getString("suspendPolicy.${prefMode(mode)}", SUSPEND_MANUAL)
|
||||
?.takeIf { it == SUSPEND_AUTO || it == SUSPEND_MANUAL || it == SUSPEND_NEVER }
|
||||
|
||||
@@ -33,6 +33,7 @@ import com.droiddeck.launcher.core.NetworkReport
|
||||
import com.droiddeck.launcher.core.SessionPart
|
||||
import com.droiddeck.launcher.core.FileUtils
|
||||
import com.droiddeck.launcher.core.HostProcess
|
||||
import com.droiddeck.launcher.frontend.GameLaunchLink
|
||||
import com.droiddeck.launcher.input.FakeInputWriter
|
||||
import com.droiddeck.launcher.runtime.LinuxNetworkLinkComponent
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
@@ -74,8 +75,17 @@ class SessionService : Service() {
|
||||
private var activityVisible = true
|
||||
private var screenOn = true
|
||||
private var manualPauseRequested = false
|
||||
/** An explicit Steam sleep request is independent of the background policy. */
|
||||
private var steamSleepToken: String? = null
|
||||
private var suspendOperationPending = false
|
||||
private var pipTask = false
|
||||
private var suspendAttemptFailed = false
|
||||
/** One validated game request waiting for this Steam session to reach a usable state. */
|
||||
private var pendingSteamGameId: String? = null
|
||||
private var pendingSteamGameGeneration = -1
|
||||
private val flushSteamGame = object : Runnable {
|
||||
override fun run() = flushQueuedSteamGame()
|
||||
}
|
||||
private var screenReceiverRegistered = false
|
||||
private val screenReceiver = object : BroadcastReceiver() {
|
||||
override fun onReceive(context: Context?, intent: Intent?) {
|
||||
@@ -84,6 +94,7 @@ class SessionService : Service() {
|
||||
Intent.ACTION_SCREEN_ON -> screenOn = true
|
||||
else -> return
|
||||
}
|
||||
if (screenOn) resumeSteamSleepOnReturn()
|
||||
suspendAttemptFailed = false
|
||||
updateSuspendPolicy()
|
||||
}
|
||||
@@ -104,6 +115,10 @@ class SessionService : Service() {
|
||||
|
||||
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||
when (intent?.action) {
|
||||
ACTION_LAUNCH_GAME -> {
|
||||
queueSteamGame(intent.getStringExtra(EXTRA_GAME_ID))
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
ACTION_TRACK_AUXILIARY -> {
|
||||
val pid = intent.getIntExtra(EXTRA_AUXILIARY_PID, -1)
|
||||
val started = if (pid > 1) readStat(pid)?.second else null
|
||||
@@ -137,8 +152,14 @@ class SessionService : Service() {
|
||||
stopSession(0)
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
ACTION_PIP_BEGIN -> {
|
||||
pipTask = true
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
ACTION_ACTIVITY_VISIBLE -> {
|
||||
if (!SessionState.pipActive) pipTask = false
|
||||
activityVisible = true
|
||||
resumeSteamSleepOnReturn()
|
||||
suspendAttemptFailed = false
|
||||
updateSuspendPolicy()
|
||||
return START_NOT_STICKY
|
||||
@@ -157,11 +178,7 @@ class SessionService : Service() {
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
ACTION_RESUME -> {
|
||||
activityVisible = true
|
||||
screenOn = (getSystemService(Context.POWER_SERVICE) as? PowerManager)?.isInteractive ?: screenOn
|
||||
manualPauseRequested = false
|
||||
suspendAttemptFailed = false
|
||||
updateSuspendPolicy()
|
||||
resumeSession()
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
}
|
||||
@@ -177,10 +194,13 @@ class SessionService : Service() {
|
||||
activityVisible = true
|
||||
screenOn = (getSystemService(Context.POWER_SERVICE) as? PowerManager)?.isInteractive ?: true
|
||||
manualPauseRequested = false
|
||||
steamSleepToken = null
|
||||
suspendOperationPending = false
|
||||
suspendAttemptFailed = false
|
||||
suspendController = null
|
||||
SessionState.suspended = false
|
||||
SessionState.pipActive = false
|
||||
pipTask = false
|
||||
SessionState.program = intent?.getStringExtra(EXTRA_PROGRAM)
|
||||
SessionState.programArgs = intent?.getStringArrayExtra(EXTRA_PROGRAM_ARGS)?.toList().orEmpty()
|
||||
SessionState.steamUi = intent?.getStringExtra(EXTRA_STEAM_UI)
|
||||
@@ -201,6 +221,8 @@ class SessionService : Service() {
|
||||
// replaces can report its own exit in the gap between the two, and that exit must not
|
||||
// be taken as this one's.
|
||||
val gen = ++sessionGen
|
||||
cancelQueuedSteamGame(clearMailbox = false)
|
||||
clearSteamGameMailbox()
|
||||
acquireLocks()
|
||||
Thread({
|
||||
// A tree the last session left behind (the app was killed or crashed, so its teardown
|
||||
@@ -267,7 +289,6 @@ class SessionService : Service() {
|
||||
val runtimeDir = File(filesDir, ".wayland-rt").apply { mkdirs() }
|
||||
killStragglers()
|
||||
SessionFiles.stage(this, root)
|
||||
VacDiagnostics.arm(this)
|
||||
|
||||
val sessionDir = openSessionFolder()
|
||||
val sessionLog = File(sessionDir, "session.log")
|
||||
@@ -515,6 +536,7 @@ class SessionService : Service() {
|
||||
guest.add("XDG_RUNTIME_DIR=" + LinuxRuntime.GUEST_RUNTIME_DIR)
|
||||
guest.add("XDG_SESSION_TYPE=wayland")
|
||||
guest.add("WAYLAND_DISPLAY=wayland-0")
|
||||
guest.add("BL_ANDROID_CLIPBOARD=" + File(filesDir, "session/android-clipboard").path)
|
||||
guest.add("GAMESCOPE_FORCE_GENERAL_QUEUE=1")
|
||||
// Steam's CEF needs GL and the rootfs ships no native GL driver: route it through Zink.
|
||||
guest.add("MESA_LOADER_DRIVER_OVERRIDE=zink")
|
||||
@@ -878,6 +900,79 @@ class SessionService : Service() {
|
||||
return !File("/proc/$pid").exists()
|
||||
}
|
||||
|
||||
private fun queueSteamGame(gameId: String?) {
|
||||
if (!GameLaunchLink.validId(gameId.orEmpty()) || !SessionState.running ||
|
||||
SessionState.mode != MODE_STEAM || SessionState.stopRequested) {
|
||||
Log.w(TAG, "ignored game launch outside a running Steam session")
|
||||
return
|
||||
}
|
||||
val accepted = gameId!!
|
||||
if (pendingSteamGameId != null) Log.i(TAG, "replacing a queued game launch with $accepted")
|
||||
pendingSteamGameId = accepted
|
||||
pendingSteamGameGeneration = sessionGen
|
||||
if (SessionState.suspended) resumeSession()
|
||||
mainHandler.removeCallbacks(flushSteamGame)
|
||||
mainHandler.post(flushSteamGame)
|
||||
}
|
||||
|
||||
private fun flushQueuedSteamGame() {
|
||||
val gameId = pendingSteamGameId ?: return
|
||||
val gen = pendingSteamGameGeneration
|
||||
if (gen != sessionGen || !SessionState.running || SessionState.stopRequested ||
|
||||
SessionState.mode != MODE_STEAM || !GameLaunchLink.validId(gameId)) {
|
||||
cancelQueuedSteamGame()
|
||||
return
|
||||
}
|
||||
if (SessionState.suspended) {
|
||||
resumeSession()
|
||||
mainHandler.postDelayed(flushSteamGame, GAME_LAUNCH_RETRY_MS)
|
||||
return
|
||||
}
|
||||
if (SessionState.phase != SessionPhase.READY) {
|
||||
mainHandler.postDelayed(flushSteamGame, GAME_LAUNCH_RETRY_MS)
|
||||
return
|
||||
}
|
||||
|
||||
val directory = LinuxRuntime.sessionRoot(this)
|
||||
val staged = File(directory, STEAM_GAME_REQUEST + ".tmp")
|
||||
val request = File(directory, STEAM_GAME_REQUEST)
|
||||
val written = runCatching {
|
||||
directory.mkdirs()
|
||||
staged.writeText("$gameId\n")
|
||||
check(staged.renameTo(request)) { "could not publish Steam game request" }
|
||||
}.onFailure { Log.w(TAG, "could not queue Steam game $gameId", it) }.isSuccess
|
||||
if (!written) {
|
||||
mainHandler.postDelayed(flushSteamGame, GAME_LAUNCH_RETRY_MS)
|
||||
return
|
||||
}
|
||||
pendingSteamGameId = null
|
||||
pendingSteamGameGeneration = -1
|
||||
SessionEvents.record("steam.game_launch_requested", mapOf("gameId" to gameId, "generation" to gen))
|
||||
Log.i(TAG, "queued Steam game $gameId for the running client")
|
||||
}
|
||||
|
||||
private fun resumeSession() {
|
||||
activityVisible = true
|
||||
screenOn = (getSystemService(Context.POWER_SERVICE) as? PowerManager)?.isInteractive ?: screenOn
|
||||
manualPauseRequested = false
|
||||
completeSteamSleep()
|
||||
suspendAttemptFailed = false
|
||||
updateSuspendPolicy()
|
||||
}
|
||||
|
||||
private fun cancelQueuedSteamGame(clearMailbox: Boolean = true) {
|
||||
mainHandler.removeCallbacks(flushSteamGame)
|
||||
pendingSteamGameId = null
|
||||
pendingSteamGameGeneration = -1
|
||||
if (clearMailbox) clearSteamGameMailbox()
|
||||
}
|
||||
|
||||
private fun clearSteamGameMailbox() {
|
||||
val directory = LinuxRuntime.sessionRoot(this)
|
||||
File(directory, STEAM_GAME_REQUEST).delete()
|
||||
File(directory, STEAM_GAME_REQUEST + ".tmp").delete()
|
||||
}
|
||||
|
||||
/**
|
||||
* proot's --kill-on-exit takes its tracees down, but a session that died from the inside
|
||||
* (the client asserting, Xwayland going) leaves gamescopereaper and the session script
|
||||
@@ -938,9 +1033,26 @@ class SessionService : Service() {
|
||||
|
||||
private fun watchLaunchRequests(dir: File) {
|
||||
launchWatcher?.stopWatching()
|
||||
listOf("steam-sleep", "steam-sleep-state", "steam-sleep-ready").forEach { File(dir, it).delete() }
|
||||
val gen = sessionGen
|
||||
@Suppress("DEPRECATION")
|
||||
val watcher = object : android.os.FileObserver(dir.path, CLOSE_WRITE or MOVED_TO) {
|
||||
override fun onEvent(event: Int, path: String?) {
|
||||
if (path == "steam-sleep") {
|
||||
val request = File(dir, path)
|
||||
val token = runCatching { request.readText().trim() }.getOrNull() ?: return
|
||||
request.delete()
|
||||
if (!token.matches(Regex("[a-f0-9]{32}"))) return
|
||||
mainHandler.post {
|
||||
if (gen != sessionGen || !SessionState.running) return@post
|
||||
steamSleepToken = token
|
||||
writeSteamSleepState(token, "paused")
|
||||
suspendAttemptFailed = false
|
||||
Log.i(TAG, "Steam requested session sleep")
|
||||
updateSuspendPolicy()
|
||||
}
|
||||
return
|
||||
}
|
||||
if (path != "steam-launch") return
|
||||
val file = File(dir, path)
|
||||
val text = try { file.readText() } catch (e: Exception) { return }
|
||||
@@ -975,18 +1087,23 @@ class SessionService : Service() {
|
||||
if (suspendPolicy == SessionPrefs.SUSPEND_MANUAL && (!activityVisible || !screenOn)) {
|
||||
manualPauseRequested = true
|
||||
}
|
||||
val shouldSuspend = when (suspendPolicy) {
|
||||
val shouldSuspend = steamSleepToken != null || when (suspendPolicy) {
|
||||
SessionPrefs.SUSPEND_AUTO -> !activityVisible || !screenOn
|
||||
SessionPrefs.SUSPEND_MANUAL -> manualPauseRequested
|
||||
else -> false
|
||||
}
|
||||
val controller = suspendController ?: return
|
||||
if (suspendOperationPending || suspendAttemptFailed || shouldSuspend == SessionState.suspended) return
|
||||
val gen = sessionGen
|
||||
suspendOperationPending = true
|
||||
SessionEvents.record(if (shouldSuspend) "session.suspend_requested" else "session.resume_requested", mapOf(
|
||||
"policy" to suspendPolicy, "activityVisible" to activityVisible,
|
||||
"screenOn" to screenOn, "steamSleep" to (steamSleepToken != null),
|
||||
))
|
||||
if (shouldSuspend) {
|
||||
controller.freeze { success ->
|
||||
mainHandler.post {
|
||||
if (!SessionState.running) return@post
|
||||
if (gen != sessionGen || !SessionState.running) return@post
|
||||
suspendOperationPending = false
|
||||
if (success) {
|
||||
SessionState.suspended = true
|
||||
@@ -994,6 +1111,7 @@ class SessionService : Service() {
|
||||
releaseLocks()
|
||||
refreshNotification()
|
||||
} else {
|
||||
completeSteamSleep()
|
||||
suspendAttemptFailed = true
|
||||
Log.w(TAG, "could not confirm that the session stopped")
|
||||
}
|
||||
@@ -1004,7 +1122,7 @@ class SessionService : Service() {
|
||||
acquireLocks()
|
||||
controller.resume { success ->
|
||||
mainHandler.post {
|
||||
if (!SessionState.running) return@post
|
||||
if (gen != sessionGen || !SessionState.running) return@post
|
||||
suspendOperationPending = false
|
||||
if (success) {
|
||||
SessionState.suspended = false
|
||||
@@ -1020,6 +1138,27 @@ class SessionService : Service() {
|
||||
}
|
||||
}
|
||||
|
||||
private fun writeSteamSleepState(token: String, state: String) {
|
||||
val dir = LinuxRuntime.sessionRoot(this)
|
||||
runCatching {
|
||||
val staged = File(dir, "steam-sleep-state.tmp")
|
||||
staged.writeText("$token:$state\n")
|
||||
check(staged.renameTo(File(dir, "steam-sleep-state")))
|
||||
}.onFailure { Log.w(TAG, "could not acknowledge Steam sleep", it) }
|
||||
}
|
||||
|
||||
private fun completeSteamSleep() {
|
||||
val token = steamSleepToken ?: return
|
||||
// Write before SIGCONT: the guest's login1 sees it immediately on thaw
|
||||
// and delivers PrepareForSleep(false), restoring Steam's main surface.
|
||||
writeSteamSleepState(token, "awake")
|
||||
steamSleepToken = null
|
||||
}
|
||||
|
||||
private fun resumeSteamSleepOnReturn() {
|
||||
if (suspendPolicy == SessionPrefs.SUSPEND_AUTO && activityVisible && screenOn) completeSteamSleep()
|
||||
}
|
||||
|
||||
private fun finishSessionStop(status: Int, stoppedGen: Int) {
|
||||
mainHandler.post {
|
||||
if (stoppedGen != sessionGen || SessionState.running) {
|
||||
@@ -1027,6 +1166,8 @@ class SessionService : Service() {
|
||||
return@post
|
||||
}
|
||||
SessionState.suspended = false
|
||||
SessionState.pipActive = false
|
||||
pipTask = false
|
||||
SessionState.guestPid = -1
|
||||
releaseLocks()
|
||||
if (status == 0) {
|
||||
@@ -1069,6 +1210,7 @@ class SessionService : Service() {
|
||||
}
|
||||
|
||||
private fun stopSession(status: Int) {
|
||||
cancelQueuedSteamGame()
|
||||
synchronized(stopLock) {
|
||||
if (!SessionState.running) return
|
||||
SessionState.running = false
|
||||
@@ -1135,6 +1277,12 @@ class SessionService : Service() {
|
||||
* guest would survive as an orphan holding the rootfs and the GPU. Treat the swipe as "quit".
|
||||
*/
|
||||
override fun onTaskRemoved(rootIntent: Intent?) {
|
||||
if (pipTask) {
|
||||
Log.i(TAG, "PiP task dismissed - retaining the session under its background policy")
|
||||
activityVisible = false
|
||||
updateSuspendPolicy()
|
||||
return
|
||||
}
|
||||
Log.i(TAG, "task removed - ending the session")
|
||||
stopSession(0)
|
||||
super.onTaskRemoved(rootIntent)
|
||||
@@ -1275,6 +1423,8 @@ class SessionService : Service() {
|
||||
private const val NOTIFICATION_ID = 1001
|
||||
const val ACTION_STOP = "com.droiddeck.launcher.STOP_SESSION"
|
||||
const val ACTION_RESUME = "com.droiddeck.launcher.RESUME_SESSION"
|
||||
private const val ACTION_PIP_BEGIN = "com.droiddeck.launcher.PIP_BEGIN"
|
||||
const val ACTION_LAUNCH_GAME = "com.droiddeck.launcher.LAUNCH_STEAM_GAME"
|
||||
const val ACTION_HOME_GUIDE = "com.droiddeck.launcher.HOME_GUIDE"
|
||||
const val ACTION_AGENT_START = "com.droiddeck.launcher.AGENT_START"
|
||||
private const val ACTION_SUSPEND_POLICY_CHANGED = "com.droiddeck.launcher.SUSPEND_POLICY_CHANGED"
|
||||
@@ -1291,6 +1441,8 @@ class SessionService : Service() {
|
||||
private const val GRACE_MS = 1200L
|
||||
private const val STEAM_PICKUP_MS = 1500L
|
||||
private const val STEAM_EXIT_MS = 10_000L
|
||||
private const val GAME_LAUNCH_RETRY_MS = 250L
|
||||
private const val STEAM_GAME_REQUEST = "steam-game"
|
||||
private const val NO_PAD_SWITCH = "Download/droiddeck-no-pad"
|
||||
private const val NO_UINPUT_SWITCH = "Download/droiddeck-no-uinput"
|
||||
private const val NO_DECK_PAD_SWITCH = "Download/droiddeck-no-deck-pad"
|
||||
@@ -1309,6 +1461,7 @@ class SessionService : Service() {
|
||||
* MODE_DESKTOP: "desktop" = open Steam's desktop client in the desktop once it is up. */
|
||||
const val EXTRA_STEAM_UI = "steamUi"
|
||||
const val EXTRA_STEAM_URL = "steamUrl"
|
||||
const val EXTRA_GAME_ID = "gameId"
|
||||
|
||||
fun start(
|
||||
context: Context, mode: String = MODE_STEAM, program: String? = null,
|
||||
@@ -1331,6 +1484,10 @@ class SessionService : Service() {
|
||||
context.startService(Intent(context, SessionService::class.java).setAction(ACTION_STOP))
|
||||
}
|
||||
|
||||
fun beginPip(context: Context) {
|
||||
context.startService(Intent(context, SessionService::class.java).setAction(ACTION_PIP_BEGIN))
|
||||
}
|
||||
|
||||
fun setActivityVisible(context: Context, visible: Boolean) {
|
||||
if (!SessionState.running) return
|
||||
val action = if (visible) ACTION_ACTIVITY_VISIBLE else ACTION_ACTIVITY_HIDDEN
|
||||
@@ -1342,6 +1499,20 @@ class SessionService : Service() {
|
||||
context.startService(Intent(context, SessionService::class.java).setAction(ACTION_RESUME))
|
||||
}
|
||||
|
||||
/** Route a validated decimal Steam game id through the current guest session. */
|
||||
fun launchGame(context: Context, gameId: String): Boolean {
|
||||
if (!GameLaunchLink.validId(gameId) || !SessionState.running ||
|
||||
SessionState.mode != MODE_STEAM || SessionState.stopRequested) return false
|
||||
return runCatching {
|
||||
context.startService(
|
||||
Intent(context, SessionService::class.java)
|
||||
.setAction(ACTION_LAUNCH_GAME)
|
||||
.putExtra(EXTRA_GAME_ID, gameId),
|
||||
)
|
||||
true
|
||||
}.getOrDefault(false)
|
||||
}
|
||||
|
||||
fun suspendPolicyChanged(context: Context) {
|
||||
if (!SessionState.running) return
|
||||
context.startService(Intent(context, SessionService::class.java).setAction(ACTION_SUSPEND_POLICY_CHANGED))
|
||||
|
||||
@@ -47,6 +47,7 @@ object SessionState {
|
||||
@Volatile
|
||||
var running = false
|
||||
var suspended by mutableStateOf(false)
|
||||
@Volatile var pipActive = false
|
||||
/** MODE_RUN: the program inside the runtime the session was started for. */
|
||||
@Volatile
|
||||
var program: String? = null
|
||||
|
||||
@@ -1,194 +0,0 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.core.LogRedactor
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import java.io.File
|
||||
import java.io.RandomAccessFile
|
||||
import java.text.SimpleDateFormat
|
||||
import java.util.Date
|
||||
import java.util.Locale
|
||||
|
||||
/**
|
||||
* VAC diagnostics: what a session can show about whether a game ran VAC-secure, from the files
|
||||
* Valve's own software writes - nothing is inferred from our side of the launch.
|
||||
*
|
||||
* The verdict is the game's to give. A Source-engine game decides secure or insecure once, as it
|
||||
* starts, and says so only in its own console ("You are in insecure mode. You must restart before
|
||||
* you can connect to secure servers."). That console reaches a file only when the game runs with
|
||||
* -condebug, as console.log in the game's mod folder. With this on, the launch wrapper
|
||||
* (bannerlator-proton, bl_vacdiag) adds -condebug to Source titles and notes each launch; at the end
|
||||
* of the session this copies each console.log written during it into vac/, scrubbed, and writes
|
||||
* vac.txt: the game's own secure/insecure lines, any VAC lines in the client's logs, and which
|
||||
* client files are present.
|
||||
*
|
||||
* The SteamLite lesson applies: its "INSECURE - VAC may kick" warning was our own parser reading the
|
||||
* wrong log while the client was secure all along. So vac.txt quotes the lines it found and says
|
||||
* "inconclusive" when the game never reached a server, rather than guessing either way.
|
||||
*/
|
||||
object VacDiagnostics {
|
||||
private const val TAG = "VacDiagnostics"
|
||||
|
||||
/** In the guest's home; the launch wrapper checks for it. Holds the session's start, epoch seconds. */
|
||||
private const val MARKER = "root/.droiddeck-vac-diagnostics"
|
||||
|
||||
/** One line per game launch the wrapper saw: epoch, app id, -condebug added or not, the exe. */
|
||||
private const val LAUNCHES = "root/.droiddeck-vac-launches"
|
||||
|
||||
/** The console log grows across launches; the end of it is the session that just ran. */
|
||||
private const val CONSOLE_TAIL_BYTES = 4L * 1024 * 1024
|
||||
|
||||
private const val MAX_QUOTED = 40
|
||||
|
||||
private val INSECURE = Regex("insecure mode", RegexOption.IGNORE_CASE)
|
||||
// "Connecting to" is only an attempt: L4D2 logs it, retries, and then refuses a VAC server with a
|
||||
// dialog ("Connection Blocked: Please remove plug-ins before attempting to connect to a VAC
|
||||
// secured server") that never reaches the console. Only "Connected to" means the game got in.
|
||||
private val CONNECTED = Regex("^Connected to", RegexOption.IGNORE_CASE)
|
||||
private val ATTEMPTED = Regex("^Connecting to", RegexOption.IGNORE_CASE)
|
||||
private val NOTABLE = Regex("\\bVAC\\b|secure|Connected to|Connecting to|Disconnect|challenge|game coordinator", RegexOption.IGNORE_CASE)
|
||||
private val STEAM_VAC = Regex("\\bVAC\\b|anti-?cheat", RegexOption.IGNORE_CASE)
|
||||
|
||||
fun enabled(context: Context): Boolean = SessionPrefs.vacDiagnostics(context)
|
||||
|
||||
/**
|
||||
* At session start, after the scripts are staged: arms the wrapper for this session (or disarms
|
||||
* it) and starts a fresh launch list, so the summary names only games this session ran.
|
||||
*/
|
||||
fun arm(context: Context) {
|
||||
val root = LinuxRuntime.rootDir(context)
|
||||
val marker = File(root, MARKER)
|
||||
try {
|
||||
File(root, LAUNCHES).delete()
|
||||
if (enabled(context)) marker.writeText("${System.currentTimeMillis() / 1000}\n")
|
||||
else marker.delete()
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "could not arm VAC diagnostics", e)
|
||||
}
|
||||
}
|
||||
|
||||
/** At the end of a session, into its folder. Does nothing unless the session was armed. */
|
||||
fun collect(context: Context, dir: File) {
|
||||
val root = LinuxRuntime.rootDir(context)
|
||||
val marker = File(root, MARKER)
|
||||
if (!marker.isFile) return
|
||||
try {
|
||||
val since = (marker.readText().trim().toLongOrNull() ?: 0L) * 1000 - 5_000
|
||||
val out = File(dir, "vac").apply { mkdirs() }
|
||||
val consoles = consoleLogs(context).filter { it.lastModified() >= since }
|
||||
val report = StringBuilder()
|
||||
report.appendLine("VAC diagnostics - ${now()}")
|
||||
report.appendLine("Read from the game's own console (-condebug) and the Steam client's logs.")
|
||||
report.appendLine()
|
||||
report.appendLine("== Client")
|
||||
clientFiles(root).forEach { report.appendLine(" $it") }
|
||||
report.appendLine()
|
||||
report.appendLine("== Game launches this session (from the launch wrapper)")
|
||||
val launches = File(root, LAUNCHES).takeIf { it.isFile }?.readLines().orEmpty().filter { it.isNotBlank() }
|
||||
if (launches.isEmpty()) report.appendLine(" none - no Windows game was launched through the client")
|
||||
launches.forEach { report.appendLine(" " + LogRedactor.redact(it)) }
|
||||
report.appendLine()
|
||||
report.appendLine("== Game consoles")
|
||||
if (consoles.isEmpty()) {
|
||||
report.appendLine(" No console.log was written this session. Only Source-engine games write one,")
|
||||
report.appendLine(" and only when started with -condebug (this setting adds it).")
|
||||
}
|
||||
consoles.forEach { log ->
|
||||
val name = consoleName(log)
|
||||
val lines = tail(log)
|
||||
File(out, "$name-console.log").bufferedWriter().use { w ->
|
||||
lines.forEach { w.write(LogRedactor.redact(it)); w.newLine() }
|
||||
}
|
||||
report.appendLine("-- $name (vac/$name-console.log)")
|
||||
report.appendLine(" Verdict: " + verdict(lines))
|
||||
lines.filter { NOTABLE.containsMatchIn(it) }.takeLast(MAX_QUOTED)
|
||||
.forEach { report.appendLine(" | " + LogRedactor.redact(it.trim())) }
|
||||
report.appendLine()
|
||||
}
|
||||
report.appendLine("== VAC in the Steam client's logs")
|
||||
val steamHits = File(dir, "steam").listFiles { f -> f.isFile }?.sortedBy { it.name }.orEmpty()
|
||||
.flatMap { f -> runCatching { f.readLines() }.getOrDefault(emptyList()).filter { STEAM_VAC.containsMatchIn(it) }.map { "${f.name}: ${it.trim()}" } }
|
||||
if (steamHits.isEmpty()) report.appendLine(" none - the client logged no VAC activity this session")
|
||||
steamHits.takeLast(MAX_QUOTED).forEach { report.appendLine(" $it") }
|
||||
File(dir, "vac.txt").writeText(report.toString())
|
||||
Log.i(TAG, "VAC diagnostics: ${consoles.size} console log(s), ${steamHits.size} client VAC line(s), into $dir")
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "collecting VAC diagnostics", e)
|
||||
}
|
||||
}
|
||||
|
||||
private fun verdict(lines: List<String>): String = when {
|
||||
lines.any { INSECURE.containsMatchIn(it) } ->
|
||||
"INSECURE - the game started in insecure mode and cannot join VAC-secured servers until it restarts."
|
||||
lines.any { CONNECTED.containsMatchIn(it) } ->
|
||||
"No insecure notice, and the game connected to a server. Confirm with the server's own info that it is VAC-secured."
|
||||
lines.any { ATTEMPTED.containsMatchIn(it) } ->
|
||||
"NOT CONNECTED - the game tried a server and never got in. If the screen said \"Connection Blocked: " +
|
||||
"Please remove plug-ins ... VAC secured server\" (Left 4 Dead 2's wording), the game is insecure; " +
|
||||
"that dialog never reaches the console."
|
||||
else ->
|
||||
"Inconclusive - the game never connected to a server. Join a VAC-secured server, then check again."
|
||||
}
|
||||
|
||||
/** Every console.log in a Steam library: <game>/<mod>/console.log (Source) and <game>/game/<mod>/console.log (Source 2). */
|
||||
private fun consoleLogs(context: Context): List<File> {
|
||||
val found = LinkedHashMap<String, File>()
|
||||
for (library in libraryRoots(context)) {
|
||||
val games = File(library, "steamapps/common").listFiles { f -> f.isDirectory } ?: continue
|
||||
for (game in games) {
|
||||
val mods = (game.listFiles { f -> f.isDirectory }.orEmpty().toList() +
|
||||
File(game, "game").listFiles { f -> f.isDirectory }.orEmpty().toList())
|
||||
for (mod in mods) {
|
||||
val log = File(mod, "console.log")
|
||||
if (log.isFile) found[runCatching { log.canonicalPath }.getOrDefault(log.path)] = log
|
||||
}
|
||||
}
|
||||
}
|
||||
return found.values.toList()
|
||||
}
|
||||
|
||||
private fun libraryRoots(context: Context): List<File> {
|
||||
val root = LinuxRuntime.rootDir(context)
|
||||
val steam = File(root, "root/.local/share/Steam")
|
||||
val roots = mutableListOf(steam)
|
||||
GameStorage.effective(context)?.let { roots.add(File(it.path)) }
|
||||
runCatching {
|
||||
Regex("\"path\"\\s+\"([^\"]+)\"").findAll(File(steam, "steamapps/libraryfolders.vdf").readText()).forEach {
|
||||
roots.add(File(root, it.groupValues[1].removePrefix("/")))
|
||||
}
|
||||
}
|
||||
return roots.filter { it.isDirectory }.distinctBy { runCatching { it.canonicalPath }.getOrDefault(it.path) }
|
||||
}
|
||||
|
||||
/** "Team Fortress 2-tf": the game folder and the mod, safe as a file name. */
|
||||
private fun consoleName(log: File): String {
|
||||
val mod = log.parentFile
|
||||
val game = mod?.parentFile?.let { if (it.name == "game") it.parentFile else it }
|
||||
return "${game?.name ?: "game"}-${mod?.name ?: "mod"}".replace(Regex("[^A-Za-z0-9._ +-]+"), "_")
|
||||
}
|
||||
|
||||
private fun tail(file: File): List<String> = try {
|
||||
RandomAccessFile(file, "r").use { raf ->
|
||||
val start = (raf.length() - CONSOLE_TAIL_BYTES).coerceAtLeast(0)
|
||||
raf.seek(start)
|
||||
val bytes = ByteArray((raf.length() - start).toInt())
|
||||
raf.readFully(bytes)
|
||||
String(bytes, Charsets.UTF_8).lines().let { if (start > 0) it.drop(1) else it }
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
emptyList()
|
||||
}
|
||||
|
||||
/** Which Steam client builds are on disk - the arm64 one has no VAC module of its own to run. */
|
||||
private fun clientFiles(root: File): List<String> {
|
||||
val steam = File(root, "root/.local/share/Steam")
|
||||
return listOf(
|
||||
"linuxarm64/steamclient.so" to "arm64 Linux client",
|
||||
"linux64/steamclient.so" to "x86-64 Linux client",
|
||||
"ubuntu12_64/steamclient.so" to "x86-64 Linux client (ubuntu12_64)",
|
||||
).map { (path, label) -> "$label: ${if (File(steam, path).isFile) "present" else "absent"} ($path)" }
|
||||
}
|
||||
|
||||
private fun now(): String = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US).format(Date())
|
||||
}
|
||||
@@ -69,8 +69,8 @@ internal fun GamesPage(s: FrontEndState, a: FrontEndActions, selected: String, o
|
||||
if (current == null) {
|
||||
Column(modifier = modifier.padding(horizontal = if (narrow) 16.dp else 22.dp, vertical = if (narrow) 12.dp else 18.dp)) {
|
||||
Rise(0) { PageHeader(stringResource(R.string.content_games)) }
|
||||
Rise(1) { Note(stringResource(R.string.games_empty)) }
|
||||
Rise(2) {
|
||||
Rise(1) { Note(stringResource(if (s.shortcutPicker && s.shortcutLibraryScanning) R.string.game_shortcut_scanning else R.string.games_empty)) }
|
||||
if (!s.shortcutPicker) Rise(2) {
|
||||
Actions { PrimaryButton(stringResource(R.string.games_play_steam), enabled = !s.busy, main = true, icon = Icons.Filled.PlayArrow, modifier = Modifier.padding(top = 12.dp), onClick = a.onPlay) }
|
||||
}
|
||||
}
|
||||
@@ -116,7 +116,7 @@ internal fun GamesPage(s: FrontEndState, a: FrontEndActions, selected: String, o
|
||||
@Composable
|
||||
private fun GameActions(g: Library.SteamGame, s: FrontEndState, a: FrontEndActions) {
|
||||
Actions {
|
||||
PrimaryButton(stringResource(R.string.games_launch), enabled = !s.busy, main = true, icon = Icons.Filled.PlayArrow) { a.onSteamGame(g) }
|
||||
PrimaryButton(stringResource(if (s.shortcutPicker) R.string.game_shortcut_choose else R.string.games_launch), enabled = !s.busy, main = true, icon = Icons.Filled.PlayArrow) { a.onSteamGame(g) }
|
||||
g.gameFiles?.takeIf { it.isDirectory }?.let { dir ->
|
||||
SecondaryButton(stringResource(R.string.games_files), compact = true) { a.onBrowseFiles(dir) }
|
||||
}
|
||||
@@ -125,10 +125,27 @@ private fun GameActions(g: Library.SteamGame, s: FrontEndState, a: FrontEndActio
|
||||
// Only games added to the library; Steam titles keep their saves with Steam Cloud.
|
||||
if (g.library == Library.ADDED) ManageSaves(g, dir, a)
|
||||
}
|
||||
if (!s.shortcutPicker) GameShortcutMenu(g, a)
|
||||
BusyChip(s)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun GameShortcutMenu(g: Library.SteamGame, a: FrontEndActions) {
|
||||
var open by remember(g.gameId) { androidx.compose.runtime.mutableStateOf(false) }
|
||||
Box {
|
||||
SecondaryButton(stringResource(R.string.game_shortcut), compact = true) { open = !open }
|
||||
AnchoredMenu(open, onDismiss = { open = false }, title = stringResource(R.string.game_shortcut)) { first ->
|
||||
MenuItem(stringResource(R.string.game_shortcut_add), checked = false, focusRequester = first) {
|
||||
open = false; a.onGameShortcut(g)
|
||||
}
|
||||
MenuItem(stringResource(R.string.game_link_copy), checked = false) {
|
||||
open = false; a.onCopyGameLink(g)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Manage saves: import a GameHub or Winlator save zip into this game's prefix, export its saves as
|
||||
* either, or open the save folder found for it. The saves are looked for when the menu opens.
|
||||
|
||||
@@ -91,12 +91,13 @@ class FrontEndState(
|
||||
val frameGenLabel: String,
|
||||
val romsDir: String?,
|
||||
val logsEnabled: Boolean,
|
||||
val vacDiagnostics: Boolean = false,
|
||||
val steamGames: List<Library.SteamGame>,
|
||||
val emulators: List<Library.Emulator>,
|
||||
val running: String?,
|
||||
val frameGen: FrameGen.Mode = FrameGen.Mode.OFF,
|
||||
val lossless: Lossless.State = Lossless.State.NONE,
|
||||
val shortcutPicker: Boolean = false,
|
||||
val shortcutLibraryScanning: Boolean = false,
|
||||
val pageKey: String? = null,
|
||||
val theme: String = Themes.GRAPHITE,
|
||||
val isHomeApp: Boolean = false,
|
||||
@@ -127,6 +128,8 @@ class FrontEndActions(
|
||||
val onPlay: () -> Unit,
|
||||
val onPlayDesktopUi: () -> Unit,
|
||||
val onSteamGame: (Library.SteamGame) -> Unit,
|
||||
val onGameShortcut: (Library.SteamGame) -> Unit = {},
|
||||
val onCopyGameLink: (Library.SteamGame) -> Unit = {},
|
||||
val onDesktop: () -> Unit,
|
||||
val onEmulator: (Library.Emulator) -> Unit,
|
||||
/** A Flatpak app by id and name, from the Store. */
|
||||
@@ -153,7 +156,6 @@ class FrontEndActions(
|
||||
val onFiles: () -> Unit,
|
||||
val onBrowseFiles: (File) -> Unit = {},
|
||||
val onLogs: () -> Unit,
|
||||
val onVacDiagnostics: () -> Unit = {},
|
||||
val onShareLogs: () -> Unit = {},
|
||||
val onClearLogs: () -> Unit = {},
|
||||
val onOffline: () -> Unit,
|
||||
@@ -333,7 +335,8 @@ fun FrontEndScreen(s: FrontEndState, a: FrontEndActions, page: (@Composable () -
|
||||
@OptIn(ExperimentalComposeUiApi::class)
|
||||
@Composable
|
||||
private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Composable () -> Unit)?, frontFocus: FrontFocus) {
|
||||
var selected by rememberSaveable { mutableStateOf("steam") }
|
||||
var selected by rememberSaveable { mutableStateOf(if (s.shortcutPicker) "games" else "steam") }
|
||||
LaunchedEffect(s.shortcutPicker) { if (s.shortcutPicker) selected = "games" }
|
||||
var showWirelessAdbFix by rememberSaveable { mutableStateOf(false) }
|
||||
var showDeveloperDisplayChoice by rememberSaveable { mutableStateOf(false) }
|
||||
var wirelessAdbDesiredEnabled by rememberSaveable { mutableStateOf(false) }
|
||||
|
||||
@@ -289,7 +289,6 @@ internal fun SetupPanel(
|
||||
}
|
||||
}
|
||||
ToggleRow(host, "logs", stringResource(R.string.setup_logs), stringResource(R.string.setup_logs_hint), s.logsEnabled) { a.onLogs() }
|
||||
ToggleRow(host, "vacdiag", stringResource(R.string.setup_vac_diag), stringResource(R.string.setup_vac_diag_hint), s.vacDiagnostics) { a.onVacDiagnostics() }
|
||||
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_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(
|
||||
|
||||
@@ -54,8 +54,12 @@ class ModeSettings(
|
||||
val gpuDrivers: String = "Auto",
|
||||
/** Frames per second the session is capped at; 0 = none. */
|
||||
val fpsLimit: Int = 0,
|
||||
val upscaler: Int = 0,
|
||||
val upscaleSharpness: Int = 75,
|
||||
val touchMode: String,
|
||||
val suspendPolicy: String,
|
||||
val pipSupported: Boolean = false,
|
||||
val pipAutoEnter: Boolean = false,
|
||||
/** Steam only. */
|
||||
val oscMode: String?,
|
||||
/** Steam only: whether single and double Back actions are swapped. */
|
||||
@@ -80,6 +84,12 @@ class ModeSettings(
|
||||
val steamController: String? = null,
|
||||
/** Steam only: start a Steam session when DroidDeck opens. */
|
||||
val runSteamAtStartup: Boolean = false,
|
||||
/** Null outside Steam; the saved choice is separate from Android's access and device switch. */
|
||||
val wifiDiscovery: Boolean? = null,
|
||||
val wifiDiscoveryPermission: Boolean = false,
|
||||
val wifiDiscoveryLocation: Boolean = false,
|
||||
val wifiDiscoveryAsked: Boolean = false,
|
||||
val wifiDiscoveryBlocked: Boolean = false,
|
||||
/** Steam only: the user's chosen Games folders; null outside Steam. */
|
||||
val addedGamesDirs: List<String>? = null,
|
||||
val addedGames: List<AddedGameRow> = emptyList(),
|
||||
@@ -107,8 +117,11 @@ class ModeSettingsActions(
|
||||
/** Opens the GPU drivers on the Components page: they are shared by every session. */
|
||||
val onGpuDrivers: () -> Unit = {},
|
||||
val onFpsLimit: (Int) -> Unit = {},
|
||||
val onUpscaler: (Int) -> Unit = {},
|
||||
val onUpscaleSharpness: (Int) -> Unit = {},
|
||||
val onTouch: (String) -> Unit,
|
||||
val onSuspendPolicy: (String) -> Unit,
|
||||
val onPipAutoEnter: (Boolean) -> Unit = {},
|
||||
val onOsc: (String) -> Unit,
|
||||
val onBackActionsInverted: (Boolean) -> Unit = {},
|
||||
val onDirectAudio: (Boolean) -> Unit,
|
||||
@@ -125,6 +138,8 @@ class ModeSettingsActions(
|
||||
val onMangoapp: (Boolean) -> Unit = {},
|
||||
val onSteamController: (String) -> Unit = {},
|
||||
val onRunSteamAtStartup: (Boolean) -> Unit = {},
|
||||
val onWifiDiscovery: (Boolean) -> Unit = {},
|
||||
val onWifiDiscoverySettings: () -> Unit = {},
|
||||
val onPickAddedGamesDir: () -> Unit = {},
|
||||
val onForgetAddedGamesDir: (path: String) -> Unit = {},
|
||||
val onAddedGamesArt: (Boolean) -> Unit = {},
|
||||
@@ -142,6 +157,7 @@ fun ModeSettingsPage(s: ModeSettings, a: ModeSettingsActions) {
|
||||
val steam = s.mode == SessionService.MODE_STEAM
|
||||
val host = rememberMenuHost()
|
||||
var confirmDeckyRemoval by remember { mutableStateOf(false) }
|
||||
var explainWifiDiscovery by remember { mutableStateOf(false) }
|
||||
val pageScroll = androidx.compose.foundation.rememberScrollState()
|
||||
val firstChip = remember { androidx.compose.ui.focus.FocusRequester() }
|
||||
androidx.compose.runtime.LaunchedEffect(Unit) {
|
||||
@@ -180,6 +196,17 @@ fun ModeSettingsPage(s: ModeSettings, a: ModeSettingsActions) {
|
||||
note = stringResource(R.string.mode_fps_note),
|
||||
onPick = a.onFpsLimit,
|
||||
)
|
||||
ChoiceRow(
|
||||
host, "upscaler", "Upscaler", "Sharpens the picture where it is enlarged to the screen.",
|
||||
com.droiddeck.launcher.session.SessionPrefs.upscalerChoices, s.upscaler,
|
||||
note = "Works only when the session is smaller than the screen; Sharpen only works at any size. Costs a little GPU time.",
|
||||
onPick = a.onUpscaler,
|
||||
)
|
||||
ChoiceRow(
|
||||
host, "upscale-sharpness", "Upscaler sharpness", null,
|
||||
com.droiddeck.launcher.session.SessionPrefs.upscaleSharpnessChoices, s.upscaleSharpness,
|
||||
enabled = s.upscaler != 0, onPick = a.onUpscaleSharpness,
|
||||
)
|
||||
if (editCustom) CustomResolutionDialog(
|
||||
initial = custom,
|
||||
onSave = { size -> editCustom = false; a.onCustomResolution(size) },
|
||||
@@ -247,6 +274,10 @@ fun ModeSettingsPage(s: ModeSettings, a: ModeSettingsActions) {
|
||||
onPick = a.onSuspendPolicy,
|
||||
)
|
||||
}
|
||||
if (s.pipSupported) SettingsGroup(stringResource(R.string.pip_title)) {
|
||||
ToggleRow(host, "pip-auto", stringResource(R.string.pip_auto), null,
|
||||
s.pipAutoEnter, onChange = a.onPipAutoEnter)
|
||||
}
|
||||
if (steam) SettingsGroup(stringResource(R.string.mode_startup)) {
|
||||
ToggleRow(
|
||||
host, "steam-startup", stringResource(R.string.mode_steam_startup),
|
||||
@@ -326,6 +357,25 @@ fun ModeSettingsPage(s: ModeSettings, a: ModeSettingsActions) {
|
||||
onPick = a.onSteamChannel,
|
||||
)
|
||||
}
|
||||
if (steam && s.wifiDiscovery != null) SettingsGroup(stringResource(R.string.mode_network)) {
|
||||
val hint = when {
|
||||
s.wifiDiscovery && !s.wifiDiscoveryLocation -> stringResource(R.string.mode_wifi_location_off)
|
||||
!s.wifiDiscoveryPermission && s.wifiDiscoveryAsked -> stringResource(R.string.mode_wifi_permission_denied)
|
||||
else -> stringResource(R.string.mode_wifi_discovery_hint)
|
||||
}
|
||||
SettingsRow(stringResource(R.string.mode_wifi_discovery), hint) {
|
||||
Row(verticalAlignment = androidx.compose.ui.Alignment.CenterVertically,
|
||||
horizontalArrangement = androidx.compose.foundation.layout.Arrangement.spacedBy(8.dp)) {
|
||||
if (s.wifiDiscoveryBlocked || (s.wifiDiscovery && !s.wifiDiscoveryLocation)) {
|
||||
SecondaryButton(stringResource(R.string.mode_wifi_open_settings), onClick = a.onWifiDiscoverySettings)
|
||||
}
|
||||
ToggleSwitch(s.wifiDiscovery, label = stringResource(R.string.mode_wifi_discovery)) { on ->
|
||||
host.open = null
|
||||
if (on) explainWifiDiscovery = true else a.onWifiDiscovery(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (steam && s.addedGamesDirs != null) SettingsGroup(stringResource(R.string.mode_added_games)) {
|
||||
for (dir in s.addedGamesDirs) {
|
||||
val n = s.addedGames.count { it.folderPath.startsWith("$dir/") }
|
||||
@@ -418,6 +468,19 @@ fun ModeSettingsPage(s: ModeSettings, a: ModeSettingsActions) {
|
||||
)
|
||||
}
|
||||
}
|
||||
if (explainWifiDiscovery) AlertDialog(
|
||||
onDismissRequest = { explainWifiDiscovery = false },
|
||||
title = { Text(stringResource(R.string.mode_wifi_explain_title)) },
|
||||
text = { Text(stringResource(R.string.mode_wifi_explain_text)) },
|
||||
confirmButton = {
|
||||
TextButton(onClick = { explainWifiDiscovery = false; a.onWifiDiscovery(true) }) {
|
||||
Text(stringResource(if (s.wifiDiscoveryBlocked) R.string.mode_wifi_open_settings else R.string.mode_wifi_continue))
|
||||
}
|
||||
},
|
||||
dismissButton = {
|
||||
TextButton(onClick = { explainWifiDiscovery = false }) { Text(stringResource(R.string.common_cancel)) }
|
||||
},
|
||||
)
|
||||
if (confirmDeckyRemoval) AlertDialog(
|
||||
onDismissRequest = { confirmDeckyRemoval = false },
|
||||
title = { Text(stringResource(R.string.mode_decky_remove_title)) },
|
||||
|
||||
@@ -100,7 +100,10 @@ class SecondScreenPresentation(
|
||||
|
||||
override fun onWindowFocusChanged(hasFocus: Boolean) {
|
||||
super.onWindowFocusChanged(hasFocus)
|
||||
if (hasFocus) applyImmersiveMode()
|
||||
if (hasFocus) {
|
||||
applyImmersiveMode()
|
||||
sessionActivity.refreshClipboard()
|
||||
}
|
||||
}
|
||||
|
||||
private fun renderMode() {
|
||||
|
||||
@@ -171,6 +171,8 @@ class DrawerActions(
|
||||
val fexPreset: String,
|
||||
/** Steam only: games stretched to the screen's size, changed live (null = not Steam). */
|
||||
val fillScreen: Boolean? = null,
|
||||
val upscaler: Int = 0,
|
||||
val upscaleSharpness: Int = 75,
|
||||
val secondScreenMode: SecondScreenMode,
|
||||
val secondScreenDisplays: List<SecondScreenDisplay>,
|
||||
val selectedSecondScreenDisplay: Int,
|
||||
@@ -192,10 +194,16 @@ class DrawerActions(
|
||||
val onShape: (String) -> Unit,
|
||||
val onFexPreset: (String) -> Unit,
|
||||
val onFillScreen: (Boolean) -> Unit = {},
|
||||
val onUpscaler: (Int) -> Unit = {},
|
||||
val onUpscaleSharpness: (Int) -> Unit = {},
|
||||
val onSecondScreenMode: (SecondScreenMode) -> Unit,
|
||||
val onSecondScreenDisplay: (Int) -> Unit,
|
||||
val onLaunchAndroidApp: (HomeApp.LaunchableApp, Int?) -> Unit,
|
||||
val onBackground: () -> Unit,
|
||||
val pipSupported: Boolean = false,
|
||||
val pipAutoEnter: Boolean = false,
|
||||
val onPip: () -> Unit = {},
|
||||
val onPipAutoEnter: (Boolean) -> Unit = {},
|
||||
val onShareLogs: () -> Unit,
|
||||
val onStop: () -> Unit,
|
||||
/** Stop with the dialog's button's bounds on screen, for the flood to grow out of; null falls back to [onStop]. */
|
||||
@@ -355,6 +363,12 @@ fun SessionDrawer(open: Boolean, page: Int, controllerActive: Boolean, onPageCha
|
||||
host, "fill", stringResource(R.string.drawer_fill), null, a.fillScreen,
|
||||
chipModifier = focus.track(page, "fill"), onChange = a.onFillScreen,
|
||||
)
|
||||
ChoiceRow(host, "upscaler", "Upscaler", null,
|
||||
SessionPrefs.upscalerChoices, a.upscaler,
|
||||
chipModifier = focus.track(page, "upscaler"), onPick = a.onUpscaler)
|
||||
ChoiceRow(host, "upscale-sharpness", "Upscaler sharpness", null,
|
||||
SessionPrefs.upscaleSharpnessChoices, a.upscaleSharpness, enabled = a.upscaler != 0,
|
||||
chipModifier = focus.track(page, "upscale-sharpness"), onPick = a.onUpscaleSharpness)
|
||||
val fgOpen = host.open == "fg"
|
||||
val fgLabel = FrameGen.label(LocalContext.current, a.frameGen)
|
||||
SettingsRow(stringResource(R.string.frame_gen_title), null, highlighted = fgOpen) {
|
||||
@@ -462,7 +476,14 @@ fun SessionDrawer(open: Boolean, page: Int, controllerActive: Boolean, onPageCha
|
||||
}
|
||||
}
|
||||
}
|
||||
if (a.pipSupported) SettingsGroup(stringResource(R.string.pip_title)) {
|
||||
ToggleRow(host, "pip-auto", stringResource(R.string.pip_auto), null,
|
||||
a.pipAutoEnter, onChange = a.onPipAutoEnter)
|
||||
}
|
||||
Spacer(Modifier.height(18.dp))
|
||||
if (a.pipSupported) DrawerOutlineButton(stringResource(R.string.pip_title), modifier = focus.track(page, "pip")) {
|
||||
host.open = null; a.onPip()
|
||||
}
|
||||
if (!a.isHomeApp) DrawerOutlineButton(stringResource(R.string.drawer_background), modifier = focus.track(page, "background")) {
|
||||
host.open = null; a.onBackground()
|
||||
}
|
||||
|
||||
@@ -202,6 +202,9 @@ private fun StatusPanel(s: FrontEndState, u: UpdatesState, ua: UpdatesActions, m
|
||||
if (s.sessionRunning && (offered || offer == Offer.AHEAD)) {
|
||||
Text(stringResource(R.string.upd_stop_session), fontSize = 12.5.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(top = 8.dp))
|
||||
}
|
||||
if (u.follow.channel == Channel.NIGHTLY) {
|
||||
PreviewHistory(catalog, me)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -286,6 +289,63 @@ private fun ChannelPicker(u: UpdatesState, ua: UpdatesActions) {
|
||||
}
|
||||
}
|
||||
|
||||
/** Read-only Preview history below the status card action; only the latest build is installable. */
|
||||
@Composable
|
||||
private fun PreviewHistory(catalog: AppUpdates.Catalog?, me: AppUpdates.Installed) {
|
||||
val history = catalog?.let { AppUpdates.previewHistory(it, me) } ?: return
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val key = catalog?.recentPreviews?.firstOrNull()?.commit
|
||||
var expanded by rememberSaveable(key) { mutableStateOf(false) }
|
||||
val heading = when (history.kind) {
|
||||
AppUpdates.PreviewHistoryKind.CURRENT -> stringResource(R.string.upd_preview_current)
|
||||
AppUpdates.PreviewHistoryKind.BEHIND -> pluralStringResource(
|
||||
R.plurals.upd_preview_behind, history.buildsBehind, history.buildsBehind,
|
||||
)
|
||||
AppUpdates.PreviewHistoryKind.RECENT -> pluralStringResource(
|
||||
R.plurals.upd_preview_recent, history.changes.size, history.changes.size,
|
||||
)
|
||||
}
|
||||
Column(Modifier.fillMaxWidth().padding(top = 18.dp)) {
|
||||
Text(heading, fontSize = 11.5.sp, fontWeight = FontWeight.Medium, color = colors.onSurfaceVariant)
|
||||
if (history.changes.isNotEmpty()) {
|
||||
val visible = if (expanded) history.changes else history.changes.take(3)
|
||||
Column(Modifier.padding(top = 3.dp), verticalArrangement = Arrangement.spacedBy(3.dp)) {
|
||||
visible.forEach { change ->
|
||||
Column {
|
||||
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
Text(
|
||||
changeTitle(change.title.ifBlank { change.commit.take(7) }),
|
||||
fontSize = 12.5.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground,
|
||||
maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f),
|
||||
)
|
||||
Text(ago(change.publishedAt), fontSize = 11.sp, color = colors.onSurfaceVariant)
|
||||
}
|
||||
if (change.summary.isNotBlank()) Text(
|
||||
change.summary, fontSize = 11.5.sp, color = colors.onSurfaceVariant,
|
||||
maxLines = 1, overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
if (history.changes.size > 3 || expanded) {
|
||||
val src = remember { MutableInteractionSource() }
|
||||
val hot = rememberHot(src)
|
||||
val toggle = { expanded = !expanded }
|
||||
Text(
|
||||
if (expanded) stringResource(R.string.upd_less) else stringResource(R.string.upd_more),
|
||||
fontSize = 12.sp, fontWeight = FontWeight.SemiBold, color = pal.signal,
|
||||
modifier = Modifier.padding(top = 1.dp).offset(x = (-6).dp).paneItem("preview:history:more")
|
||||
.clip(Shape12).glideBorder(hot, Shape12, pal.signal)
|
||||
.hoverable(src).clickable(interactionSource = src, indication = null, role = Role.Button, onClick = toggle)
|
||||
.controllerConfirm(onClick = toggle)
|
||||
.padding(horizontal = 6.dp, vertical = 4.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ChannelCard(
|
||||
icon: ImageVector, title: String, hint: String, latest: String?, selected: Boolean,
|
||||
|
||||
@@ -54,11 +54,19 @@ object AppUpdates {
|
||||
val apk: Apk?,
|
||||
)
|
||||
|
||||
class PreviewChange(
|
||||
val commit: String,
|
||||
val title: String,
|
||||
val summary: String,
|
||||
val publishedAt: Long,
|
||||
)
|
||||
|
||||
class Catalog(
|
||||
val stable: Release?,
|
||||
val preview: Release?,
|
||||
val tests: List<Release>,
|
||||
val checkedAt: Long,
|
||||
val recentPreviews: List<PreviewChange> = emptyList(),
|
||||
)
|
||||
|
||||
class Installed(
|
||||
@@ -68,6 +76,15 @@ object AppUpdates {
|
||||
val versionCode: Int,
|
||||
val updatable: Boolean,
|
||||
val committedAt: Long = 0L,
|
||||
val ciBuild: Boolean = BuildConfig.CI_BUILD,
|
||||
)
|
||||
|
||||
enum class PreviewHistoryKind { CURRENT, BEHIND, RECENT }
|
||||
|
||||
class PreviewHistory(
|
||||
val kind: PreviewHistoryKind,
|
||||
val buildsBehind: Int,
|
||||
val changes: List<PreviewChange>,
|
||||
)
|
||||
|
||||
enum class Offer {
|
||||
@@ -146,6 +163,37 @@ object AppUpdates {
|
||||
r.commit.startsWith(me.commit, ignoreCase = true)
|
||||
}
|
||||
|
||||
/** Recent Preview changes relative to a CI-installed commit, when its position is known. */
|
||||
fun previewHistory(catalog: Catalog, me: Installed = installed()): PreviewHistory? {
|
||||
if (!me.ciBuild || catalog.recentPreviews.isEmpty()) return null
|
||||
val stable = catalog.stable
|
||||
if (
|
||||
me.pr != 0 || stable?.let { isRunning(it, me) } == true ||
|
||||
stable?.version?.let { compareVersions(me.version, it) <= 0 } == true
|
||||
) {
|
||||
return PreviewHistory(PreviewHistoryKind.RECENT, 0, catalog.recentPreviews)
|
||||
}
|
||||
|
||||
val matching = catalog.recentPreviews.indices.filter {
|
||||
matchesInstalledCommit(catalog.recentPreviews[it].commit, me.commit)
|
||||
}
|
||||
if (matching.size != 1) {
|
||||
return PreviewHistory(PreviewHistoryKind.RECENT, 0, catalog.recentPreviews)
|
||||
}
|
||||
val index = matching.single()
|
||||
return if (index == 0) {
|
||||
PreviewHistory(PreviewHistoryKind.CURRENT, 0, emptyList())
|
||||
} else {
|
||||
PreviewHistory(PreviewHistoryKind.BEHIND, index, catalog.recentPreviews.take(index))
|
||||
}
|
||||
}
|
||||
|
||||
private fun matchesInstalledCommit(published: String, installed: String): Boolean {
|
||||
if (!Regex("^[0-9a-fA-F]{7,40}$").matches(installed)) return false
|
||||
return published.equals(installed, ignoreCase = true) ||
|
||||
(installed.length < 40 && published.startsWith(installed, ignoreCase = true))
|
||||
}
|
||||
|
||||
/** Why Android cannot install this published build over [me], before downloading anything. */
|
||||
fun installBlock(r: Release, me: Installed = installed()): String? = when {
|
||||
r.apk == null -> "This build has no download for this copy of DroidDeck."
|
||||
@@ -218,6 +266,7 @@ object AppUpdates {
|
||||
)
|
||||
}
|
||||
val tests = root.optJSONArray("tests") ?: JSONArray()
|
||||
val recentPreviews = root.optJSONArray("recentPreviews") ?: JSONArray()
|
||||
return Catalog(
|
||||
root.optJSONObject("stable")?.let { readPublishedRelease(it, packageName) },
|
||||
root.optJSONObject("preview")?.let { readPublishedRelease(it, packageName) },
|
||||
@@ -226,9 +275,20 @@ object AppUpdates {
|
||||
.filter { it.pr > 0 }
|
||||
.sortedByDescending { it.publishedAt },
|
||||
checkedAt,
|
||||
(0 until recentPreviews.length())
|
||||
.mapNotNull { recentPreviews.optJSONObject(it)?.let(::readPublishedPreviewChange) }
|
||||
.sortedByDescending { it.publishedAt }
|
||||
.distinctBy { it.commit.lowercase() }
|
||||
.take(10),
|
||||
)
|
||||
}
|
||||
|
||||
private fun readPublishedPreviewChange(o: JSONObject): PreviewChange? {
|
||||
val commit = o.optString("commit")
|
||||
if (!Regex("^[0-9a-fA-F]{40}$").matches(commit)) return null
|
||||
return PreviewChange(commit.lowercase(), o.optString("title"), o.optString("summary"), o.optLong("publishedAt"))
|
||||
}
|
||||
|
||||
private fun readPublishedRelease(o: JSONObject, packageName: String): Release {
|
||||
val commit = o.getString("commit")
|
||||
if (!Regex("^[0-9a-fA-F]{7,40}$").matches(commit)) {
|
||||
@@ -358,23 +418,42 @@ object AppUpdates {
|
||||
},
|
||||
)
|
||||
|
||||
private fun writeCatalog(c: Catalog): JSONObject = JSONObject()
|
||||
internal fun writeCatalog(c: Catalog): JSONObject = JSONObject()
|
||||
.put("stable", c.stable?.let(::writeRelease))
|
||||
.put("preview", c.preview?.let(::writeRelease))
|
||||
.put("tests", JSONArray().apply { c.tests.forEach { put(writeRelease(it)) } })
|
||||
.put("recentPreviews", JSONArray().apply { c.recentPreviews.forEach { put(writePreviewChange(it)) } })
|
||||
.put("checkedAt", c.checkedAt)
|
||||
|
||||
private fun readCachedCatalog(o: JSONObject): Catalog {
|
||||
private fun writePreviewChange(c: PreviewChange): JSONObject = JSONObject()
|
||||
.put("commit", c.commit)
|
||||
.put("title", c.title)
|
||||
.put("summary", c.summary)
|
||||
.put("publishedAt", c.publishedAt)
|
||||
|
||||
internal fun readCachedCatalog(o: JSONObject): Catalog {
|
||||
val tests = o.optJSONArray("tests") ?: JSONArray()
|
||||
val preview = o.optJSONObject("preview") ?: o.optJSONObject("nightly")
|
||||
val recentPreviews = o.optJSONArray("recentPreviews") ?: JSONArray()
|
||||
return Catalog(
|
||||
o.optJSONObject("stable")?.let(::readCachedRelease),
|
||||
preview?.let(::readCachedRelease),
|
||||
(0 until tests.length()).map { readCachedRelease(tests.getJSONObject(it)) },
|
||||
o.optLong("checkedAt"),
|
||||
(0 until recentPreviews.length())
|
||||
.mapNotNull { recentPreviews.optJSONObject(it)?.let(::readCachedPreviewChange) }
|
||||
.sortedByDescending { it.publishedAt }
|
||||
.distinctBy { it.commit.lowercase() }
|
||||
.take(10),
|
||||
)
|
||||
}
|
||||
|
||||
private fun readCachedPreviewChange(o: JSONObject): PreviewChange? {
|
||||
val commit = o.optString("commit")
|
||||
if (!Regex("^[0-9a-fA-F]{40}$").matches(commit)) return null
|
||||
return PreviewChange(commit.lowercase(), o.optString("title"), o.optString("summary"), o.optLong("publishedAt"))
|
||||
}
|
||||
|
||||
private fun prefs(context: Context) =
|
||||
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
|
||||
}
|
||||
@@ -132,6 +132,13 @@ public final class WaylandCompositor {
|
||||
|
||||
public static void setClipboardListener(ClipboardListener l) { clipboardListener = l; }
|
||||
|
||||
public static boolean isClipboardListener(ClipboardListener l) { return clipboardListener == l; }
|
||||
|
||||
/** A replaced activity must not unhook the clipboard listener of its successor. */
|
||||
public static void clearClipboardListener(ClipboardListener l) {
|
||||
if (clipboardListener == l) clipboardListener = null;
|
||||
}
|
||||
|
||||
/** Invoked from native (banner_on_clipboard_text) with UTF-8 bytes. */
|
||||
@SuppressWarnings("unused")
|
||||
static void onClipboardText(byte[] utf8) {
|
||||
|
||||
@@ -483,8 +483,6 @@
|
||||
<string name="setup_session">Sesión</string>
|
||||
<string name="setup_logs">Registros de sesión</string>
|
||||
<string name="setup_logs_hint">Se guardan tras cada sesión</string>
|
||||
<string name="setup_vac_diag">Diagnóstico de VAC</string>
|
||||
<string name="setup_vac_diag_hint">Los juegos Source registran su consola (-condebug); vac.txt en los registros dice si es seguro o no</string>
|
||||
<string name="setup_latest_logs">Últimos registros de sesión</string>
|
||||
<string name="setup_saved_logs">Registros de sesión guardados</string>
|
||||
<string name="setup_saved_logs_hint">Conserva los %1$d más recientes</string>
|
||||
@@ -600,6 +598,7 @@
|
||||
<string name="upd_channel">CANAL DE ACTUALIZACIÓN</string>
|
||||
<string name="upd_stable_hint">Versiones probadas, para la mayoría</string>
|
||||
<string name="upd_preview_hint">Las correcciones más recientes, antes que Stable</string>
|
||||
<string name="upd_preview_current">Al día</string>
|
||||
<string name="upd_tests">Versiones de prueba</string>
|
||||
<string name="upd_tests_hint">Prueba una corrección antes de su publicación</string>
|
||||
<string name="upd_tests_none">Ninguna por ahora</string>
|
||||
@@ -612,6 +611,14 @@
|
||||
<item quantity="one">%1$d para probar</item>
|
||||
<item quantity="other">%1$d para probar</item>
|
||||
</plurals>
|
||||
<plurals name="upd_preview_behind">
|
||||
<item quantity="one">Cambios desde tu versión · %1$d versión atrás</item>
|
||||
<item quantity="other">Cambios desde tu versión · %1$d versiones atrás</item>
|
||||
</plurals>
|
||||
<plurals name="upd_preview_recent">
|
||||
<item quantity="one">Cambios recientes · %1$d versión</item>
|
||||
<item quantity="other">Cambios recientes · %1$d versiones</item>
|
||||
</plurals>
|
||||
<string name="gate_title">Un ajuste de Android por cambiar</string>
|
||||
<string name="gate_lede">Android detiene las apps que inician muchos procesos en segundo plano, y Steam inicia decenas. Hasta que esto cambie, los juegos se cierran sin mostrar ningún error.</string>
|
||||
<string name="gate_fix_for_me">Solucionarlo por mí</string>
|
||||
|
||||
@@ -292,6 +292,15 @@
|
||||
<string name="mode_client_audio_direct">DirectAudio</string>
|
||||
<string name="mode_mic">Microphone</string>
|
||||
<string name="mode_mic_hint">For voice chat.</string>
|
||||
<string name="mode_network">Network</string>
|
||||
<string name="mode_wifi_discovery">Wi-Fi discovery</string>
|
||||
<string name="mode_wifi_discovery_hint">Show Wi-Fi names and nearby networks in Steam.</string>
|
||||
<string name="mode_wifi_location_off">Location services are off.</string>
|
||||
<string name="mode_wifi_permission_denied">Location permission not granted.</string>
|
||||
<string name="mode_wifi_open_settings">Open settings</string>
|
||||
<string name="mode_wifi_continue">Continue</string>
|
||||
<string name="mode_wifi_explain_title">Enable Wi-Fi discovery?</string>
|
||||
<string name="mode_wifi_explain_text">Android requires Location permission to read Wi-Fi names and discover nearby networks. DroidDeck uses this access to show those networks in Steam. We don\'t track your location. Internet access works without this permission.</string>
|
||||
<string name="mode_storage">Game storage</string>
|
||||
<string name="mode_storage_auto">Automatic - the SD card when present</string>
|
||||
<string name="mode_storage_auto_none">Automatic - the SD card when present (none now)</string>
|
||||
@@ -508,8 +517,6 @@
|
||||
<string name="setup_session">Session</string>
|
||||
<string name="setup_logs">Session logs</string>
|
||||
<string name="setup_logs_hint">Saved after each session</string>
|
||||
<string name="setup_vac_diag">VAC diagnostics</string>
|
||||
<string name="setup_vac_diag_hint">Source games log their console (-condebug); vac.txt in the session logs says secure or insecure</string>
|
||||
<string name="setup_latest_logs">Latest session logs</string>
|
||||
<string name="setup_saved_logs">Saved session logs</string>
|
||||
<string name="setup_saved_logs_hint">Keeps the newest %1$d</string>
|
||||
@@ -640,6 +647,7 @@
|
||||
<string name="upd_version_ago">%1$s · %2$s</string>
|
||||
<string name="upd_preview">Preview</string>
|
||||
<string name="upd_preview_hint">Newest fixes, before Stable</string>
|
||||
<string name="upd_preview_current">Up to date</string>
|
||||
<string name="upd_tests">Test builds</string>
|
||||
<string name="upd_tests_hint">Try a fix before it\'s released</string>
|
||||
<string name="upd_tests_none">None right now</string>
|
||||
@@ -653,6 +661,14 @@
|
||||
<item quantity="one">%1$d to try</item>
|
||||
<item quantity="other">%1$d to try</item>
|
||||
</plurals>
|
||||
<plurals name="upd_preview_behind">
|
||||
<item quantity="one">Changes since your build · %1$d build behind</item>
|
||||
<item quantity="other">Changes since your build · %1$d builds behind</item>
|
||||
</plurals>
|
||||
<plurals name="upd_preview_recent">
|
||||
<item quantity="one">Recent changes · %1$d build</item>
|
||||
<item quantity="other">Recent changes · %1$d builds</item>
|
||||
</plurals>
|
||||
<string name="gate_title">One Android setting to change</string>
|
||||
<string name="gate_eyebrow">Steam</string>
|
||||
<string name="gate_lede">Android stops apps that start many background processes, and Steam starts dozens. Until this changes, games close without an error.</string>
|
||||
@@ -902,4 +918,21 @@
|
||||
<string name="game_env_change_title">Change variable</string>
|
||||
<string name="game_env_restore_default">Back to default</string>
|
||||
<string name="game_env_eyebrow">Proton games</string>
|
||||
<string name="pip_title">Picture in picture</string>
|
||||
<string name="pip_auto">Automatically enter PiP</string>
|
||||
<string name="pip_suspended">Suspended</string>
|
||||
<string name="pip_not_ready">Picture in picture is available once the session is ready.</string>
|
||||
<string name="pip_permission">Allow picture in picture for DroidDeck in Android settings.</string>
|
||||
<string name="pip_unavailable">Android could not open picture in picture.</string>
|
||||
<string name="game_shortcut">Shortcut</string>
|
||||
<string name="game_shortcut_add">Add to home screen</string>
|
||||
<string name="game_shortcut_choose">Choose game</string>
|
||||
<string name="game_shortcut_scanning">Scanning installed games…</string>
|
||||
<string name="game_link_copy">Copy launch link</string>
|
||||
<string name="game_link_copied">Launch link copied</string>
|
||||
<string name="game_shortcut_unsupported">This launcher cannot add shortcuts. Use Copy launch link instead.</string>
|
||||
<string name="game_link_invalid">Invalid game launch link.</string>
|
||||
<string name="game_link_missing">This game is no longer in your DroidDeck library.</string>
|
||||
<string name="game_link_session_busy">Stop the current session before launching a Steam game.</string>
|
||||
<string name="game_link_failed">Could not send the game to Steam. Try launching it again.</string>
|
||||
</resources>
|
||||
@@ -0,0 +1,83 @@
|
||||
package com.droiddeck.launcher.frontend
|
||||
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import android.app.Activity
|
||||
import com.droiddeck.launcher.MainActivity
|
||||
import com.droiddeck.launcher.frontend.Library
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNotNull
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.Robolectric
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.RuntimeEnvironment
|
||||
import org.robolectric.annotation.Config
|
||||
|
||||
class GameLaunchLinkTest {
|
||||
@Test fun acceptsCanonicalUnsignedDecimalIdsIncludingFullWidthShortcuts() {
|
||||
val ids = listOf("1", "17410", "9223372036854775808", "18446744073709551615")
|
||||
ids.forEach { id ->
|
||||
assertTrue(GameLaunchLink.validId(id))
|
||||
assertEquals(id, GameLaunchLink.parse(GameLaunchLink.uri(id)))
|
||||
assertEquals("steam://rungameid/$id", GameLaunchLink.steamUrl(id))
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun rejectsAnythingOtherThanOneCanonicalGamePath() {
|
||||
listOf(
|
||||
null, "", "droiddeck://game/0", "droiddeck://game/01", "droiddeck://game/+1",
|
||||
"droiddeck://game/-1", "droiddeck://game/18446744073709551616",
|
||||
"droiddeck://game/1?url=steam://rungameid/2", "droiddeck://game/1/../2",
|
||||
"droiddeck://games/1", "droiddeck://game/1/", "DROIDDECK://game/1",
|
||||
"droiddeck://game:4/1", "file:///game/1", "steam://rungameid/1",
|
||||
).forEach { assertNull("should reject $it", GameLaunchLink.parse(it)) }
|
||||
}
|
||||
|
||||
@Test fun convertsSignedStorageRepresentationToUnsignedShortcutUri() {
|
||||
assertEquals("18446744073709551615", Library.SteamGame(1, "Added", null, Library.ADDED, -1L).gameIdString)
|
||||
assertEquals("9223372036854775808", Library.SteamGame(1, "Added", null, Library.ADDED, Long.MIN_VALUE).gameIdString)
|
||||
assertEquals("droiddeck://game/18446744073709551615", GameLaunchLink.uri(Library.SteamGame(1, "Added", null, Library.ADDED, -1L).gameIdString))
|
||||
}
|
||||
}
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [33])
|
||||
class GameShortcutIntentTest {
|
||||
@Test fun shortcutLaunchIsExplicitAndReturnsThroughTheExistingMainActivity() {
|
||||
val context = RuntimeEnvironment.getApplication()
|
||||
val id = "18446744073709551615"
|
||||
val intent = GameShortcuts.launchIntent(context, id)
|
||||
|
||||
assertEquals(Intent.ACTION_VIEW, intent.action)
|
||||
assertEquals(Uri.parse("droiddeck://game/$id"), intent.data)
|
||||
assertEquals(MainActivity::class.java.name, intent.component?.className)
|
||||
assertEquals(android.content.Intent.FLAG_ACTIVITY_CLEAR_TOP or android.content.Intent.FLAG_ACTIVITY_SINGLE_TOP, intent.flags)
|
||||
}
|
||||
|
||||
@Test fun pinnedShortcutHasStableIdAndCanonicalExplicitLaunchIntent() {
|
||||
val activity = Robolectric.buildActivity(Activity::class.java).setup().get()
|
||||
val game = Library.SteamGame(8400, "Geometry Wars: Retro Evolved", null, "steam", 8400L)
|
||||
|
||||
GameShortcuts.pin(activity, game)
|
||||
|
||||
val shortcut = activity.getSystemService(android.content.pm.ShortcutManager::class.java)
|
||||
.pinnedShortcuts.single()
|
||||
val launch = requireNotNull(shortcut.intent)
|
||||
assertEquals("game:8400", shortcut.id)
|
||||
assertEquals("Geometry Wars: Retro Evolved", shortcut.shortLabel.toString())
|
||||
assertEquals(MainActivity::class.java.name, shortcut.activity?.className)
|
||||
assertEquals(Intent.ACTION_VIEW, launch.action)
|
||||
assertEquals(Uri.parse("droiddeck://game/8400"), launch.data)
|
||||
assertEquals(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP, launch.flags)
|
||||
}
|
||||
|
||||
@Test fun actionCreateShortcutUsesAndroidsShortcutResultIntentApi() {
|
||||
val activity = Robolectric.buildActivity(Activity::class.java).setup().get()
|
||||
val game = Library.SteamGame(8400, "Geometry Wars: Retro Evolved", null, "steam", 8400L)
|
||||
|
||||
assertNotNull(GameShortcuts.result(activity, game))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
|
||||
class PipPolicyTest {
|
||||
@Test fun automaticEntryNeverOpensStartingFailedOrSuspendedSessions() {
|
||||
for (phase in SessionPhase.entries) {
|
||||
assertEquals(phase == SessionPhase.READY,
|
||||
PipPolicy.eligible(true, true, phase, phase == SessionPhase.SUSPENDED, true))
|
||||
}
|
||||
assertFalse(PipPolicy.eligible(true, false, SessionPhase.READY, false, true))
|
||||
assertFalse(PipPolicy.eligible(false, true, SessionPhase.READY, false, true))
|
||||
}
|
||||
|
||||
@Test fun manualEntryAllowsAVisibleSuspendedPicture() {
|
||||
assertTrue(PipPolicy.eligible(true, true, SessionPhase.SUSPENDED, true, false))
|
||||
assertFalse(PipPolicy.eligible(true, false, SessionPhase.SUSPENDED, true, false))
|
||||
}
|
||||
|
||||
@Test fun aspectRatiosStayWithinAndroidLimitsWithoutChangingNormalContent() {
|
||||
assertEquals(1920 to 1080, PipPolicy.aspect(1920, 1080))
|
||||
assertEquals(239 to 100, PipPolicy.aspect(5760, 1080))
|
||||
assertEquals(100 to 239, PipPolicy.aspect(1080, 5760))
|
||||
assertEquals(16 to 9, PipPolicy.aspect(0, 0))
|
||||
}
|
||||
}
|
||||
@@ -5,9 +5,12 @@ import com.droiddeck.launcher.update.AppUpdates.Channel
|
||||
import com.droiddeck.launcher.update.AppUpdates.Follow
|
||||
import com.droiddeck.launcher.update.AppUpdates.Installed
|
||||
import com.droiddeck.launcher.update.AppUpdates.Offer
|
||||
import com.droiddeck.launcher.update.AppUpdates.PreviewChange
|
||||
import com.droiddeck.launcher.update.AppUpdates.PreviewHistoryKind
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNotNull
|
||||
import org.junit.Assert.assertNull
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Assert.fail
|
||||
@@ -63,7 +66,17 @@ class AppUpdatesTest {
|
||||
pr: Int = 0,
|
||||
version: String = "0.2.0",
|
||||
versionCode: Int = 9,
|
||||
) = Installed(commit, pr, version, versionCode, updatable = true)
|
||||
ciBuild: Boolean = true,
|
||||
) = Installed(commit, pr, version, versionCode, updatable = true, ciBuild = ciBuild)
|
||||
|
||||
private fun change(commit: String, title: String, publishedAt: Long) =
|
||||
PreviewChange(commit, title, "Summary for $title", publishedAt)
|
||||
|
||||
private val recentPreview = listOf(
|
||||
change("1".repeat(40), "Newest", 300L),
|
||||
change("2".repeat(40), "Middle", 200L),
|
||||
change("3".repeat(40), "Oldest", 100L),
|
||||
)
|
||||
|
||||
@Test
|
||||
fun theStableBuildIsCurrentOnStable() {
|
||||
@@ -122,6 +135,76 @@ class AppUpdatesTest {
|
||||
assertNotNull(AppUpdates.installBlock(missing, me("eeeeeee")))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun previewHistoryCountsOnlyAnUnambiguousPublishedPreviewCommit() {
|
||||
val withHistory = AppUpdates.Catalog(stable, release("1111111"), emptyList(), 0L, recentPreview)
|
||||
val result = AppUpdates.previewHistory(withHistory, me("2".repeat(40), version = "0.3.0"))!!
|
||||
assertEquals(PreviewHistoryKind.BEHIND, result.kind)
|
||||
assertEquals(1, result.buildsBehind)
|
||||
assertEquals(listOf("Newest"), result.changes.map { it.title })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun currentPreviewHasNoRedundantChangeRows() {
|
||||
val withHistory = AppUpdates.Catalog(stable, release("1111111"), emptyList(), 0L, recentPreview)
|
||||
val result = AppUpdates.previewHistory(withHistory, me("1".repeat(40), version = "0.3.0"))!!
|
||||
assertEquals(PreviewHistoryKind.CURRENT, result.kind)
|
||||
assertTrue(result.changes.isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun missingOrAmbiguousPreviewCommitsUseNeutralRecentHistory() {
|
||||
val withHistory = AppUpdates.Catalog(stable, release("1111111"), emptyList(), 0L, recentPreview)
|
||||
assertEquals(
|
||||
PreviewHistoryKind.RECENT,
|
||||
AppUpdates.previewHistory(withHistory, me("9".repeat(40), version = "0.3.0"))!!.kind,
|
||||
)
|
||||
|
||||
val ambiguous = listOf(
|
||||
change("abcdef0" + "1".repeat(33), "First", 300L),
|
||||
change("abcdef0" + "2".repeat(33), "Second", 200L),
|
||||
)
|
||||
val ambiguousCatalog = AppUpdates.Catalog(stable, release("abcdef0"), emptyList(), 0L, ambiguous)
|
||||
val result = AppUpdates.previewHistory(ambiguousCatalog, me("abcdef0", version = "0.3.0"))!!
|
||||
assertEquals(PreviewHistoryKind.RECENT, result.kind)
|
||||
assertEquals(2, result.changes.size)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun prStableAndLocalBuildsDoNotGetPreviewDistance() {
|
||||
val withHistory = AppUpdates.Catalog(stable, release("1111111"), emptyList(), 0L, recentPreview)
|
||||
assertEquals(
|
||||
PreviewHistoryKind.RECENT,
|
||||
AppUpdates.previewHistory(withHistory, me("2".repeat(40), pr = 93, version = "0.3.0"))!!.kind,
|
||||
)
|
||||
assertEquals(
|
||||
PreviewHistoryKind.RECENT,
|
||||
AppUpdates.previewHistory(withHistory, me(stable.commit))!!.kind,
|
||||
)
|
||||
assertNull(AppUpdates.previewHistory(withHistory, me("2".repeat(40), version = "0.3.0", ciBuild = false)))
|
||||
assertEquals(
|
||||
PreviewHistoryKind.RECENT,
|
||||
AppUpdates.previewHistory(withHistory, me("2".repeat(40), version = "0.1.0"))!!.kind,
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun cachedPreviewHistorySurvivesRoundTrip() {
|
||||
val withHistory = AppUpdates.Catalog(stable, release("1111111"), emptyList(), 123L, recentPreview)
|
||||
val cached = AppUpdates.readCachedCatalog(AppUpdates.writeCatalog(withHistory))
|
||||
assertEquals(123L, cached.checkedAt)
|
||||
assertEquals(3, cached.recentPreviews.size)
|
||||
assertEquals("Newest", cached.recentPreviews.first().title)
|
||||
assertEquals(recentPreview.first().commit, cached.recentPreviews.first().commit)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun oldCachedCatalogWithoutPreviewHistoryRemainsReadable() {
|
||||
val cached = AppUpdates.readCachedCatalog(JSONObject().put("tests", JSONArray()).put("checkedAt", 123L))
|
||||
assertEquals(123L, cached.checkedAt)
|
||||
assertTrue(cached.recentPreviews.isEmpty())
|
||||
}
|
||||
|
||||
private fun publishedCatalog(signer: String = BuildConfig.RELEASE_SIGNER): JSONObject {
|
||||
val raw = """
|
||||
{
|
||||
@@ -169,6 +252,25 @@ class AppUpdatesTest {
|
||||
assertEquals(9, parsed.preview!!.apk!!.versionCode)
|
||||
assertNull(parsed.preview!!.version)
|
||||
assertEquals(123L, parsed.checkedAt)
|
||||
assertTrue(parsed.recentPreviews.isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun publishedCatalogReadsOptionalPreviewHistoryAndDeduplicates() {
|
||||
val first = "a".repeat(40)
|
||||
val newest = "b".repeat(40)
|
||||
val raw = publishedCatalog().put(
|
||||
"recentPreviews",
|
||||
JSONArray()
|
||||
.put(JSONObject().put("commit", first).put("title", "Older").put("summary", "Old").put("publishedAt", 1L))
|
||||
.put(JSONObject().put("commit", newest).put("title", "Newest").put("summary", "New").put("publishedAt", 2L))
|
||||
.put(JSONObject().put("commit", first).put("title", "Duplicate").put("summary", "Again").put("publishedAt", 3L))
|
||||
.put(JSONObject().put("commit", "shortsha").put("title", "Invalid")),
|
||||
)
|
||||
val parsed = AppUpdates.readPublishedCatalog(raw, "com.droiddeck.launcher", 123L)
|
||||
assertEquals(2, parsed.recentPreviews.size)
|
||||
assertEquals("Duplicate", parsed.recentPreviews.first().title)
|
||||
assertEquals(newest, parsed.recentPreviews.last().commit)
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
# Android clipboard text
|
||||
|
||||
Copy text in an Android app, return to DroidDeck, and paste into Steam with Ctrl+V.
|
||||
The session's PC keyboard supports this through its sticky Ctrl key and V.
|
||||
|
||||
Android clipboard reads follow window focus, including the secondary-display presentation.
|
||||
The existing Wayland text selection handles native guest clients. Gamescope does not relay
|
||||
that selection to its inner Xwayland, so a session helper publishes Android text there.
|
||||
It waits for file and X11 events, and exits when its parent session exits.
|
||||
|
||||
The Gamescope bridge currently supports Android-to-guest plain text up to 64 KiB.
|
||||
It does not transfer images/files or export Steam's copied text back to Android.
|
||||
Oversized text clears an earlier Android selection rather than pasting a truncated command.
|
||||
Clipboard text stays in private app data and is never included in session logs.
|
||||
|
||||
## Thor validation, 2026-10-02
|
||||
|
||||
AYN Thor, serial `d234a848`, Android 13, release APK installed in place.
|
||||
Built with `tools/build_local.sh`; shell syntax, workflow YAML, and diff checks passed.
|
||||
Installed APK SHA-256 matched the local artifact:
|
||||
`624782af4319af538a9ae5dba6e012ebb51c7fd43a3955c4f568d214f9c32c07`.
|
||||
|
||||
- The supplied launch-options string pasted through Ctrl+V into Steam's actual Launch Options field exactly. The field was restored to its original empty value.
|
||||
- Unicode (`café 日本語 😀`, quotes, dollar sign, and backslash) also pasted exactly into Steam. The field was restored again.
|
||||
- Final-build X11 selection checks passed for launch options, multiline text, Unicode, 8 KiB, clearing, and replacing the clipboard across Android app switches.
|
||||
- Copying on Thor's second display transferred the text while Steam remained visible on the first display.
|
||||
- Copying the same Android text after a guest owned the X11 selection restored the Android selection.
|
||||
- A 65,537-byte clipboard was rejected without truncation; a subsequent normal clipboard transferred correctly.
|
||||
- The helper exited during APK replacement. The temporary Android test app, guest probe, and local ADB forward were removed.
|
||||
|
||||
Local screenshots, field values, build log, and check results: `/tmp/droiddeck-clipboard-evidence`.
|
||||
|
||||
## Visible editor-to-Steam test
|
||||
|
||||
Typed the supplied launch command into a temporary native Android EditText editor
|
||||
using Android keyboard events, selected all, and copied with Android's standard
|
||||
Ctrl+C action. Returned to the running DroidDeck Steam session and pasted into
|
||||
The Sims Legacy Collection's Launch Options. Steam's persisted value matched the
|
||||
complete 126-byte command exactly. No clipboard-setting API was used by the editor.
|
||||
|
||||
Repeated with `DroidDeck Thor clipboard test 2026-10-02`, using Steam's on-screen
|
||||
keyboard Paste button. The whole value is visible in these unedited Thor screenshots:
|
||||
|
||||

|
||||
|
||||

|
||||
|
||||
The launch options were restored to their original empty value and verified in
|
||||
Steam's configuration. The temporary editor and ADB forward were removed.
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 97 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 287 KiB |
@@ -0,0 +1,49 @@
|
||||
# Game launcher shortcuts
|
||||
|
||||
DroidDeck exposes installed Steam titles and AddedGames through a canonical launch link:
|
||||
|
||||
```text
|
||||
droiddeck://game/<unsigned-decimal-game-id>
|
||||
```
|
||||
|
||||
The ID is the value accepted by `steam://rungameid/`, including an AddedGames shortcut ID that occupies the unsigned 64-bit range. The app accepts only the exact URI form and only after a fresh library scan finds that game. It does not accept paths, Steam URLs, extra parameters, leading zeroes, or IDs outside the unsigned 64-bit range.
|
||||
|
||||
Each game page's **Shortcut** menu offers **Add to home screen** through Android's pinned-shortcut request and **Copy launch link**. When a launcher invokes `ACTION_CREATE_SHORTCUT`, DroidDeck opens the Games page and returns Android's standard shortcut result after the user chooses a game.
|
||||
|
||||
With the debug app installed, exercise link routing with an installed game ID from the current library:
|
||||
|
||||
```sh
|
||||
adb shell am start -n com.droiddeck.launcher/.MainActivity \
|
||||
-a android.intent.action.VIEW -d 'droiddeck://game/620'
|
||||
```
|
||||
|
||||
Open the standard shortcut picker with:
|
||||
|
||||
```sh
|
||||
adb shell am start -n com.droiddeck.launcher/.MainActivity \
|
||||
-a android.intent.action.CREATE_SHORTCUT
|
||||
```
|
||||
|
||||
A cold link starts the normal Steam session with `steam://rungameid/<id>` as its startup URL. A warm link is accepted only during a running Steam session. The service waits for READY, resumes a suspended session, then writes a decimal-only request for the existing Steam client to consume. Desktop and program sessions remain active and report that the game cannot be launched until the current session ends.
|
||||
|
||||
Build a full local debug APK, including the native/audio bundle, with:
|
||||
|
||||
```sh
|
||||
DROIDDECK_BUILD_VARIANT=debug tools/build_local.sh
|
||||
```
|
||||
|
||||
The focused JVM suite is `./gradlew app:testDebugUnitTest`. See the task report and session logs when validating cold launch, warm launch, resume, queueing, and rejection paths on a device.
|
||||
|
||||
## Thor acceptance run
|
||||
|
||||
Validated on the AYN Thor (Android 13 / API 33, serial `adb-d234a848-fv2FDl (2)._adb-tls-connect._tcp`). The full debug APK at `app/build/outputs/apk/debug/app-debug.apk` installed with `adb install -r --no-incremental`, without uninstalling or clearing app data.
|
||||
|
||||
- Pinned **Geometry Wars: Retro Evolved** from its game page, confirmed `game:8400` in Android's pinned shortcut database, and tapped that actual home-screen icon. The cold session reached READY with first frame; `Download/DroidDeck/2026-10-02-27-steam/session.log` records `steam://rungameid/8400`, Steam game ID 8400, `GeometryWars.exe`, and Gamescope focus on app 8400.
|
||||
- Copied the link from the game menu. Android's clipboard preview showed `droiddeck://game/8400`. An ACTION_VIEW of that URI reused session `2026-10-02-27-steam`, guest PID 14740, and gamescope PID 14762; its event log recorded `steam.game_launch_requested` without a new compositor or guest process.
|
||||
- Sent another game link while the generic Steam session was in `STARTING_STEAM`. Session `2026-10-02-28-steam` reached READY before recording the queued launch, and its guest log says it launched game 8400 through the running client.
|
||||
- Pressing Home suspended the warm Steam session. Tapping the same pinned shortcut resumed session `2026-10-02-27-steam` with guest PID 14740 and dispatched the game request after `session.resumed`.
|
||||
- Leading-zero, overflow-with-query, and unknown-ID links left the agent IDLE with no guest. A MODE_RUN session using `/usr/bin/sleep 300` remained the same session and program after opening the game link; no Steam launch was requested.
|
||||
- ACTION_CREATE_SHORTCUT opened the Games picker on a fresh scan; choosing the title finished the picker. A shell-started activity has no caller to inspect the returned payload, so the end-to-end result extras were not directly captured on-device. Robolectric covers the result API call and shortcut intent metadata.
|
||||
- The existing Game files and Proton prefix controls still opened Geometry Wars' installed folder and `compatdata/8400/pfx` in the file manager.
|
||||
|
||||
The device logs remain under `/sdcard/Download/DroidDeck/2026-10-02-27-steam` and `.../2026-10-02-28-steam`. Screenshots from the run are in `/tmp/game-launcher-thor-*.png`, `/tmp/files.png`, and `/tmp/prefix.png`. The only shortcut added for this run was `game:8400`; it was removed after validation.
|
||||
@@ -0,0 +1,79 @@
|
||||
# Opt-in software Steam compatibility
|
||||
|
||||
This change provides an explicit software fallback for the Linux Steam/Gamescope
|
||||
session. It does not enable fallback automatically or install a Mali Linux ICD.
|
||||
The Android presenter still uses Vulkan; a positively identified Mali kbase
|
||||
GPU uses the system Android driver. Adreno and unknown devices keep the existing
|
||||
selection, and explicit Android driver choices retain precedence.
|
||||
|
||||
## Enable and recover
|
||||
|
||||
Set `/sdcard/Download/droiddeck-env` to include:
|
||||
|
||||
```sh
|
||||
BL_STEAM_SOFTWARE=1
|
||||
```
|
||||
|
||||
Remove that entry or set it to `0` to return to normal session rendering. No
|
||||
preference is migrated or enabled by this branch. Only the exact value `1`
|
||||
activates the fallback in the scripts and native Gamescope.
|
||||
|
||||
The fallback selects Lavapipe/llvmpipe, Gamescope's SDL Wayland swapchain,
|
||||
software Steam CEF/SDL rendering, and disables mangoapp for that session.
|
||||
An explicitly requested software session takes precedence over `BL_VK_DRIVER`;
|
||||
with the mode off, imported Linux drivers retain their existing behavior.
|
||||
Desktop Steam can also use this mode on a pixman desktop.
|
||||
|
||||
The optional present timing, local texture allocation, SHM refresh and ready
|
||||
fence handling in the new Gamescope patches apply only in this mode. Normal
|
||||
sessions retain the original dma-buf, buffer-cache and presentation paths.
|
||||
The Android presenter lowers its 1.3 request when the loader positively reports
|
||||
an older usable API. Custom ICDs that cannot report a version retain the original
|
||||
request. Dma-buf import is advertised only with the complete extension set.
|
||||
|
||||
## Validation
|
||||
|
||||
`tools/tests/test_software_graphics.py` exercises the actual outer session
|
||||
launcher with a capturing Gamescope executable: default accelerated backend,
|
||||
custom-driver selection, software-only activation, precedence, overlay, HDR,
|
||||
refresh rate and argument preservation. The native component is built against
|
||||
all existing patches and checked against the runtime's shared-library list.
|
||||
`gamescope-3.16.29-p6` is a versioned component release; the existing release
|
||||
download/checksum path is unchanged. There is no CI artifact pin or extra build
|
||||
workflow permission.
|
||||
|
||||
Local validation passed all 121 JVM tests and the macOS-applicable Python tests
|
||||
(62 discovered, 13 Linux-only skipped). The corrected native build passed
|
||||
[run 37161255955](https://github.com/Droid-Deck/DroidDeck/actions/runs/37161255955).
|
||||
The final code's APK build, Python and JVM tests, and native dependency closure
|
||||
check passed [run 37162182731](https://github.com/Droid-Deck/DroidDeck/actions/runs/37162182731).
|
||||
The installed Gamescope binary matches the component's contents
|
||||
(`2c92c155f7836a798c2a04eb1db5779e149680fcce888cd9a1ebe3fef7e5a2af`).
|
||||
|
||||
The cleanup build was installed in place on the wired Mali device using the
|
||||
release-signed debug APK. Automatic selection logged the positive Mali kbase
|
||||
identification, and Steam Big Picture reached the logged-in home screen through
|
||||
the new software-compatible Gamescope. Animated frames and input worked. A
|
||||
Geometry Wars retest stalled during Wine prefix startup; successful gameplay
|
||||
below belongs to the earlier experiment, not this cleanup validation. No
|
||||
physical Adreno device was updated during this cleanup.
|
||||
|
||||
Earlier experiment validation on the wired Unisoc T618 / Mali-G52 MC2 device
|
||||
(Android 12, kbase JM 11.31) reached Steam Big Picture sign-in and downloaded
|
||||
Geometry Wars: Retro Evolved. Its software-rendered menu, movement, shooting and
|
||||
pause worked, at roughly 3–5 displayed FPS. The per-game workaround was:
|
||||
|
||||
```sh
|
||||
DISABLE_GAMESCOPE_WSI=1 %command%
|
||||
```
|
||||
|
||||
This option is not applied globally. Software gameplay remains too slow for
|
||||
normal play. The previous experimental branch `mali-software-steam` retains
|
||||
the private PanVK build and GPU proof: compute, draw/readback, indexed draw and
|
||||
visible VKCube worked, but accelerated Geometry Wars lost the GPU device.
|
||||
That driver lab is intentionally outside this compatibility change.
|
||||
|
||||
Before a PR, validate default rendering on supported Adreno devices, explicit
|
||||
Android/Linux driver choices, overlays and supported HDR/frame-generation
|
||||
behavior as well as the opted-in wired Mali session. Passing launcher checks
|
||||
alone is not proof of physical Adreno regression safety.
|
||||
+13
-4
@@ -14,6 +14,12 @@ fi
|
||||
sdk_dir=${ANDROID_HOME:-${ANDROID_SDK_ROOT:-"${HOME}/Library/Android/sdk"}}
|
||||
java_dir=${JAVA_HOME:-"/opt/homebrew/opt/openjdk@17/libexec/openjdk.jdk/Contents/Home"}
|
||||
image_name=${DROIDDECK_BUILD_IMAGE:-droiddeck-local-cross:24.04-v2}
|
||||
build_variant=${DROIDDECK_BUILD_VARIANT:-release}
|
||||
case "$build_variant" in
|
||||
debug) gradle_task=assembleDebug ;;
|
||||
release) gradle_task=assembleRelease ;;
|
||||
*) echo "DROIDDECK_BUILD_VARIANT must be debug or release" >&2; exit 1 ;;
|
||||
esac
|
||||
|
||||
if [[ ! -x "${sdk_dir}/platform-tools/adb" ]]; then
|
||||
echo "Android SDK not found at ${sdk_dir}; set ANDROID_HOME or ANDROID_SDK_ROOT." >&2
|
||||
@@ -120,6 +126,9 @@ docker run --rm --platform linux/amd64 \
|
||||
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"
|
||||
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"
|
||||
for script in tools/linuxfs/overlay/usr/local/bin/bannerlator-*; do
|
||||
install -Dm644 "$script" "$d/usr/local/bin/$(basename "$script")"
|
||||
done
|
||||
@@ -282,11 +291,11 @@ bundle_replaced=1
|
||||
mv "${staging_dir}/pulseaudio.tzst" "${bundle_asset}"
|
||||
|
||||
cd "${repo_root}"
|
||||
./gradlew assembleRelease --console=plain -PndkVersion="${ndk_version}"
|
||||
./gradlew "${gradle_task}" --console=plain -PndkVersion="${ndk_version}"
|
||||
cp -p "${bundle_backup}" "${bundle_asset}"
|
||||
bundle_replaced=0
|
||||
|
||||
apk="${repo_root}/app/build/outputs/apk/release/app-release.apk"
|
||||
apk="${repo_root}/app/build/outputs/apk/${build_variant}/app-${build_variant}.apk"
|
||||
audio_check="${staging_dir}/audio-check"
|
||||
mkdir -p "${audio_check}"
|
||||
unzip -p "${apk}" assets/pulseaudio.tzst | zstd -dc | tar -xf - -C "${audio_check}"
|
||||
@@ -300,10 +309,10 @@ for audio_file in \
|
||||
fi
|
||||
done
|
||||
|
||||
docker run --rm --platform linux/amd64 -v "${repo_root}:/src:ro" -w /src "${image_name}" \
|
||||
docker run --rm --platform linux/amd64 -e build_variant="${build_variant}" -v "${repo_root}:/src:ro" -w /src "${image_name}" \
|
||||
bash -lc '
|
||||
set -euo pipefail
|
||||
apk=app/build/outputs/apk/release/app-release.apk
|
||||
apk=app/build/outputs/apk/${build_variant}/app-${build_variant}.apk
|
||||
work=$(mktemp -d)
|
||||
unzip -q "$apk" "lib/arm64-v8a/*" -d "$work"
|
||||
cd "$work/lib/arm64-v8a"
|
||||
|
||||
@@ -1,38 +0,0 @@
|
||||
#!/usr/bin/bash
|
||||
# Runs INSIDE an Arch Linux ARM container (menci/archlinuxarm:base-devel) on an arm64 runner.
|
||||
# Builds FEX for the runtime, with tools/fex/patches, (Arch Linux ARM ships no package and FEX publishes no Linux
|
||||
# binaries), plus the runtime's own unsquashfs to unpack FEX's x86 rootfs image, and packs both
|
||||
# as fex.tzst (usr/local/...) for bannerlator-steam-x64 to stage. No thunks: they need an x86
|
||||
# cross toolchain, and the x86-64 Steam client only needs FEX to run, not host GPU drivers.
|
||||
set -euxo pipefail
|
||||
VERSION=${FEX_VERSION:-FEX-2609}
|
||||
WORK=/work
|
||||
cd "$WORK"
|
||||
# Same pacman workarounds as tools/gamescope/build-in-arch.sh.
|
||||
grep -q '^DisableSandbox' /etc/pacman.conf || sed -i 's/^\[options\]/[options]\nDisableSandbox/' /etc/pacman.conf
|
||||
{ for m in https://ca.us.mirror.archlinuxarm.org https://fl.us.mirror.archlinuxarm.org https://de3.mirror.archlinuxarm.org https://nl.mirror.archlinuxarm.org; do echo "Server = $m/\$arch/\$repo"; done; cat /etc/pacman.d/mirrorlist; } > /etc/pacman.d/mirrorlist.new
|
||||
mv /etc/pacman.d/mirrorlist.new /etc/pacman.d/mirrorlist
|
||||
pacman -Syu --noconfirm --needed git zstd binutils cmake ninja clang lld llvm python squashfs-tools file
|
||||
|
||||
rm -rf fex-src out && git clone -q --depth 1 --branch "$VERSION" --recurse-submodules --shallow-submodules https://github.com/FEX-Emu/FEX.git fex-src
|
||||
# Our proot answers openat2 with ENOSYS (tools/proot/PATCHES.md, 0008); FEX opened every rootfs
|
||||
# path with openat2 and fell through to the arm64 guest's files on anything but EXDEV.
|
||||
for p in tools/fex/patches/*.patch; do patch -d fex-src -p1 --no-backup-if-mismatch < "$p"; done
|
||||
# TUNE_CPU none: the default (native) would tune for the runner's Neoverse cores, not the device.
|
||||
cmake -S fex-src -B fex-build -G Ninja \
|
||||
-DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=/usr/local \
|
||||
-DCMAKE_C_COMPILER=clang -DCMAKE_CXX_COMPILER=clang++ -DUSE_LINKER=lld \
|
||||
-DTUNE_CPU=none -DTUNE_ARCH=armv8-a \
|
||||
-DBUILD_TESTING=OFF -DBUILD_THUNKS=OFF -DBUILD_FEXCONFIG=OFF -DENABLE_ASSERTIONS=OFF \
|
||||
-DENABLE_CCACHE=OFF -DENABLE_OFFLINE_TELEMETRY=OFF
|
||||
ninja -C fex-build
|
||||
DESTDIR="$WORK/out" ninja -C fex-build install
|
||||
install -Dm755 /usr/bin/unsquashfs out/usr/local/bin/unsquashfs
|
||||
# Nothing outside the runtime's own libraries: every needed soname must resolve in a stock guest.
|
||||
for f in out/usr/local/bin/*; do
|
||||
file "$f" | grep -q ELF || continue
|
||||
readelf -d "$f" | awk '/NEEDED/ { gsub(/[\[\]]/, "", $5); print $5 }'
|
||||
done | sort -u | tee fex-needed.txt
|
||||
(cd out && find . -type f -o -type l | sort) | tee fex-files.txt
|
||||
tar -C out -c . | zstd -19 -T0 -o fex.tzst
|
||||
sha256sum fex.tzst | tee fex.tzst.sha256
|
||||
@@ -1,42 +0,0 @@
|
||||
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/FileManagement.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/FileManagement.cpp
|
||||
index 7172460..d566e3b 100644
|
||||
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/FileManagement.cpp
|
||||
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/FileManagement.cpp
|
||||
@@ -674,9 +674,10 @@ uint64_t FileManager::Open(const char* pathname, int flags, uint32_t mode) {
|
||||
};
|
||||
fd = ::syscall(SYSCALL_DEF(openat2), Path.FD, Path.Path, &how, sizeof(how));
|
||||
|
||||
- if (fd == -1 && errno == EXDEV) {
|
||||
- // This means a magic symlink (/proc/foo) was involved. In this case we
|
||||
- // just punt and do the access without RESOLVE_IN_ROOT.
|
||||
+ if (fd == -1 && (errno == EXDEV || errno == ENOSYS)) {
|
||||
+ // EXDEV: a magic symlink (/proc/foo) was involved. ENOSYS: no openat2 here (proot).
|
||||
+ // Either way, do the access without RESOLVE_IN_ROOT; GetEmulatedFDPath has already
|
||||
+ // followed absolute symlinks inside the rootfs.
|
||||
fd = ::syscall(SYSCALL_DEF(openat), Path.FD, Path.Path, flags, mode);
|
||||
}
|
||||
}
|
||||
@@ -927,9 +928,10 @@ uint64_t FileManager::Openat([[maybe_unused]] int dirfs, const char* pathname, i
|
||||
.resolve = (Path.FD == AT_FDCWD) ? 0u : RESOLVE_IN_ROOT, // AT_FDCWD means it's a thunk and not via RootFS
|
||||
};
|
||||
fd = ::syscall(SYSCALL_DEF(openat2), Path.FD, Path.Path, &how, sizeof(how));
|
||||
- if (fd == -1 && errno == EXDEV) {
|
||||
- // This means a magic symlink (/proc/foo) was involved. In this case we
|
||||
- // just punt and do the access without RESOLVE_IN_ROOT.
|
||||
+ if (fd == -1 && (errno == EXDEV || errno == ENOSYS)) {
|
||||
+ // EXDEV: a magic symlink (/proc/foo) was involved. ENOSYS: no openat2 here (proot).
|
||||
+ // Either way, do the access without RESOLVE_IN_ROOT; GetEmulatedFDPath has already
|
||||
+ // followed absolute symlinks inside the rootfs.
|
||||
fd = ::syscall(SYSCALL_DEF(openat), Path.FD, Path.Path, flags, mode);
|
||||
}
|
||||
}
|
||||
@@ -967,6 +969,9 @@ uint64_t FileManager::Openat2(int dirfs, const char* pathname, FEX::HLE::open_ho
|
||||
// This means a magic symlink (/proc/foo) was involved. In this case we
|
||||
// just punt and do the access without RESOLVE_IN_ROOT.
|
||||
fd = ::syscall(SYSCALL_DEF(openat2), Path.FD, Path.Path, how, usize);
|
||||
+ } else if (fd == -1 && errno == ENOSYS && how->resolve == 0) {
|
||||
+ // No openat2 here (proot): the plain openat inside the rootfs, as above.
|
||||
+ fd = ::syscall(SYSCALL_DEF(openat), Path.FD, Path.Path, (int)how->flags, (int)how->mode);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -49,3 +49,13 @@ library list, before anything is published.
|
||||
|
||||
Sixteen more of Armada's patches are DRM/lease/HDR-on-KMS work for a native display, which this
|
||||
app's Wayland-hosted gamescope never reaches, or need a newer gamescope than the runtime has.
|
||||
|
||||
- `0114-software-swapchain-compat.patch` - this app: only with
|
||||
`BL_STEAM_SOFTWARE=1`, allow the SDL Vulkan swapchain to run without present-ID/wait
|
||||
support and keep local textures private. Explicit exports and dma-buf imports retain
|
||||
their allocation requirements. With the mode unset, extension requests, feature chains,
|
||||
texture allocation and present-wait pacing follow the existing path.
|
||||
- `0115-software-shm-commits.patch` - this app: only in that compatibility mode,
|
||||
refresh reused shared-memory buffers on every commit and treat their completed
|
||||
synchronous uploads as ready. Normal sessions retain buffer memoization and fence
|
||||
handling; dma-buf commits retain both in either mode.
|
||||
@@ -0,0 +1,157 @@
|
||||
diff --git a/src/rendervulkan.cpp b/src/rendervulkan.cpp
|
||||
index 54e4efc..4777f7c 100644
|
||||
--- a/src/rendervulkan.cpp
|
||||
+++ b/src/rendervulkan.cpp
|
||||
@@ -57,6 +57,12 @@
|
||||
|
||||
#include "reshade_effect_manager.hpp"
|
||||
|
||||
+// Opt-in compatibility mode; an unset or other value preserves the normal backend.
|
||||
+const bool g_bSoftwareCompat = [] {
|
||||
+ const char *value = getenv( "BL_STEAM_SOFTWARE" );
|
||||
+ return value && strcmp( value, "1" ) == 0;
|
||||
+}();
|
||||
+
|
||||
extern bool g_bWasPartialComposite;
|
||||
extern bool g_bAllowDeferredBackend;
|
||||
|
||||
@@ -450,7 +456,16 @@ bool CVulkanDevice::createDevice()
|
||||
bool hasDrmProps = vulkan_has_drm_props();
|
||||
bool supportsForeignQueue = false;
|
||||
bool supportsHDRMetadata = false;
|
||||
+ bool supportsPresentId = false;
|
||||
+ bool supportsPresentWait = false;
|
||||
for (const auto& ext : m_supportedExts) {
|
||||
+ if ( g_bSoftwareCompat )
|
||||
+ {
|
||||
+ if ( strcmp(ext.extensionName, VK_KHR_PRESENT_ID_EXTENSION_NAME) == 0 )
|
||||
+ supportsPresentId = true;
|
||||
+ if ( strcmp(ext.extensionName, VK_KHR_PRESENT_WAIT_EXTENSION_NAME) == 0 )
|
||||
+ supportsPresentWait = true;
|
||||
+ }
|
||||
if ( strcmp(ext.extensionName, VK_EXT_IMAGE_DRM_FORMAT_MODIFIER_EXTENSION_NAME) == 0 )
|
||||
m_bSupportsModifiers = true;
|
||||
|
||||
@@ -518,6 +533,26 @@ bool CVulkanDevice::createDevice()
|
||||
m_bSupportsModifiers = false;
|
||||
}
|
||||
|
||||
+ m_bSupportsPresentWait = !g_bSoftwareCompat;
|
||||
+ if ( g_bSoftwareCompat && supportsPresentId && supportsPresentWait )
|
||||
+ {
|
||||
+ VkPhysicalDevicePresentWaitFeaturesKHR waitFeatures = {
|
||||
+ .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PRESENT_WAIT_FEATURES_KHR,
|
||||
+ };
|
||||
+ VkPhysicalDevicePresentIdFeaturesKHR idFeatures = {
|
||||
+ .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PRESENT_ID_FEATURES_KHR,
|
||||
+ .pNext = &waitFeatures,
|
||||
+ };
|
||||
+ VkPhysicalDeviceFeatures2 features = {
|
||||
+ .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2,
|
||||
+ .pNext = &idFeatures,
|
||||
+ };
|
||||
+ vk.GetPhysicalDeviceFeatures2( physDev(), &features );
|
||||
+ m_bSupportsPresentWait = idFeatures.presentId && waitFeatures.presentWait;
|
||||
+ }
|
||||
+ if ( GetBackend()->UsesVulkanSwapchain() && !m_bSupportsPresentWait )
|
||||
+ vk_log.infof( "Present ID/wait unavailable; using timer-based pacing." );
|
||||
+
|
||||
{
|
||||
VkPhysicalDeviceVulkan12Features vulkan12Features = {
|
||||
.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES,
|
||||
@@ -570,8 +605,11 @@ bool CVulkanDevice::createDevice()
|
||||
enabledExtensions.push_back( VK_KHR_SWAPCHAIN_EXTENSION_NAME );
|
||||
enabledExtensions.push_back( VK_KHR_SWAPCHAIN_MUTABLE_FORMAT_EXTENSION_NAME );
|
||||
|
||||
- enabledExtensions.push_back( VK_KHR_PRESENT_ID_EXTENSION_NAME );
|
||||
- enabledExtensions.push_back( VK_KHR_PRESENT_WAIT_EXTENSION_NAME );
|
||||
+ if ( m_bSupportsPresentWait )
|
||||
+ {
|
||||
+ enabledExtensions.push_back( VK_KHR_PRESENT_ID_EXTENSION_NAME );
|
||||
+ enabledExtensions.push_back( VK_KHR_PRESENT_WAIT_EXTENSION_NAME );
|
||||
+ }
|
||||
|
||||
if ( supportsHDRMetadata )
|
||||
enabledExtensions.push_back( VK_EXT_HDR_METADATA_EXTENSION_NAME );
|
||||
@@ -646,7 +684,7 @@ bool CVulkanDevice::createDevice()
|
||||
|
||||
VkPhysicalDeviceFeatures2 features2 = {
|
||||
.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2,
|
||||
- .pNext = &presentIdFeatures,
|
||||
+ .pNext = m_bSupportsPresentWait ? static_cast<void *>( &presentIdFeatures ) : static_cast<void *>( &features13 ),
|
||||
.features = {
|
||||
.shaderInt16 = m_bSupportsFp16,
|
||||
},
|
||||
@@ -2082,6 +2120,11 @@ static VkImageViewType VulkanImageTypeToViewType(VkImageType type)
|
||||
|
||||
bool CVulkanTexture::BInit( uint32_t width, uint32_t height, uint32_t depth, uint32_t drmFormat, createFlags flags, wlr_dmabuf_attributes *pDMA /* = nullptr */, uint32_t contentWidth /* = 0 */, uint32_t contentHeight /* = 0 */, CVulkanTexture *pExistingImageToReuseMemory, gamescope::OwningRc<gamescope::IBackendFb> pBackendFb )
|
||||
{
|
||||
+ // Software swapchains need local cursor, blank and wl_shm textures, not scan-out.
|
||||
+ // Explicit exports and dma-buf imports retain their original allocation requirements.
|
||||
+ if ( g_bSoftwareCompat && GetBackend()->UsesVulkanSwapchain() && !pDMA && !flags.bExportable )
|
||||
+ flags.bFlippable = false;
|
||||
+
|
||||
m_pBackendFb = std::move( pBackendFb );
|
||||
m_drmFormat = drmFormat;
|
||||
VkResult res = VK_ERROR_INITIALIZATION_FAILED;
|
||||
@@ -3086,7 +3129,7 @@ void vulkan_present_to_window( void )
|
||||
|
||||
VkPresentInfoKHR presentInfo = {
|
||||
.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR,
|
||||
- .pNext = &presentIdInfo,
|
||||
+ .pNext = g_device.supportsPresentWait() ? &presentIdInfo : nullptr,
|
||||
.swapchainCount = 1,
|
||||
.pSwapchains = &g_output.swapChain,
|
||||
.pImageIndices = &g_output.nOutImage,
|
||||
@@ -3094,8 +3137,11 @@ void vulkan_present_to_window( void )
|
||||
|
||||
if ( g_device.vk.QueuePresentKHR( g_device.queue(), &presentInfo ) == VK_SUCCESS )
|
||||
{
|
||||
- g_currentPresentWaitId = presentId;
|
||||
- g_currentPresentWaitId.notify_all();
|
||||
+ if ( g_device.supportsPresentWait() )
|
||||
+ {
|
||||
+ g_currentPresentWaitId = presentId;
|
||||
+ g_currentPresentWaitId.notify_all();
|
||||
+ }
|
||||
}
|
||||
else
|
||||
vulkan_remake_swapchain();
|
||||
@@ -3662,7 +3708,7 @@ bool vulkan_init( VkInstance instance, VkSurfaceKHR surface )
|
||||
if (!init_nis_data())
|
||||
return false;
|
||||
|
||||
- if ( GetBackend()->UsesVulkanSwapchain() )
|
||||
+ if ( GetBackend()->UsesVulkanSwapchain() && g_device.supportsPresentWait() )
|
||||
{
|
||||
std::thread present_wait_thread( present_wait_thread_func );
|
||||
present_wait_thread.detach();
|
||||
diff --git a/src/rendervulkan.hpp b/src/rendervulkan.hpp
|
||||
index fa519db..a784c29 100644
|
||||
--- a/src/rendervulkan.hpp
|
||||
+++ b/src/rendervulkan.hpp
|
||||
@@ -20,6 +20,8 @@
|
||||
|
||||
#include "shaders/descriptor_set_constants.h"
|
||||
|
||||
+extern const bool g_bSoftwareCompat;
|
||||
+
|
||||
class CVulkanCmdBuffer;
|
||||
|
||||
// 1: Fade Plane (Fade outs between switching focus)
|
||||
@@ -862,6 +864,7 @@ public:
|
||||
inline VkPipelineLayout pipelineLayout() {return m_pipelineLayout;}
|
||||
inline int drmRenderFd() {return m_drmRendererFd;}
|
||||
inline bool supportsModifiers() {return m_bSupportsModifiers;}
|
||||
+ inline bool supportsPresentWait() {return m_bSupportsPresentWait;}
|
||||
inline bool hasDrmPrimaryDevId() {return m_bHasDrmPrimaryDevId;}
|
||||
inline dev_t primaryDevId() {return m_drmPrimaryDevId;}
|
||||
inline bool supportsFp16() {return m_bSupportsFp16;}
|
||||
@@ -930,6 +933,7 @@ protected:
|
||||
uint32_t m_uVendorID = 0;
|
||||
bool m_bHasDrmPrimaryDevId = false;
|
||||
bool m_bSupportsModifiers = false;
|
||||
+ bool m_bSupportsPresentWait = true;
|
||||
bool m_bInitialized = false;
|
||||
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
diff --git a/src/steamcompmgr.cpp b/src/steamcompmgr.cpp
|
||||
index 18b799e..d854a68 100644
|
||||
--- a/src/steamcompmgr.cpp
|
||||
+++ b/src/steamcompmgr.cpp
|
||||
@@ -1850,30 +1850,32 @@ import_commit (
|
||||
commit->fifo = false;
|
||||
}
|
||||
|
||||
- if ( gamescope::OwningRc<CVulkanTexture> pTexture = s_BufferMemos.LookupVulkanTexture( buf ) )
|
||||
+ struct wlr_dmabuf_attributes dmabuf = {0};
|
||||
+ // Only the software compatibility path refreshes private wl_shm copies.
|
||||
+ // Normal sessions retain the original memo lookup before probing the buffer.
|
||||
+ const bool bRefreshShm = g_bSoftwareCompat && !wlr_buffer_get_dmabuf( buf, &dmabuf );
|
||||
+ if ( !bRefreshShm )
|
||||
{
|
||||
- // Going from OwningRc -> Rc now.
|
||||
- commit->vulkanTex = pTexture;
|
||||
- return commit;
|
||||
+ if ( gamescope::OwningRc<CVulkanTexture> pTexture = s_BufferMemos.LookupVulkanTexture( buf ) )
|
||||
+ {
|
||||
+ commit->vulkanTex = pTexture;
|
||||
+ return commit;
|
||||
+ }
|
||||
}
|
||||
|
||||
- struct wlr_dmabuf_attributes dmabuf = {0};
|
||||
gamescope::OwningRc<gamescope::IBackendFb> pBackendFb;
|
||||
if ( wlr_buffer_get_dmabuf( buf, &dmabuf ) )
|
||||
- {
|
||||
pBackendFb = GetBackend()->ImportDmabufToBackend( &dmabuf );
|
||||
- }
|
||||
|
||||
gamescope::OwningRc<CVulkanTexture> pOwnedTexture = vulkan_create_texture_from_wlr_buffer( buf, std::move( pBackendFb ) );
|
||||
|
||||
if ( pOwnedTexture == nullptr ) {
|
||||
- // Failed to create Vulkan texture from Wayland buffer for some reason.
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
commit->vulkanTex = pOwnedTexture;
|
||||
-
|
||||
- s_BufferMemos.MemoizeBuffer( buf, std::move( pOwnedTexture ) );
|
||||
+ if ( !bRefreshShm )
|
||||
+ s_BufferMemos.MemoizeBuffer( buf, std::move( pOwnedTexture ) );
|
||||
|
||||
return commit;
|
||||
}
|
||||
@@ -8504,6 +8506,13 @@ void update_wayland_res(CommitDoneList_t *doneCommits, steamcompmgr_win_t *w, Re
|
||||
{
|
||||
fence = dup( dmabuf.fd[0] );
|
||||
}
|
||||
+ else if ( g_bSoftwareCompat && GetBackend()->UsesVulkanSwapchain() &&
|
||||
+ !newCommit->vulkanTex->externalImage() )
|
||||
+ {
|
||||
+ // wl_shm uploads wait for their copy to finish in vulkan_create_texture_from_wlr_buffer.
|
||||
+ // A private swapchain texture has no dma-buf to poll; it is already ready.
|
||||
+ bKnownReady = true;
|
||||
+ }
|
||||
else
|
||||
{
|
||||
fence = newCommit->vulkanTex->memoryFence();
|
||||
@@ -1,2 +1,2 @@
|
||||
GAMESCOPE_TAG=gamescope-3.16.29-p5
|
||||
GAMESCOPE_SHA256=188144e5564e020d0bc485a1f4f90e1c5fd61d0d1d6dd29db21e8b019036a5c6
|
||||
GAMESCOPE_TAG=gamescope-3.16.29-p6
|
||||
GAMESCOPE_SHA256=b34294a5c5358b8d0bb7a2d7d45c92595dad6d8257eacc5ef36b980b8b7931f0
|
||||
@@ -0,0 +1,154 @@
|
||||
/* Android text -> Gamescope's Xwayland selection. Gamescope's Wayland backend does not
|
||||
* relay the outer compositor's clipboard. libX11 is loaded from the guest at runtime;
|
||||
* the small stable Xlib ABI below keeps this helper independent of cross X11 headers.
|
||||
* The private host file is atomically replaced, never put in session logs. */
|
||||
#define _GNU_SOURCE
|
||||
#include <sys/inotify.h>
|
||||
#include <sys/stat.h>
|
||||
#include <sys/prctl.h>
|
||||
#include <signal.h>
|
||||
#include <poll.h>
|
||||
#include <fcntl.h>
|
||||
#include <unistd.h>
|
||||
#include <dlfcn.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <errno.h>
|
||||
#include <limits.h>
|
||||
|
||||
typedef struct _XDisplay Display;
|
||||
typedef unsigned long Window, Atom, Time;
|
||||
typedef struct {
|
||||
int type; unsigned long serial; int send_event; Display *display;
|
||||
Window owner, requestor; Atom selection, target, property; Time time;
|
||||
} SelectionRequest;
|
||||
typedef struct {
|
||||
int type; unsigned long serial; int send_event; Display *display;
|
||||
Window requestor; Atom selection, target, property; Time time;
|
||||
} SelectionNotify;
|
||||
typedef union { int type; SelectionRequest request; SelectionNotify selection; long pad[24]; } Event;
|
||||
|
||||
#define API(ret, name, args) static ret (*name) args
|
||||
API(Display *, XOpenDisplay, (const char *));
|
||||
API(Window, XDefaultRootWindow, (Display *));
|
||||
API(Window, XCreateSimpleWindow, (Display *, Window, int, int, unsigned, unsigned, unsigned, unsigned long, unsigned long));
|
||||
API(Atom, XInternAtom, (Display *, const char *, int));
|
||||
API(int, XSetSelectionOwner, (Display *, Atom, Window, Time));
|
||||
API(Window, XGetSelectionOwner, (Display *, Atom));
|
||||
API(int, XChangeProperty, (Display *, Window, Atom, Atom, int, int, const unsigned char *, int));
|
||||
API(int, XSendEvent, (Display *, Window, int, long, Event *));
|
||||
API(int, XPending, (Display *));
|
||||
API(int, XNextEvent, (Display *, Event *));
|
||||
API(int, XFlush, (Display *));
|
||||
API(int, XConnectionNumber, (Display *));
|
||||
API(int, XCloseDisplay, (Display *));
|
||||
API(void *, XSetErrorHandler, (int (*)(Display *, void *)));
|
||||
|
||||
/* Stay below X11's normal maximum property request. Never paste a truncated command. */
|
||||
#define MAX_TEXT (64 * 1024)
|
||||
static int ignore_x_error(Display *d, void *event) { (void)d; (void)event; return 0; }
|
||||
|
||||
/* The host renames complete files into place. The inode distinguishes copying the same
|
||||
* text again after a guest program has taken ownership of the clipboard. */
|
||||
static int refresh(Display *d, Window w, Atom clipboard, const char *path,
|
||||
char **text, size_t *len, ino_t *inode) {
|
||||
int fd = open(path, O_RDONLY | O_CLOEXEC | O_NOFOLLOW);
|
||||
if (fd < 0) return 0;
|
||||
struct stat st;
|
||||
if (fstat(fd, &st) || !S_ISREG(st.st_mode) || st.st_ino == *inode) { close(fd); return 0; }
|
||||
*inode = st.st_ino;
|
||||
if (st.st_size < 0 || st.st_size > MAX_TEXT) {
|
||||
fprintf(stderr, "== clipboard: text exceeds %d bytes, not pasted\n", MAX_TEXT);
|
||||
if (XGetSelectionOwner(d, clipboard) == w) XSetSelectionOwner(d, clipboard, 0, 0);
|
||||
XFlush(d);
|
||||
free(*text); *text = NULL; *len = 0;
|
||||
close(fd); return 0;
|
||||
}
|
||||
char *copy = malloc((size_t)st.st_size + 1);
|
||||
if (!copy) { close(fd); return 0; }
|
||||
size_t got = 0;
|
||||
while (got < (size_t)st.st_size) {
|
||||
ssize_t n = read(fd, copy + got, (size_t)st.st_size - got);
|
||||
if (n > 0) got += n;
|
||||
else if (n < 0 && errno == EINTR) continue;
|
||||
else break;
|
||||
}
|
||||
close(fd);
|
||||
if (got != (size_t)st.st_size) { free(copy); return 0; }
|
||||
copy[got] = 0;
|
||||
free(*text); *text = copy; *len = got;
|
||||
if (got) XSetSelectionOwner(d, clipboard, w, 0);
|
||||
else if (XGetSelectionOwner(d, clipboard) == w) XSetSelectionOwner(d, clipboard, 0, 0);
|
||||
XFlush(d);
|
||||
fprintf(stderr, "== clipboard: Android text available in Xwayland (%zu bytes)\n", got);
|
||||
return 1;
|
||||
}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
if (argc != 2 || !getenv("DISPLAY")) return 1;
|
||||
pid_t parent_pid = getppid();
|
||||
if (parent_pid == 1 || prctl(PR_SET_PDEATHSIG, SIGTERM) || getppid() != parent_pid) return 1;
|
||||
void *lib = dlopen("libX11.so.6", RTLD_NOW | RTLD_LOCAL);
|
||||
if (!lib) { fprintf(stderr, "== clipboard: libX11 unavailable\n"); return 1; }
|
||||
#define LOAD(name) do { *(void **)(&name) = dlsym(lib, #name); if (!name) return 1; } while (0)
|
||||
LOAD(XOpenDisplay); LOAD(XDefaultRootWindow); LOAD(XCreateSimpleWindow); LOAD(XInternAtom);
|
||||
LOAD(XSetSelectionOwner); LOAD(XGetSelectionOwner); LOAD(XChangeProperty); LOAD(XSendEvent);
|
||||
LOAD(XPending); LOAD(XNextEvent); LOAD(XFlush); LOAD(XConnectionNumber); LOAD(XCloseDisplay);
|
||||
LOAD(XSetErrorHandler);
|
||||
Display *d = XOpenDisplay(NULL);
|
||||
if (!d) { fprintf(stderr, "== clipboard: cannot open Xwayland\n"); return 1; }
|
||||
XSetErrorHandler(ignore_x_error); /* A paste requester can close its window at any time. */
|
||||
Window w = XCreateSimpleWindow(d, XDefaultRootWindow(d), 0, 0, 1, 1, 0, 0, 0);
|
||||
Atom clipboard = XInternAtom(d, "CLIPBOARD", 0);
|
||||
Atom targets = XInternAtom(d, "TARGETS", 0), utf8 = XInternAtom(d, "UTF8_STRING", 0);
|
||||
Atom plain = XInternAtom(d, "text/plain;charset=utf-8", 0), text_atom = XInternAtom(d, "TEXT", 0);
|
||||
Atom string = XInternAtom(d, "STRING", 0);
|
||||
char parent[PATH_MAX];
|
||||
if (strlen(argv[1]) >= sizeof(parent)) return 1;
|
||||
strcpy(parent, argv[1]); char *slash = strrchr(parent, '/');
|
||||
if (!slash) return 1;
|
||||
*slash = 0;
|
||||
int watch = inotify_init1(IN_CLOEXEC | IN_NONBLOCK);
|
||||
if (watch < 0 || inotify_add_watch(watch, parent, IN_MOVED_TO | IN_CLOSE_WRITE) < 0) return 1;
|
||||
char *text = NULL; size_t len = 0; ino_t inode = 0;
|
||||
refresh(d, w, clipboard, argv[1], &text, &len, &inode);
|
||||
struct pollfd fds[] = {{XConnectionNumber(d), POLLIN, 0}, {watch, POLLIN, 0}};
|
||||
for (;;) {
|
||||
while (XPending(d)) {
|
||||
Event e; XNextEvent(d, &e);
|
||||
if (e.type != 30) continue; /* SelectionRequest */
|
||||
SelectionRequest *r = &e.request;
|
||||
Atom property = r->property ? r->property : r->target;
|
||||
Event reply = {0};
|
||||
reply.selection = (SelectionNotify){31, 0, 1, d, r->requestor, r->selection, r->target, 0, r->time};
|
||||
if (r->selection == clipboard && text && len) {
|
||||
size_t ascii; for (ascii = 0; ascii < len && (unsigned char)text[ascii] < 128; ascii++) {}
|
||||
if (r->target == targets) {
|
||||
Atom supported[] = {targets, utf8, plain, text_atom, string};
|
||||
XChangeProperty(d, r->requestor, property, 4 /* XA_ATOM */, 32, 0,
|
||||
(const unsigned char *)supported, ascii == len ? 5 : 4);
|
||||
reply.selection.property = property;
|
||||
} else if (r->target == utf8 || r->target == plain || r->target == text_atom) {
|
||||
XChangeProperty(d, r->requestor, property, utf8, 8, 0, (const unsigned char *)text, (int)len);
|
||||
reply.selection.property = property;
|
||||
} else if (r->target == string) {
|
||||
/* STRING is Latin-1. Offer it only for ASCII rather than corrupt UTF-8. */
|
||||
if (ascii == len) {
|
||||
XChangeProperty(d, r->requestor, property, string, 8, 0, (const unsigned char *)text, (int)len);
|
||||
reply.selection.property = property;
|
||||
}
|
||||
}
|
||||
}
|
||||
XSendEvent(d, r->requestor, 0, 0, &reply); XFlush(d);
|
||||
}
|
||||
if (poll(fds, 2, -1) < 0) { if (errno == EINTR) continue; break; }
|
||||
if (fds[0].revents & (POLLERR | POLLHUP | POLLNVAL)) break;
|
||||
if (fds[1].revents & POLLIN) {
|
||||
char events[4096]; while (read(watch, events, sizeof(events)) > 0) {}
|
||||
refresh(d, w, clipboard, argv[1], &text, &len, &inode);
|
||||
}
|
||||
}
|
||||
free(text); close(watch); XCloseDisplay(d); dlclose(lib);
|
||||
return 0;
|
||||
}
|
||||
@@ -119,17 +119,6 @@ export BL_DESKTOP=1
|
||||
ln -sf /usr/local/bin/bannerlator-steam-launch /usr/local/bin/steamdeck-steam 2>/dev/null
|
||||
ln -sf /usr/local/bin/bannerlator-steam-shim /usr/local/bin/steam 2>/dev/null
|
||||
python3 /usr/local/bin/bannerlator-desktop-games 2>&1 | sed 's/^/[games] /'
|
||||
# EXPERIMENT: Valve's x86-64 client under FEX (bannerlator-steam-x64), in a terminal so its
|
||||
# first-run downloads show. Not a Game entry, so droiddeck-desktop-gpu leaves its Exec alone.
|
||||
cat > /usr/share/applications/droiddeck-steam-x64.desktop <<'ENTRY'
|
||||
[Desktop Entry]
|
||||
Type=Application
|
||||
Name=Steam x86-64 (FEX, experimental)
|
||||
Comment=Valve's x86-64 Linux client under FEX, in its own home with its own login
|
||||
Exec=qterminal -e /usr/local/bin/bannerlator-steam-x64
|
||||
Icon=steam
|
||||
Categories=System;
|
||||
ENTRY
|
||||
# Player 1 on the controller in every emulator that has no profile of its own yet - now, and again
|
||||
# every half minute: an emulator started for the first time writes its own config, which is then
|
||||
# given the controller for its next start without waiting for the next desktop.
|
||||
|
||||
+154
@@ -0,0 +1,154 @@
|
||||
#!/usr/bin/python3
|
||||
"""Steam's login1 sleep notifications, backed by DroidDeck's session pause.
|
||||
|
||||
Android owns device power. Suspend here pauses the guest through SessionService;
|
||||
the app's Resume action thaws it and completes PrepareForSleep(false). Steam
|
||||
must see this service before startup or it can stay black after its idle timer.
|
||||
"""
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import uuid
|
||||
|
||||
import gi
|
||||
|
||||
gi.require_version("Gio", "2.0")
|
||||
from gi.repository import Gio, GLib # noqa: E402
|
||||
|
||||
NAME = "org.freedesktop.login1"
|
||||
ROOT = "/org/freedesktop/login1"
|
||||
INTERFACE = NAME + ".Manager"
|
||||
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>
|
||||
<property name="PreparingForSleep" type="b" access="read"/>
|
||||
<signal name="PrepareForSleep"><arg type="b"/></signal>
|
||||
</interface>
|
||||
</node>
|
||||
"""
|
||||
|
||||
|
||||
class LoginManager:
|
||||
def __init__(self, bus, directory):
|
||||
self.bus = bus
|
||||
self.directory = Path(directory)
|
||||
self.request = self.directory / "steam-sleep"
|
||||
self.state = self.directory / "steam-sleep-state"
|
||||
self.pending = None
|
||||
self.timeout = None
|
||||
info = Gio.DBusNodeInfo.new_for_xml(INTROSPECTION).interfaces[0]
|
||||
self.registration = bus.register_object(ROOT, info, self.method, self.property, None)
|
||||
self.monitor = Gio.File.new_for_path(str(self.directory)).monitor_directory(Gio.FileMonitorFlags.NONE, None)
|
||||
self.monitor.connect("changed", self.changed)
|
||||
|
||||
def property(self, connection, sender, path, interface, name):
|
||||
if name == "PreparingForSleep":
|
||||
return GLib.Variant("b", self.pending is not None)
|
||||
return None
|
||||
|
||||
def notify(self, sleeping):
|
||||
self.bus.emit_signal(None, ROOT, INTERFACE, "PrepareForSleep", GLib.Variant("(b)", (sleeping,)))
|
||||
self.bus.emit_signal(None, ROOT, "org.freedesktop.DBus.Properties", "PropertiesChanged",
|
||||
GLib.Variant("(sa{sv}as)", (INTERFACE, {
|
||||
"PreparingForSleep": GLib.Variant("b", sleeping),
|
||||
}, [])))
|
||||
print("== login1: " + ("pausing the session" if sleeping else "session resumed"), flush=True)
|
||||
|
||||
def method(self, connection, sender, path, interface, name, args, reply):
|
||||
if name == "CanSuspend":
|
||||
reply.return_value(GLib.Variant("(s)", ("yes",)))
|
||||
elif name in ("Suspend", "SuspendWithFlags"):
|
||||
if self.pending:
|
||||
reply.return_dbus_error(NAME + ".OperationInProgress", "The session is already pausing")
|
||||
return
|
||||
self.pending = uuid.uuid4().hex
|
||||
self.notify(True)
|
||||
reply.return_value(None)
|
||||
# Flush the signal and method reply without blocking this D-Bus callback. Once both are
|
||||
# on the wire, publishing the request lets the host safely freeze this service.
|
||||
self.bus.flush_async(None, self.publish_after_flush, None)
|
||||
|
||||
def publish_after_flush(self, connection, result, _data):
|
||||
try:
|
||||
connection.flush_finish(result)
|
||||
except GLib.Error as error:
|
||||
print("== login1: cannot complete suspend handshake: " + str(error), file=sys.stderr)
|
||||
self.resume()
|
||||
return
|
||||
self.publish()
|
||||
|
||||
def publish(self):
|
||||
try:
|
||||
staged = self.request.with_suffix(".tmp")
|
||||
staged.write_text(self.pending + "\n")
|
||||
staged.replace(self.request)
|
||||
self.timeout = GLib.timeout_add_seconds(5, self.check_ack)
|
||||
except OSError as error:
|
||||
print("== login1: cannot request pause: " + str(error), file=sys.stderr)
|
||||
self.resume()
|
||||
return False
|
||||
|
||||
def changed(self, monitor, file, other, event):
|
||||
if file.get_basename() == self.state.name or (other and other.get_basename() == self.state.name):
|
||||
self.check_state()
|
||||
|
||||
def read_state(self):
|
||||
try:
|
||||
return self.state.read_text().strip()
|
||||
except OSError:
|
||||
return ""
|
||||
|
||||
def check_state(self):
|
||||
if self.pending and self.read_state() == self.pending + ":awake":
|
||||
self.resume()
|
||||
|
||||
def check_ack(self):
|
||||
self.timeout = None
|
||||
if self.pending and self.read_state() != self.pending + ":paused":
|
||||
# A missing host or a failed freeze must not strand Steam in black.
|
||||
self.request.unlink(missing_ok=True)
|
||||
self.resume()
|
||||
return False
|
||||
|
||||
def resume(self):
|
||||
if self.pending is None:
|
||||
return
|
||||
self.pending = None
|
||||
if self.timeout is not None:
|
||||
GLib.source_remove(self.timeout)
|
||||
self.timeout = None
|
||||
self.notify(False)
|
||||
|
||||
|
||||
def main():
|
||||
directory = os.environ.get("BL_LAUNCH_DIR")
|
||||
if not directory or not Path(directory).is_dir():
|
||||
sys.exit("bannerlator-login1: no DroidDeck session directory")
|
||||
ready = Path(directory) / "steam-sleep-ready"
|
||||
ready.unlink(missing_ok=True)
|
||||
loop = GLib.MainLoop()
|
||||
manager = []
|
||||
|
||||
def connected(bus, name):
|
||||
manager.append(LoginManager(bus, directory))
|
||||
|
||||
def acquired(bus, name):
|
||||
ready.write_text("ready\n")
|
||||
|
||||
def lost(bus, name):
|
||||
ready.unlink(missing_ok=True)
|
||||
loop.quit()
|
||||
|
||||
owner = Gio.bus_own_name(Gio.BusType.SYSTEM, NAME, Gio.BusNameOwnerFlags.NONE, connected, acquired, lost)
|
||||
try:
|
||||
loop.run()
|
||||
finally:
|
||||
ready.unlink(missing_ok=True)
|
||||
Gio.bus_unown_name(owner)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,20 +1,17 @@
|
||||
#!/usr/bin/python3
|
||||
# Ported from WinNative (maxjivi05, feature/wayland-gamescope e7a224ae), GPL-3.0, with thanks.
|
||||
# Renamed again for this app; the answers themselves are his.
|
||||
#
|
||||
# Answers for NetworkManager on the runtime's system bus, for the Steam client:
|
||||
# bannerlator-netmanager
|
||||
#
|
||||
# The client's network page and its connection indicator are built on NetworkManager. It asks for
|
||||
# one over the system bus as it starts, and without an answer it leaves out half of what its
|
||||
# interface then calls: Settings > Internet stops with "StartScanningForNetworks is not a function"
|
||||
# and the header shows no connection while downloads run.
|
||||
#
|
||||
# The network here is Android's: the app has no say in Wi-Fi, and nothing in this runtime could
|
||||
# scan or join one. So this reports what is true and no more - one connection that is up while
|
||||
# Android has a route out, under the address the app was given - and refuses what it cannot do.
|
||||
# Based on WinNative (maxjivi05, feature/wayland-gamescope e7a224ae), GPL-3.0.
|
||||
# Steam speaks NetworkManager; Android owns the radios, routes and connection. Export the
|
||||
# app's live snapshot through that API, including nearby Wi-Fi access points. Requests to
|
||||
# scan are handed to Android; Android settings still handle joining networks.
|
||||
import ipaddress
|
||||
import json
|
||||
import re
|
||||
import time
|
||||
import socket
|
||||
import struct
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from xml.sax.saxutils import escape
|
||||
|
||||
import gi
|
||||
|
||||
@@ -24,207 +21,401 @@ from gi.repository import Gio, GLib # noqa: E402
|
||||
NAME = "org.freedesktop.NetworkManager"
|
||||
ROOT = "/org/freedesktop/NetworkManager"
|
||||
SETTINGS = ROOT + "/Settings"
|
||||
DEVICE = ROOT + "/Devices/1"
|
||||
ACTIVE = ROOT + "/ActiveConnection/1"
|
||||
IP4 = ROOT + "/IP4Config/1"
|
||||
IP6 = ROOT + "/IP6Config/1"
|
||||
AP = ROOT + "/AccessPoint/1"
|
||||
PROFILE = SETTINGS + "/1"
|
||||
UUID = "b1d0c8e4-57f0-4c0e-9d60-77696e6e6174"
|
||||
CHECK_SECONDS = 10
|
||||
SNAPSHOT = Path("/etc/bannerlator-network.json")
|
||||
SCAN_REQUEST = Path("/etc/bannerlator-wifi-scan-request")
|
||||
OBJECT_MANAGER = "org.freedesktop.DBus.ObjectManager"
|
||||
PROPERTIES = "org.freedesktop.DBus.Properties"
|
||||
|
||||
# NetworkManager's own numbers.
|
||||
NM_STATE_DISCONNECTED, NM_STATE_CONNECTED_GLOBAL = 20, 70
|
||||
NM_CONNECTIVITY_NONE, NM_CONNECTIVITY_FULL = 1, 4
|
||||
NM_DEVICE_TYPE_ETHERNET = 1
|
||||
NM_DEVICE_STATE_DISCONNECTED, NM_DEVICE_STATE_ACTIVATED = 30, 100
|
||||
NM_ACTIVE_CONNECTION_STATE_ACTIVATED = 2
|
||||
|
||||
INTROSPECTION = """
|
||||
<node>
|
||||
<interface name="org.freedesktop.DBus.ObjectManager">
|
||||
<method name="GetManagedObjects">
|
||||
<arg type="a{oa{sa{sv}}}" direction="out"/>
|
||||
</method>
|
||||
</interface>
|
||||
<interface name="org.freedesktop.NetworkManager">
|
||||
<method name="GetPermissions"><arg type="a{ss}" direction="out"/></method>
|
||||
<method name="CheckConnectivity"><arg type="u" direction="out"/></method>
|
||||
<method name="GetDevices"><arg type="ao" direction="out"/></method>
|
||||
<method name="GetAllDevices"><arg type="ao" direction="out"/></method>
|
||||
<signal name="StateChanged"><arg type="u"/></signal>
|
||||
</interface>
|
||||
<interface name="org.freedesktop.NetworkManager.Settings.Connection">
|
||||
<method name="GetSettings"><arg type="a{sa{sv}}" direction="out"/></method>
|
||||
</interface>
|
||||
<interface name="org.freedesktop.NetworkManager.Device">
|
||||
<signal name="StateChanged"><arg type="u"/><arg type="u"/><arg type="u"/></signal>
|
||||
</interface>
|
||||
</node>
|
||||
"""
|
||||
|
||||
|
||||
def address():
|
||||
"""The address Android routes out by, or None without a route. Nothing is sent."""
|
||||
try:
|
||||
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
|
||||
s.connect(("192.0.2.1", 9))
|
||||
return s.getsockname()[0]
|
||||
except OSError:
|
||||
return None
|
||||
METHODS = {
|
||||
OBJECT_MANAGER: '''
|
||||
<method name="GetManagedObjects"><arg type="a{oa{sa{sv}}}" direction="out"/></method>
|
||||
<signal name="InterfacesAdded"><arg type="o"/><arg type="a{sa{sv}}"/></signal>
|
||||
<signal name="InterfacesRemoved"><arg type="o"/><arg type="as"/></signal>''',
|
||||
NAME: '''
|
||||
<method name="GetPermissions"><arg type="a{ss}" direction="out"/></method>
|
||||
<method name="CheckConnectivity"><arg type="u" direction="out"/></method>
|
||||
<method name="GetDevices"><arg type="ao" direction="out"/></method>
|
||||
<method name="GetAllDevices"><arg type="ao" direction="out"/></method>
|
||||
<signal name="StateChanged"><arg type="u"/></signal>''',
|
||||
NAME + ".Settings": '<method name="ListConnections"><arg type="ao" direction="out"/></method>',
|
||||
NAME + ".Settings.Connection": '<method name="GetSettings"><arg type="a{sa{sv}}" direction="out"/></method><signal name="Updated"/>',
|
||||
NAME + ".Device": '<signal name="StateChanged"><arg type="u"/><arg type="u"/><arg type="u"/></signal>',
|
||||
NAME + ".Device.Wireless": '''
|
||||
<method name="GetAccessPoints"><arg type="ao" direction="out"/></method>
|
||||
<method name="GetAllAccessPoints"><arg type="ao" direction="out"/></method>
|
||||
<method name="RequestScan"><arg type="a{sv}" direction="in"/></method>
|
||||
<signal name="AccessPointAdded"><arg type="o"/></signal>
|
||||
<signal name="AccessPointRemoved"><arg type="o"/></signal>''',
|
||||
}
|
||||
|
||||
|
||||
def v(signature, value):
|
||||
return GLib.Variant(signature, value)
|
||||
|
||||
|
||||
def objects(ip):
|
||||
"""Every object NetworkManager would export, as its ObjectManager describes them."""
|
||||
up = ip is not None
|
||||
def read_snapshot():
|
||||
# Atomic replacement by the app means we never see a partially written handover.
|
||||
try:
|
||||
state = json.loads(SNAPSHOT.read_text())
|
||||
if not isinstance(state, dict) or not isinstance(state.get("connected"), bool):
|
||||
return None
|
||||
return state
|
||||
except (OSError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def legacy_snapshot():
|
||||
# Older APKs do not publish transport metadata. Never guess Wi-Fi from an interface name.
|
||||
try:
|
||||
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock:
|
||||
sock.connect(("192.0.2.1", 9))
|
||||
ip = sock.getsockname()[0]
|
||||
return {"connected": True, "transport": "ethernet", "addresses": [{"address": ip, "prefix": 32}]}
|
||||
except OSError:
|
||||
return {"connected": False, "transport": "none"}
|
||||
|
||||
|
||||
def connection_type(state):
|
||||
return {"wifi": "802-11-wireless", "cellular": "gsm", "ethernet": "802-3-ethernet",
|
||||
"vpn": "tun"}.get(state.get("transport"), "generic")
|
||||
|
||||
|
||||
def device_path(state):
|
||||
transport = state.get("transport", "none")
|
||||
if not state["connected"] and state.get("wifiEnabled"):
|
||||
transport = "wifi"
|
||||
return ROOT + "/Devices/" + {"wifi": "Wifi", "cellular": "Cellular", "ethernet": "Ethernet",
|
||||
"vpn": "Vpn"}.get(transport, "Android")
|
||||
|
||||
|
||||
def connection_name(state):
|
||||
return {"wifi": state.get("ssid") or "Wi-Fi", "cellular": "Cellular", "ethernet": "Ethernet",
|
||||
"vpn": "VPN"}.get(state.get("transport"), "Android")
|
||||
|
||||
|
||||
def connectivity(state):
|
||||
if not state["connected"]:
|
||||
return 1 # NONE
|
||||
if state.get("validated"):
|
||||
return 4 # FULL
|
||||
return 2 if state.get("captivePortal") else 3 # PORTAL / LIMITED
|
||||
|
||||
|
||||
def metered(state):
|
||||
return {True: 1, False: 2}.get(state.get("metered"), 0)
|
||||
|
||||
|
||||
def family_addresses(state, version):
|
||||
return [entry for entry in state.get("addresses", [])
|
||||
if ipaddress.ip_address(entry["address"]).version == version]
|
||||
|
||||
|
||||
def ip_config(state, version):
|
||||
entries = family_addresses(state, version)
|
||||
gateways = [ip for ip in state.get("gateways", []) if ipaddress.ip_address(ip).version == version]
|
||||
dns = [ip for ip in state.get("dns", []) if ipaddress.ip_address(ip).version == version]
|
||||
gateway = gateways[0] if gateways else ""
|
||||
props = {
|
||||
"AddressData": v("aa{sv}", [{"address": v("s", a["address"]), "prefix": v("u", a["prefix"])} for a in entries]),
|
||||
"Gateway": v("s", gateway), "RouteData": v("aa{sv}", []),
|
||||
"Domains": v("as", []), "Searches": v("as", []), "DnsOptions": v("as", []), "DnsPriority": v("i", 0),
|
||||
}
|
||||
if version == 4:
|
||||
native = lambda ip: struct.unpack("=I", socket.inet_aton(ip))[0]
|
||||
props.update({
|
||||
"Addresses": v("aau", [[native(a["address"]), a["prefix"], native(gateway) if gateway else 0] for a in entries]),
|
||||
"Routes": v("aau", []),
|
||||
"NameserverData": v("aa{sv}", [{"address": v("s", ip)} for ip in dns]),
|
||||
"Nameservers": v("au", [native(ip) for ip in dns]),
|
||||
"WinsServerData": v("as", []), "WinsServers": v("au", []),
|
||||
})
|
||||
else:
|
||||
packed = lambda ip: list(socket.inet_pton(socket.AF_INET6, ip))
|
||||
props.update({
|
||||
"Addresses": v("a(ayuay)", [(packed(a["address"]), a["prefix"], packed(gateway) if gateway else [0] * 16) for a in entries]),
|
||||
"Routes": v("a(ayuayu)", []), "Nameservers": v("aay", [packed(ip) for ip in dns]),
|
||||
})
|
||||
return props
|
||||
|
||||
|
||||
def ap_path(bssid):
|
||||
if bssid and re.fullmatch(r"(?:[0-9a-fA-F]{2}:){5}[0-9a-fA-F]{2}", bssid):
|
||||
return ROOT + "/AccessPoint/" + bssid.replace(":", "").lower()
|
||||
return AP
|
||||
|
||||
|
||||
def active_ap(state):
|
||||
return ap_path(state.get("bssid")) if state["connected"] and state.get("transport") == "wifi" else "/"
|
||||
|
||||
|
||||
def ap_security(capabilities):
|
||||
# NetworkManager's cipher/key-management flags, from Android's beacon capabilities.
|
||||
wpa = rsn = 0
|
||||
for group in re.findall(r"\[([^]]+)\]", capabilities.upper()):
|
||||
flags = 0
|
||||
if "CCMP" in group:
|
||||
flags |= 0x08 | 0x80
|
||||
if "TKIP" in group:
|
||||
flags |= 0x04 | 0x40
|
||||
if "PSK" in group:
|
||||
flags |= 0x100
|
||||
if "EAP" in group:
|
||||
flags |= 0x200
|
||||
if "SAE" in group:
|
||||
flags |= 0x400
|
||||
if "OWE" in group:
|
||||
flags |= 0x800
|
||||
if "WPA2" in group or "RSN" in group or "SAE" in group or "OWE" in group:
|
||||
rsn |= flags
|
||||
elif "WPA" in group:
|
||||
wpa |= flags
|
||||
privacy = int(bool(wpa or rsn or "WEP" in capabilities.upper()))
|
||||
return privacy, wpa, rsn
|
||||
|
||||
|
||||
def access_points(state):
|
||||
result = {ap_path(ap.get("bssid")): dict(ap) for ap in state.get("accessPoints", []) if ap.get("ssid")}
|
||||
if active_ap(state) != "/":
|
||||
current = result.setdefault(active_ap(state), {})
|
||||
for key in ("ssid", "bssid", "strength", "frequency", "bitrate"):
|
||||
if key in state:
|
||||
current[key] = state[key]
|
||||
current.setdefault("ssid", "Wi-Fi")
|
||||
return result
|
||||
|
||||
|
||||
def ap_properties(ap):
|
||||
privacy, wpa, rsn = ap_security(ap.get("capabilities", ""))
|
||||
return {
|
||||
"Flags": v("u", privacy), "WpaFlags": v("u", wpa), "RsnFlags": v("u", rsn),
|
||||
"Ssid": v("ay", list(ap["ssid"].encode("utf-8"))),
|
||||
"Frequency": v("u", ap.get("frequency", 0)), "HwAddress": v("s", ap.get("bssid", "")), "Mode": v("u", 2),
|
||||
"MaxBitrate": v("u", ap.get("bitrate", 0)),
|
||||
"Strength": v("y", max(0, min(100, ap.get("strength", 0)))), "LastSeen": v("i", ap.get("lastSeen", -1)),
|
||||
}
|
||||
|
||||
|
||||
def objects(state):
|
||||
device = device_path(state)
|
||||
aps = access_points(state)
|
||||
current_ap = active_ap(state)
|
||||
up = state["connected"]
|
||||
transport = state.get("transport", "none")
|
||||
wifi = transport == "wifi" or (not up and state.get("wifiEnabled", False))
|
||||
cellular = transport == "cellular"
|
||||
kind = connection_type(state)
|
||||
ip4 = up and bool(family_addresses(state, 4))
|
||||
ip6 = up and bool(family_addresses(state, 6))
|
||||
device_state = 100 if up else 30
|
||||
found = {
|
||||
ROOT: {NAME: {
|
||||
"Devices": v("ao", [DEVICE]),
|
||||
"AllDevices": v("ao", [DEVICE]),
|
||||
"Devices": v("ao", [device]), "AllDevices": v("ao", [device]),
|
||||
"ActiveConnections": v("ao", [ACTIVE] if up else []),
|
||||
"PrimaryConnection": v("o", ACTIVE if up else "/"),
|
||||
"PrimaryConnectionType": v("s", "802-3-ethernet" if up else ""),
|
||||
"ActivatingConnection": v("o", "/"),
|
||||
"PrimaryConnectionType": v("s", kind if up else ""), "ActivatingConnection": v("o", "/"),
|
||||
"NetworkingEnabled": v("b", True),
|
||||
"WirelessEnabled": v("b", False),
|
||||
"WirelessHardwareEnabled": v("b", False),
|
||||
"WwanEnabled": v("b", False),
|
||||
"WwanHardwareEnabled": v("b", False),
|
||||
"Startup": v("b", False),
|
||||
"Version": v("s", "1.46.0"),
|
||||
"State": v("u", NM_STATE_CONNECTED_GLOBAL if up else NM_STATE_DISCONNECTED),
|
||||
"Connectivity": v("u", NM_CONNECTIVITY_FULL if up else NM_CONNECTIVITY_NONE),
|
||||
"ConnectivityCheckAvailable": v("b", False),
|
||||
"ConnectivityCheckEnabled": v("b", False),
|
||||
"Metered": v("u", 0),
|
||||
"WirelessEnabled": v("b", bool(state.get("wifiEnabled", wifi))),
|
||||
"WirelessHardwareEnabled": v("b", bool(state.get("wifiEnabled", wifi))),
|
||||
"WwanEnabled": v("b", cellular), "WwanHardwareEnabled": v("b", cellular),
|
||||
"Startup": v("b", False), "Version": v("s", "1.46.0"),
|
||||
"State": v("u", (70 if state.get("validated") else 60) if up else 20),
|
||||
"Connectivity": v("u", connectivity(state)),
|
||||
"ConnectivityCheckAvailable": v("b", False), "ConnectivityCheckEnabled": v("b", False),
|
||||
"Metered": v("u", metered(state)),
|
||||
}},
|
||||
SETTINGS: {NAME + ".Settings": {
|
||||
"Connections": v("ao", [PROFILE]),
|
||||
"Hostname": v("s", socket.gethostname()),
|
||||
"CanModify": v("b", False),
|
||||
"Connections": v("ao", [PROFILE]), "Hostname": v("s", socket.gethostname()), "CanModify": v("b", False),
|
||||
}},
|
||||
PROFILE: {NAME + ".Settings.Connection": {
|
||||
"Unsaved": v("b", False),
|
||||
"Flags": v("u", 0),
|
||||
"Filename": v("s", ""),
|
||||
"Unsaved": v("b", True), "Flags": v("u", 0), "Filename": v("s", ""),
|
||||
}},
|
||||
device: {NAME + ".Device": {
|
||||
"Interface": v("s", state.get("interface", "android")),
|
||||
"IpInterface": v("s", state.get("interface", "android") if up else ""),
|
||||
"Driver": v("s", "android"),
|
||||
"DeviceType": v("u", 2 if wifi else 8 if cellular else {"ethernet": 1, "vpn": 16}.get(transport, 14)),
|
||||
"State": v("u", device_state), "StateReason": v("(uu)", (device_state, 0)),
|
||||
"ActiveConnection": v("o", ACTIVE if up else "/"),
|
||||
"Ip4Config": v("o", IP4 if ip4 else "/"), "Ip6Config": v("o", IP6 if ip6 else "/"),
|
||||
"Dhcp4Config": v("o", "/"), "Dhcp6Config": v("o", "/"),
|
||||
"AvailableConnections": v("ao", [PROFILE]), "Managed": v("b", True),
|
||||
"Autoconnect": v("b", False), "Real": v("b", True), "Capabilities": v("u", 1),
|
||||
"Mtu": v("u", state.get("mtu", 1500)), "HwAddress": v("s", ""), "Metered": v("u", metered(state)),
|
||||
}},
|
||||
DEVICE: {
|
||||
NAME + ".Device": {
|
||||
"Interface": v("s", "android"),
|
||||
"IpInterface": v("s", "android" if up else ""),
|
||||
"Driver": v("s", "android"),
|
||||
"DeviceType": v("u", NM_DEVICE_TYPE_ETHERNET),
|
||||
"State": v("u", NM_DEVICE_STATE_ACTIVATED if up else NM_DEVICE_STATE_DISCONNECTED),
|
||||
"StateReason": v("(uu)", (NM_DEVICE_STATE_ACTIVATED if up else NM_DEVICE_STATE_DISCONNECTED, 0)),
|
||||
"ActiveConnection": v("o", ACTIVE if up else "/"),
|
||||
"Ip4Config": v("o", IP4 if up else "/"),
|
||||
"Ip6Config": v("o", "/"),
|
||||
"Dhcp4Config": v("o", "/"),
|
||||
"Dhcp6Config": v("o", "/"),
|
||||
"AvailableConnections": v("ao", [PROFILE]),
|
||||
"Managed": v("b", True),
|
||||
"Autoconnect": v("b", True),
|
||||
"Real": v("b", True),
|
||||
"Capabilities": v("u", 1),
|
||||
"Mtu": v("u", 1500),
|
||||
"HwAddress": v("s", ""),
|
||||
},
|
||||
NAME + ".Device.Wired": {
|
||||
"HwAddress": v("s", ""),
|
||||
"PermHwAddress": v("s", ""),
|
||||
"Speed": v("u", 0),
|
||||
"Carrier": v("b", up),
|
||||
},
|
||||
},
|
||||
}
|
||||
if wifi:
|
||||
found[device][NAME + ".Device.Wireless"] = {
|
||||
"HwAddress": v("s", ""), "PermHwAddress": v("s", ""), "Mode": v("u", 2),
|
||||
"Bitrate": v("u", state.get("bitrate", 0)), "WirelessCapabilities": v("u", 0),
|
||||
"AccessPoints": v("ao", list(aps)), "ActiveAccessPoint": v("o", current_ap),
|
||||
"LastScan": v("x", state.get("lastScan", -1)),
|
||||
}
|
||||
for path, ap in aps.items():
|
||||
found[path] = {NAME + ".AccessPoint": ap_properties(ap)}
|
||||
elif cellular:
|
||||
found[device][NAME + ".Device.Modem"] = {
|
||||
"ModemCapabilities": v("u", 4), "CurrentCapabilities": v("u", 4),
|
||||
"DeviceId": v("s", "android"), "OperatorCode": v("s", ""), "Apn": v("s", ""),
|
||||
}
|
||||
elif transport == "ethernet":
|
||||
found[device][NAME + ".Device.Wired"] = {
|
||||
"HwAddress": v("s", ""), "PermHwAddress": v("s", ""), "Speed": v("u", 0), "Carrier": v("b", up),
|
||||
}
|
||||
if up:
|
||||
found[ACTIVE] = {NAME + ".Connection.Active": {
|
||||
"Connection": v("o", PROFILE),
|
||||
"SpecificObject": v("o", "/"),
|
||||
"Id": v("s", "Android"),
|
||||
"Uuid": v("s", UUID),
|
||||
"Type": v("s", "802-3-ethernet"),
|
||||
"Devices": v("ao", [DEVICE]),
|
||||
"State": v("u", NM_ACTIVE_CONNECTION_STATE_ACTIVATED),
|
||||
"StateFlags": v("u", 0),
|
||||
"Default": v("b", True),
|
||||
"Ip4Config": v("o", IP4),
|
||||
"Dhcp4Config": v("o", "/"),
|
||||
"Default6": v("b", False),
|
||||
"Ip6Config": v("o", "/"),
|
||||
"Dhcp6Config": v("o", "/"),
|
||||
"Vpn": v("b", False),
|
||||
"Master": v("o", "/"),
|
||||
}}
|
||||
found[IP4] = {NAME + ".IP4Config": {
|
||||
# The one address the app can see; the prefix says only that much is known.
|
||||
"AddressData": v("aa{sv}", [{"address": v("s", ip), "prefix": v("u", 32)}]),
|
||||
"Addresses": v("aau", []),
|
||||
"Gateway": v("s", ""),
|
||||
"RouteData": v("aa{sv}", []),
|
||||
"Routes": v("aau", []),
|
||||
"NameserverData": v("aa{sv}", []),
|
||||
"Nameservers": v("au", []),
|
||||
"Domains": v("as", []),
|
||||
"Searches": v("as", []),
|
||||
"DnsOptions": v("as", []),
|
||||
"DnsPriority": v("i", 0),
|
||||
"WinsServerData": v("as", []),
|
||||
"WinsServers": v("au", []),
|
||||
"Connection": v("o", PROFILE), "SpecificObject": v("o", current_ap),
|
||||
"Id": v("s", connection_name(state)), "Uuid": v("s", UUID), "Type": v("s", kind),
|
||||
"Devices": v("ao", [device]), "State": v("u", 2), "StateFlags": v("u", 0),
|
||||
"Default": v("b", ip4), "Default6": v("b", ip6),
|
||||
"Ip4Config": v("o", IP4 if ip4 else "/"), "Ip6Config": v("o", IP6 if ip6 else "/"),
|
||||
"Dhcp4Config": v("o", "/"), "Dhcp6Config": v("o", "/"), "Vpn": v("b", False), "Master": v("o", "/"),
|
||||
}}
|
||||
for version, present, path in ((4, ip4, IP4), (6, ip6, IP6)):
|
||||
if present:
|
||||
found[path] = {NAME + f".IP{version}Config": ip_config(state, version)}
|
||||
if up and not wifi and state.get("wifiEnabled"):
|
||||
# Android can keep its Wi-Fi radio available while cellular/VPN is the default route.
|
||||
wireless = objects(dict(state, connected=False, transport="none",
|
||||
interface=state.get("wifiInterface", "wlan0"), metered=None))
|
||||
wifi_device = ROOT + "/Devices/Wifi"
|
||||
found[wifi_device] = wireless[wifi_device]
|
||||
found[wifi_device][NAME + ".Device"]["AvailableConnections"] = v("ao", [])
|
||||
for path, interfaces in wireless.items():
|
||||
if NAME + ".AccessPoint" in interfaces:
|
||||
found[path] = interfaces
|
||||
found[ROOT][NAME]["Devices"] = v("ao", [device, wifi_device])
|
||||
found[ROOT][NAME]["AllDevices"] = v("ao", [device, wifi_device])
|
||||
return found
|
||||
|
||||
|
||||
def settings(state):
|
||||
result = {"connection": {
|
||||
"id": v("s", connection_name(state)), "uuid": v("s", UUID), "type": v("s", connection_type(state)),
|
||||
"interface-name": v("s", state.get("interface", "android")), "metered": v("u", metered(state)),
|
||||
}}
|
||||
if state.get("transport") == "wifi":
|
||||
result["802-11-wireless"] = {
|
||||
"ssid": v("ay", list((state.get("ssid") or "Wi-Fi").encode("utf-8"))), "mode": v("s", "infrastructure"),
|
||||
}
|
||||
elif state.get("transport") == "cellular":
|
||||
result["gsm"] = {} # Android owns the SIM/APN; no credentials are exported.
|
||||
return result
|
||||
|
||||
|
||||
def interface_info(interface, values):
|
||||
# Register properties on the actual objects as well as returning ObjectManager snapshots.
|
||||
# Steam/libnm also use Properties.Get/GetAll and introspect the wireless methods.
|
||||
props = "".join(f'<property name="{escape(key)}" type="{value.get_type_string()}" access="read"/>'
|
||||
for key, value in values.items())
|
||||
node = Gio.DBusNodeInfo.new_for_xml(f'<node><interface name="{interface}">{METHODS.get(interface, "")}{props}</interface></node>')
|
||||
return node.interfaces[0]
|
||||
|
||||
|
||||
class NetworkManager:
|
||||
def __init__(self, bus):
|
||||
self.bus = bus
|
||||
self.ip = address()
|
||||
node = Gio.DBusNodeInfo.new_for_xml(INTROSPECTION)
|
||||
manager, root, profile, device = node.interfaces
|
||||
for path, interface in (("/org/freedesktop", manager), (ROOT, root), (PROFILE, profile), (DEVICE, device)):
|
||||
bus.register_object_with_closures2(path, interface, self.call, None, None)
|
||||
GLib.timeout_add_seconds(CHECK_SECONDS, self.check)
|
||||
self.state = read_snapshot() or legacy_snapshot()
|
||||
self.objects = objects(self.state)
|
||||
self.registrations = {}
|
||||
for path in ("/org/freedesktop", ROOT):
|
||||
bus.register_object(path, interface_info(OBJECT_MANAGER, {}), self.call, None, None)
|
||||
self.register(self.objects)
|
||||
GLib.timeout_add_seconds(1, self.check)
|
||||
|
||||
def register(self, found):
|
||||
wanted = {(path, interface) for path, interfaces in found.items() for interface in interfaces}
|
||||
for key in self.registrations.keys() - wanted:
|
||||
self.bus.unregister_object(self.registrations.pop(key))
|
||||
for path, interface in wanted - self.registrations.keys():
|
||||
self.registrations[(path, interface)] = self.bus.register_object(
|
||||
path, interface_info(interface, found[path][interface]), self.call, self.get_property, None)
|
||||
|
||||
def get_property(self, bus, sender, path, interface, name):
|
||||
return self.objects.get(path, {}).get(interface, {}).get(name)
|
||||
|
||||
def call(self, bus, sender, path, interface, method, args, invocation):
|
||||
if method == "GetManagedObjects":
|
||||
invocation.return_value(v("(a{oa{sa{sv}}})", (objects(self.ip),)))
|
||||
invocation.return_value(v("(a{oa{sa{sv}}})", (self.objects,)))
|
||||
elif method == "GetPermissions":
|
||||
invocation.return_value(v("(a{ss})", ({},)))
|
||||
elif method == "CheckConnectivity":
|
||||
self.check()
|
||||
invocation.return_value(v("(u)", (NM_CONNECTIVITY_FULL if self.ip else NM_CONNECTIVITY_NONE,)))
|
||||
invocation.return_value(v("(u)", (connectivity(self.state),)))
|
||||
elif method == "GetSettings":
|
||||
# The name the client shows the connection under.
|
||||
invocation.return_value(v("(a{sa{sv}})", ({"connection": {
|
||||
"id": v("s", "Android"), "uuid": v("s", UUID), "type": v("s", "802-3-ethernet")}},)))
|
||||
invocation.return_value(v("(a{sa{sv}})", (settings(self.state),)))
|
||||
elif method == "ListConnections":
|
||||
invocation.return_value(v("(ao)", ([PROFILE],)))
|
||||
elif method in ("GetAccessPoints", "GetAllAccessPoints"):
|
||||
invocation.return_value(v("(ao)", (self.objects[path][NAME + ".Device.Wireless"]["AccessPoints"].unpack(),)))
|
||||
elif method == "RequestScan":
|
||||
if self.state.get("scanAllowed") is False:
|
||||
invocation.return_dbus_error(NAME + ".Device.NotAllowed", "Wi-Fi discovery requires Android Location permission and enabled Location services")
|
||||
return
|
||||
try:
|
||||
SCAN_REQUEST.write_text(str(time.monotonic_ns()))
|
||||
except OSError:
|
||||
invocation.return_dbus_error(NAME + ".Device.Failed", "Could not request an Android Wi-Fi scan")
|
||||
return
|
||||
self.check()
|
||||
invocation.return_value(v("()", ()))
|
||||
elif method in ("GetDevices", "GetAllDevices"):
|
||||
invocation.return_value(v("(ao)", (self.objects[ROOT][NAME]["Devices"].unpack(),)))
|
||||
else:
|
||||
invocation.return_value(v("(ao)", ([DEVICE],)))
|
||||
invocation.return_dbus_error(NAME + ".NotSupported", "Manage this connection in Android settings")
|
||||
|
||||
def check(self):
|
||||
"""Tells the bus when Android gains or loses its route, as NetworkManager would."""
|
||||
ip = address()
|
||||
if (ip is None) != (self.ip is None) or (ip and ip != self.ip):
|
||||
before, after = objects(self.ip), objects(ip)
|
||||
self.ip = ip
|
||||
for path in before.keys() - after.keys():
|
||||
self.announce("InterfacesRemoved", path, v("(oas)", (path, list(before[path]))))
|
||||
for path in after.keys() - before.keys():
|
||||
self.announce("InterfacesAdded", path, v("(oa{sa{sv}})", (path, after[path])))
|
||||
for path in after.keys() & before.keys():
|
||||
for interface, values in after[path].items():
|
||||
self.bus.emit_signal(None, path, "org.freedesktop.DBus.Properties", "PropertiesChanged",
|
||||
v("(sa{sv}as)", (interface, values, [])))
|
||||
state = after[ROOT][NAME]["State"].unpack()
|
||||
device = after[DEVICE][NAME + ".Device"]["State"].unpack()
|
||||
was = before[DEVICE][NAME + ".Device"]["State"].unpack()
|
||||
self.bus.emit_signal(None, ROOT, NAME, "StateChanged", v("(u)", (state,)))
|
||||
self.bus.emit_signal(None, DEVICE, NAME + ".Device", "StateChanged", v("(uuu)", (device, was, 0)))
|
||||
state = read_snapshot()
|
||||
if state is None:
|
||||
return True # A transient read failure must not replace a known link with Ethernet.
|
||||
if state == self.state:
|
||||
return True
|
||||
before, after = self.objects, objects(state)
|
||||
old_state = self.state
|
||||
self.state, self.objects = state, after
|
||||
self.register(after)
|
||||
for path in before.keys() | after.keys():
|
||||
removed = before.get(path, {}).keys() - after.get(path, {}).keys()
|
||||
added = after.get(path, {}).keys() - before.get(path, {}).keys()
|
||||
if removed:
|
||||
self.announce("InterfacesRemoved", v("(oas)", (path, list(removed))))
|
||||
if added:
|
||||
self.announce("InterfacesAdded", v("(oa{sa{sv}})", (path, {i: after[path][i] for i in added})))
|
||||
for interface in before.get(path, {}).keys() & after.get(path, {}).keys():
|
||||
changed = {k: value for k, value in after[path][interface].items() if value != before[path][interface].get(k)}
|
||||
if changed:
|
||||
self.bus.emit_signal(None, path, PROPERTIES, "PropertiesChanged", v("(sa{sv}as)", (interface, changed, [])))
|
||||
wifi_device = ROOT + "/Devices/Wifi"
|
||||
wireless = NAME + ".Device.Wireless"
|
||||
old_aps = before.get(wifi_device, {}).get(wireless, {}).get("AccessPoints", v("ao", [])).unpack()
|
||||
new_aps = after.get(wifi_device, {}).get(wireless, {}).get("AccessPoints", v("ao", [])).unpack()
|
||||
if wifi_device in after:
|
||||
for path in set(old_aps) - set(new_aps):
|
||||
self.bus.emit_signal(None, wifi_device, wireless, "AccessPointRemoved", v("(o)", (path,)))
|
||||
for path in set(new_aps) - set(old_aps):
|
||||
self.bus.emit_signal(None, wifi_device, wireless, "AccessPointAdded", v("(o)", (path,)))
|
||||
was = before[ROOT][NAME]["State"]
|
||||
now = after[ROOT][NAME]["State"]
|
||||
if now != was:
|
||||
self.bus.emit_signal(None, ROOT, NAME, "StateChanged", v("(u)", (now.unpack(),)))
|
||||
device = device_path(state)
|
||||
if device in before:
|
||||
was = before[device][NAME + ".Device"]["State"]
|
||||
now = after[device][NAME + ".Device"]["State"]
|
||||
if now != was:
|
||||
self.bus.emit_signal(None, device, NAME + ".Device", "StateChanged", v("(uuu)", (now.unpack(), was.unpack(), 0)))
|
||||
if settings(old_state) != settings(state):
|
||||
self.bus.emit_signal(None, PROFILE, NAME + ".Settings.Connection", "Updated", v("()", ()))
|
||||
return True
|
||||
|
||||
def announce(self, signal, path, body):
|
||||
self.bus.emit_signal(None, "/org/freedesktop", "org.freedesktop.DBus.ObjectManager", signal, body)
|
||||
def announce(self, signal, body):
|
||||
for path in ("/org/freedesktop", ROOT):
|
||||
self.bus.emit_signal(None, path, OBJECT_MANAGER, signal, body)
|
||||
|
||||
|
||||
def main():
|
||||
|
||||
@@ -53,7 +53,15 @@ trap 'collect_steam_logs 2>/dev/null || true' TERM INT HUP
|
||||
# VK_DRIVER_FILES REPLACES the loader's search, so a manifest whose library is unreadable would
|
||||
# leave the session with no Vulkan at all - check both before setting it, and say so in the log
|
||||
# rather than fail silently half a minute later.
|
||||
if [ -n "${BL_VK_DRIVER:-}" ]; then
|
||||
# Compatibility mode: the Android presenter still uses its selected Vulkan driver, while the
|
||||
# Linux session renders on the CPU. Gamescope's SDL swapchain can carry these frames as wl_shm;
|
||||
# its Wayland backend requires exportable dma-bufs even for its dummy black texture.
|
||||
if [ "${BL_STEAM_SOFTWARE:-0}" = 1 ]; then
|
||||
export VK_DRIVER_FILES=/usr/share/vulkan/icd.d/lvp_icd.json
|
||||
export VK_ICD_FILENAMES=$VK_DRIVER_FILES
|
||||
export LIBGL_ALWAYS_SOFTWARE=1 GALLIUM_DRIVER=llvmpipe MESA_LOADER_DRIVER_OVERRIDE=swrast
|
||||
echo "== linux graphics: software rendering requested (Lavapipe/llvmpipe)"
|
||||
elif [ -n "${BL_VK_DRIVER:-}" ]; then
|
||||
bl_icd_lib=$(sed -n 's/.*"library_path"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$BL_VK_DRIVER" 2>/dev/null | head -1)
|
||||
# JSON may escape the separator: org.json writes "\/data\/user\/0\/...". The Vulkan loader
|
||||
# parses that correctly; this check has to as well, or an absolute path looks relative and gets
|
||||
@@ -148,7 +156,13 @@ if [ -z "${BL_INSIDE:-}" ]; then
|
||||
echo "== gamescope: games at ${nested}x${height} stretched to the ${width}x${height} output"
|
||||
fi
|
||||
fi
|
||||
args=(--backend wayland --expose-wayland -f -W "$width" -H "$height" -w "$nested" -h "$height")
|
||||
backend=wayland
|
||||
if [ "${BL_STEAM_SOFTWARE:-0}" = 1 ]; then
|
||||
backend=sdl
|
||||
export SDL_VIDEODRIVER=wayland
|
||||
echo "== gamescope: SDL Wayland swapchain for software rendering"
|
||||
fi
|
||||
args=(--backend "$backend" --expose-wayland -f -W "$width" -H "$height" -w "$nested" -h "$height")
|
||||
[ "$nested" != "$width" ] && args+=(-S stretch)
|
||||
# -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
|
||||
@@ -179,7 +193,8 @@ if [ -z "${BL_INSIDE:-}" ]; then
|
||||
# MANGOHUD_CONFIGFILE. The apk stages Valve's aarch64 build (tools/mangoapp) - without it the menu
|
||||
# still offers the levels and nothing appears. Starts hidden until the client writes a level.
|
||||
# BL_MANGOAPP=0 turns it off (one community build found Valve's mangoapp crashing on Turnip).
|
||||
if [ "$mode" = steam ] && [ "${BL_STEAMDECK:-0}" = 1 ] && [ "${BL_MANGOAPP:-1}" = 1 ] \
|
||||
if [ "$mode" = steam ] && [ "${BL_STEAM_SOFTWARE:-0}" != 1 ] \
|
||||
&& [ "${BL_STEAMDECK:-0}" = 1 ] && [ "${BL_MANGOAPP:-1}" = 1 ] \
|
||||
&& [ "${BL_STEAM_UI:-}" != desktop ] && command -v mangoapp >/dev/null 2>&1; then
|
||||
MANGOHUD_CONFIGFILE=$(mktemp /tmp/mangohud.XXXXXXXX)
|
||||
echo no_display > "$MANGOHUD_CONFIGFILE"
|
||||
@@ -216,6 +231,12 @@ reap_orphans() {
|
||||
done
|
||||
}
|
||||
|
||||
# Gamescope's Wayland backend does not forward the outer clipboard into Xwayland.
|
||||
# This helper owns only Android text selections and exits with this guest session.
|
||||
if [ -n "${BL_ANDROID_CLIPBOARD:-}" ] && [ -x /usr/local/bin/droiddeck-clipboard ]; then
|
||||
/usr/local/bin/droiddeck-clipboard "$BL_ANDROID_CLIPBOARD" &
|
||||
fi
|
||||
|
||||
case $mode in
|
||||
desktop)
|
||||
exec pcmanfm
|
||||
@@ -498,31 +519,6 @@ case $mode in
|
||||
done
|
||||
return 1
|
||||
}
|
||||
# A title the compat pass maps while the client runs only takes that mapping at the client's
|
||||
# next start (see bannerlator-steam-compat): until then the client launches it its own way -
|
||||
# a Linux build stuck on "Downloading content (0%)" for a Steam Linux Runtime and FEX that
|
||||
# cannot run here (Left 4 Dead 2, 2026-10-02). So restart the client once for it, through the
|
||||
# same marker and -shutdown as the ARM64 Proton's restart: only when every new title has
|
||||
# finished installing (StateFlags 4) and no game is running; another download just resumes.
|
||||
# Once per title and three times per session at most, so a client that rewrites config.vdf
|
||||
# can never loop it.
|
||||
compat_pending=$HOME/.bl-compat-pending
|
||||
compat_restarted=$HOME/.bl-compat-restarted
|
||||
rm -f "$compat_pending"
|
||||
: > "$compat_restarted"
|
||||
compat_restarts=0
|
||||
compat_settled() {
|
||||
local app m flags
|
||||
while read -r app; do
|
||||
[ -n "$app" ] || continue
|
||||
m="$steam_root/steamapps/appmanifest_$app.acf"
|
||||
[ -f "$m" ] || m="/mnt/droiddeck-sd/steamapps/appmanifest_$app.acf"
|
||||
[ -f "$m" ] || return 1
|
||||
flags=$(sed -n 's/^[[:space:]]*"StateFlags"[[:space:]]*"\([0-9]*\)".*/\1/p' "$m" | head -n 1)
|
||||
[ "$flags" = 4 ] || return 1
|
||||
done < "$compat_pending"
|
||||
! pgrep -f 'reaper SteamLaunch' >/dev/null 2>&1
|
||||
}
|
||||
for ((_i = 0; _i < 720; _i++)); do
|
||||
nap 5
|
||||
beat=$((beat + 1))
|
||||
@@ -530,17 +526,7 @@ case $mode in
|
||||
bannerlator-seed-redists "$steam_root" >/dev/null 2>&1 || true
|
||||
if compat_due; then
|
||||
: > "$compat_stamp"
|
||||
bannerlator-steam-compat "$steam_root" --live >/dev/null 2>&1 || true
|
||||
fi
|
||||
if [ -s "$compat_pending" ] && compat_settled; then
|
||||
_bl_new=$(sort -u "$compat_pending" | grep -vxF -f "$compat_restarted" || true)
|
||||
rm -f "$compat_pending"
|
||||
[ -n "$_bl_new" ] && [ "$compat_restarts" -lt 3 ] || continue
|
||||
compat_restarts=$((compat_restarts + 1))
|
||||
printf '%s\n' $_bl_new >> "$compat_restarted"
|
||||
step "newly installed title(s) $(echo $_bl_new) set to the ARM64 Proton: restarting the Steam client once so it takes effect"
|
||||
: > "$HOME/.bl-restart-once"
|
||||
"$steam_root/steamrtarm64/steam" -shutdown >/dev/null 2>&1 || true
|
||||
bannerlator-steam-compat "$steam_root" >/dev/null 2>&1 || true
|
||||
fi
|
||||
done
|
||||
) &
|
||||
@@ -593,11 +579,29 @@ BUSCONF
|
||||
bannerlator-netmanager &
|
||||
netmanager=$!
|
||||
echo "== network: system bus up, NetworkManager stand-in running"
|
||||
# Steam blanks its main UI before calling login1.Suspend. Without the
|
||||
# matching resume notification it stays black although the menus work.
|
||||
# Own the name before Steam constructs its login1 proxy at startup.
|
||||
rm -f "$BL_LAUNCH_DIR/steam-sleep-ready"
|
||||
bannerlator-login1 &
|
||||
login_manager=$!
|
||||
for ((_i = 0; _i < 50; _i++)); do
|
||||
[ -f "$BL_LAUNCH_DIR/steam-sleep-ready" ] && break
|
||||
kill -0 "$login_manager" 2>/dev/null || break
|
||||
nap 0.1
|
||||
done
|
||||
if [ ! -f "$BL_LAUNCH_DIR/steam-sleep-ready" ]; then
|
||||
echo "== sleep: login1 did not start; refusing a client that cannot resume"
|
||||
exit 69
|
||||
fi
|
||||
echo "== sleep: login1 ready, Android session pause/resume available"
|
||||
else
|
||||
echo "== network: the system bus did not come up; the client will show no connection"
|
||||
exit 69
|
||||
fi
|
||||
else
|
||||
echo "== network: no dbus-daemon or netmanager in this runtime; the client will show no connection"
|
||||
exit 69
|
||||
fi
|
||||
|
||||
export STEAM_RUNTIME=1
|
||||
@@ -650,6 +654,15 @@ BUSCONF
|
||||
# desktop's launchers ask for; gamescope shows one window at a time and the game takes over.
|
||||
_bl_ui=(-gamepadui)
|
||||
[ "${BL_STEAM_UI:-}" = desktop ] && _bl_ui=()
|
||||
# Software compatibility mode: CEF and Steam use CPU frames through Xwayland,
|
||||
# inside either the desktop or the software Gamescope session.
|
||||
_bl_cef=(-cef-force-gpu -cef-ozone-platform=x11 -cef-use-gl=angle -cef-use-angle=vulkan)
|
||||
if [ "${BL_STEAM_SOFTWARE:-0}" = 1 ]; then
|
||||
_bl_cef=(-cef-disable-gpu -cef-disable-gpu-compositing -cef-ozone-platform=x11)
|
||||
export LIBGL_ALWAYS_SOFTWARE=1 GALLIUM_DRIVER=llvmpipe
|
||||
export MESA_LOADER_DRIVER_OVERRIDE=swrast SDL_RENDER_DRIVER=software SDL_VIDEODRIVER=x11
|
||||
echo "== steam: software rendering requested"
|
||||
fi
|
||||
# Deck mode (BL_STEAMDECK=1, the Steam page's Client settings): -steamdeck is the flag that puts
|
||||
# the Quick Access Menu and the Deck settings pages on screen; the QAM's performance overlay
|
||||
# controls stay greyed out without -steamos3, as SteamOS and Armada launch it. -steamos3 makes
|
||||
@@ -709,13 +722,13 @@ BUSCONF
|
||||
done
|
||||
) &
|
||||
fi
|
||||
echo "== steam args: ${_bl_ui[*]} -clientbeta $steam_channel -no-cef-sandbox -cef-force-gpu -cef-ozone-platform=x11 -cef-use-gl=angle -cef-use-angle=vulkan $*"
|
||||
echo "== steam args: ${_bl_ui[*]} -clientbeta $steam_channel -no-cef-sandbox ${_bl_cef[*]} $*"
|
||||
# An update that cannot install asks for a restart (rc=42) every time; the count is capped so a
|
||||
# session can never again loop in silence, which reads as a menu opening and closing by itself.
|
||||
steam_updates=0
|
||||
rm -f "$HOME/.bl-stop-requested"
|
||||
if [ -n "${BL_LAUNCH_DIR:-}" ] && [ -d "$BL_LAUNCH_DIR" ]; then
|
||||
rm -f "$BL_LAUNCH_DIR/steam-stop"
|
||||
rm -f "$BL_LAUNCH_DIR/steam-stop" "$BL_LAUNCH_DIR/steam-game" "$BL_LAUNCH_DIR/steam-game.tmp"
|
||||
(
|
||||
while :; do
|
||||
if [ -e "$BL_LAUNCH_DIR/steam-stop" ]; then
|
||||
@@ -725,6 +738,24 @@ BUSCONF
|
||||
"$steam_root/steamrtarm64/steam" -shutdown >/dev/null 2>&1 || true
|
||||
exit 0
|
||||
fi
|
||||
if [ -f "$BL_LAUNCH_DIR/steam-game" ]; then
|
||||
game_id=$(cat "$BL_LAUNCH_DIR/steam-game" 2>/dev/null)
|
||||
rm -f "$BL_LAUNCH_DIR/steam-game"
|
||||
case $game_id in
|
||||
''|0*|*[!0-9]*) echo "== steam: ignored invalid game launch request" ;;
|
||||
*)
|
||||
game_id_length=${#game_id}
|
||||
if [ "$game_id_length" -lt 20 ] || {
|
||||
[ "$game_id_length" -eq 20 ] && [[ "$game_id" < "18446744073709551616" ]];
|
||||
}; then
|
||||
echo "== steam: launching requested game $game_id in the running client"
|
||||
"$steam_root/steamrtarm64/steam" "steam://rungameid/$game_id" >/dev/null 2>&1 &
|
||||
else
|
||||
echo "== steam: ignored out-of-range game launch request"
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
fi
|
||||
nap 0.5
|
||||
done
|
||||
) &
|
||||
@@ -738,8 +769,7 @@ BUSCONF
|
||||
fi
|
||||
step "starting the Steam client${BL_STEAM_UI:+ ($BL_STEAM_UI UI)}"
|
||||
"$steam_root/steamrtarm64/steam" "${_bl_ui[@]}" -clientbeta "$steam_channel" \
|
||||
-no-cef-sandbox -cef-force-gpu -cef-ozone-platform=x11 \
|
||||
-cef-use-gl=angle -cef-use-angle=vulkan "$@"
|
||||
-no-cef-sandbox "${_bl_cef[@]}" "$@"
|
||||
rc=$?
|
||||
echo "== steam exited rc=$rc"
|
||||
collect_steam_logs
|
||||
@@ -754,9 +784,6 @@ BUSCONF
|
||||
# arguments, which were acted on. Not counted against the update cap.
|
||||
if [ -f "$HOME/.bl-restart-once" ]; then
|
||||
echo "== steam: restarting once so the new compatibility layer is in the client's lists"
|
||||
# The client wrote config.vdf back from its own memory as it exited, which can drop the
|
||||
# per-title entries written while it ran - the very ones this restart is for.
|
||||
bannerlator-steam-compat "$steam_root" >/dev/null 2>&1 || true
|
||||
set --
|
||||
continue
|
||||
fi
|
||||
|
||||
@@ -189,37 +189,6 @@ bl_idtech3() {
|
||||
}
|
||||
"""
|
||||
|
||||
# VAC diagnostics (the app's Setup page): a Source-engine game says whether it started VAC-secure
|
||||
# only in its own console, and writes that console to <mod>/console.log only with -condebug. Armed
|
||||
# per session by the app (~/.droiddeck-vac-diagnostics); each launch is noted for its summary.
|
||||
# Nothing else about the launch changes - this only asks the game to keep its own log.
|
||||
BL_VACDIAG_SETUP = """
|
||||
bl_vacdiag() {
|
||||
[ -f "${HOME:-/root}/.droiddeck-vac-diagnostics" ] || return 0
|
||||
[ "${verb:-}" = waitforexitandrun ] || return 0
|
||||
local exe= a dir added=no app=${SteamAppId:-${STEAM_COMPAT_APP_ID:-0}}
|
||||
for a in "$@"; do case $a in *.exe|*.EXE) exe=$a ;; esac; done
|
||||
[ -n "$exe" ] || return 0
|
||||
dir=$(dirname "$exe")
|
||||
# Source: <game>/<mod>/gameinfo.txt beside the exe. Source 2: <game>/game/bin/win64/<exe> with
|
||||
# <game>/game/<mod>/gameinfo.gi.
|
||||
if ls "$dir"/*/gameinfo.txt >/dev/null 2>&1 || ls "$dir"/../../*/gameinfo.gi >/dev/null 2>&1; then
|
||||
case " $* " in
|
||||
*" -condebug "*) echo "bannerlator-proton: vac-diag: app $app already has -condebug" >&2 ;;
|
||||
*) BL_EXTRA_ARGS+=(-condebug); added=yes
|
||||
echo "bannerlator-proton: vac-diag: app $app is a Source title; launched with -condebug" >&2 ;;
|
||||
esac
|
||||
else
|
||||
added=not-source
|
||||
echo "bannerlator-proton: vac-diag: app $app is not a Source title; it keeps no console log to read" >&2
|
||||
fi
|
||||
case " $* " in
|
||||
*" -insecure "*) echo "bannerlator-proton: vac-diag: app $app has -insecure in its launch options - it can never be VAC-secure this way" >&2 ;;
|
||||
esac
|
||||
printf '%s\tapp %s\tcondebug %s\t%s\n' "$(date +%s)" "$app" "$added" "${exe##*/}" >> "${HOME:-/root}/.droiddeck-vac-launches"
|
||||
}
|
||||
"""
|
||||
|
||||
BL_DIRECTAUDIO_SETUP = """
|
||||
bl_directaudio() {
|
||||
base=$1
|
||||
@@ -302,7 +271,6 @@ if [ -n "$depot" ]; then
|
||||
bl_directaudio "$depot"
|
||||
bl_game_cpus
|
||||
bl_idtech3 "$@"
|
||||
bl_vacdiag "$@"
|
||||
bl_libpath
|
||||
exec ${BL_TASKSET:-} /usr/local/bin/bannerlator-game-env "$depot/proton" "$verb" "$@" "${BL_EXTRA_ARGS[@]}"
|
||||
fi
|
||||
@@ -314,7 +282,7 @@ exit 1
|
||||
# something else.
|
||||
LAUNCHER_SH = LAUNCHER_SH.replace(
|
||||
"verb=$1; shift", "verb=$1; shift\n" + BL_DIRECTAUDIO_SETUP + BL_GAME_CPUS_SETUP + BL_IDTECH3_SETUP
|
||||
+ BL_VACDIAG_SETUP + BL_COMPONENTS_SETUP + BL_LIBPATH_SETUP, 1)
|
||||
+ BL_COMPONENTS_SETUP + BL_LIBPATH_SETUP, 1)
|
||||
|
||||
# A third-party Proton dropped into compatibilitytools.d - GE-Proton, proton-cachyos, anything of
|
||||
# that shape - is adopted rather than used as shipped, for the same two reasons Valve's ARM64 depot
|
||||
@@ -350,7 +318,6 @@ bl_components "$here"
|
||||
bl_directaudio "$here"
|
||||
bl_game_cpus
|
||||
bl_idtech3 "$@"
|
||||
bl_vacdiag "$@"
|
||||
bl_libpath
|
||||
# Proton takes its base directory from dirname(sys.argv[0]) without resolving it, so it has to be
|
||||
# started from its own tree.
|
||||
@@ -536,7 +503,7 @@ def adopt_extras(tools):
|
||||
body = (EXTRA_WRAPPER_SH % entry_point).replace(
|
||||
'here=$(dirname "$0")',
|
||||
'here=$(dirname "$0")\n' + BL_DIRECTAUDIO_SETUP + BL_GAME_CPUS_SETUP + BL_IDTECH3_SETUP
|
||||
+ BL_VACDIAG_SETUP + BL_COMPONENTS_SETUP + BL_LIBPATH_SETUP, 1)
|
||||
+ BL_COMPONENTS_SETUP + BL_LIBPATH_SETUP, 1)
|
||||
write_changed(wrapper, body, 0o755)
|
||||
write_changed(manifest, EXTRA_MANIFEST_VDF)
|
||||
write_changed(compat_vdf, EXTRA_COMPAT_TOOL_VDF % (name, entry))
|
||||
@@ -579,8 +546,7 @@ def installed_apps(steam_root):
|
||||
|
||||
|
||||
def register_default(config_path, apps=(), name=None, protect=()):
|
||||
"""Writes the mapping. `name` defaults to our own tool; the first-run seed passes Valve's.
|
||||
Returns the app ids given a per-app entry by this call."""
|
||||
"""Writes the mapping. `name` defaults to our own tool; the first-run seed passes Valve's."""
|
||||
tool = name or TOOL
|
||||
# Tool names the user may deliberately have chosen (see adopt_extras); never repointed.
|
||||
keep = {n.lower() for n in protect}
|
||||
@@ -589,8 +555,7 @@ def register_default(config_path, apps=(), name=None, protect=()):
|
||||
tokens = tokenize(original)
|
||||
steam = find_block(tokens, ["InstallConfigStore", "Software", "Valve", "Steam"])
|
||||
if steam is None:
|
||||
return []
|
||||
added = []
|
||||
return
|
||||
mapping = find_block(tokens[steam + 1:], ["CompatToolMapping"])
|
||||
entry = ['"0"', "{", '"name"', '"%s"' % tool, '"config"', '""', '"priority"', '"75"', "}"]
|
||||
if mapping is None:
|
||||
@@ -614,12 +579,10 @@ def register_default(config_path, apps=(), name=None, protect=()):
|
||||
continue
|
||||
tokens[mapping + 1:mapping + 1] = [
|
||||
'"%s"' % app, "{", '"name"', '"%s"' % tool, '"config"', '""', '"priority"', '"250"', "}"]
|
||||
added.append(app)
|
||||
# Nothing to change is the usual case on the session's beat: the client's own file is left alone.
|
||||
text = serialize(tokens)
|
||||
if text != serialize(tokenize(original)):
|
||||
write_changed(config_path, text)
|
||||
return added
|
||||
|
||||
|
||||
def depot_build(depot):
|
||||
@@ -670,18 +633,8 @@ def main():
|
||||
config = os.path.join(steam_root, "config", "config.vdf")
|
||||
if os.path.isfile(config):
|
||||
apps = installed_apps(steam_root)
|
||||
added = register_default(config, apps, protect=extras)
|
||||
register_default(config, apps, protect=extras)
|
||||
print("bannerlator-steam-compat: default and %d installed title(s) set to %s" % (len(apps), TOOL))
|
||||
# The client reads config.vdf once, as it starts, and keeps its own decisions in memory for
|
||||
# the rest of its run: a title installed while it runs gets the client's own pick (native
|
||||
# for a Linux build, which then waits for Steam Linux Runtime + FEX it can never run here;
|
||||
# proton-stable for a Windows one), and the entry written here only counts from the next
|
||||
# start. Run from the session's beat (--live), the new entries are noted for the session,
|
||||
# which restarts the client once the install has settled (bannerlator-session).
|
||||
if added and "--live" in sys.argv[2:]:
|
||||
with open(os.path.join(os.path.expanduser("~"), ".bl-compat-pending"), "a") as f:
|
||||
f.write("".join("%s\n" % a for a in added))
|
||||
print("bannerlator-steam-compat: mapped while the client runs: %s" % " ".join(added))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
# On a software desktop (pixman: the GPU renderers failed on this device) there is no dma-buf, so a
|
||||
# game - or the client's own Vulkan window - would die at its first frame. There the request goes
|
||||
# to the app, which ends the desktop and starts a Steam session under gamescope in its place.
|
||||
# BL_STEAM_SOFTWARE=1 opts into a CPU-rendered client on that desktop for compatibility testing.
|
||||
set -u
|
||||
ui=${1:-desktop}
|
||||
target=${2:-}
|
||||
@@ -28,7 +29,8 @@ esac
|
||||
steam_root=${XDG_DATA_HOME:-${HOME:-/root}/.local/share}/Steam
|
||||
client=$steam_root/steamrtarm64/steam
|
||||
|
||||
if [ "${BL_DESKTOP:-}" = 1 ] && [ -n "${WLR_RENDERER:-}" ] && [ "$WLR_RENDERER" != pixman ]; then
|
||||
if [ "${BL_DESKTOP:-}" = 1 ] && [ -n "${WLR_RENDERER:-}" ] \
|
||||
&& { [ "$WLR_RENDERER" != pixman ] || [ "${BL_STEAM_SOFTWARE:-0}" = 1 ]; }; then
|
||||
log=${BL_DEBUG_DIR:-$HOME/.cache/droiddeck}/steam-desktop.log
|
||||
mkdir -p "$(dirname "$log")" 2>/dev/null
|
||||
if pgrep -f 'steamrtarm64/steam( |$)' >/dev/null 2>&1 && [ -x "$client" ]; then
|
||||
|
||||
@@ -1,123 +0,0 @@
|
||||
#!/bin/bash
|
||||
# EXPERIMENT, opt-in: Valve's x86-64 Linux Steam client under FEX, beside the default arm64 one.
|
||||
# bannerlator-steam-x64 [steam:// URL or client arguments]
|
||||
#
|
||||
# Why: the arm64 Linux client never runs VAC (TF2, L4D2: "Connection Blocked ... VAC secured
|
||||
# server", no VAC line in any client log) - VAC modules are x86 code. The x86-64 client under FEX
|
||||
# has a module it can run, the way SteamLite does in Wine. This runs Valve's client unchanged.
|
||||
#
|
||||
# Everything lives in its own home ($X64_HOME): the x86 client gets its own ~/.steam links, its
|
||||
# own login and its own config, and never touches the arm64 client's. Games are shared: its
|
||||
# steamapps is the arm64 client's. Only one client runs at a time (same account), so the arm64
|
||||
# one is shut down first.
|
||||
#
|
||||
# First run downloads FEX (this repo's release), FEX's Ubuntu 24.04 x86 rootfs (~525 MB, unpacked
|
||||
# ~1.5 GB) and the x86 client (~600 MB). Log: $X64_HOME/steam-x64.log.
|
||||
set -eu
|
||||
FEX_TAG=fex-2609-r2
|
||||
FEX_SHA256=PENDING
|
||||
FEX_URL=https://github.com/Droid-Deck/DroidDeck/releases/download/$FEX_TAG/fex.tzst
|
||||
ROOTFS_URL=https://rootfs.fex-emu.gg/Ubuntu_24_04/2026-08-11/Ubuntu_24_04.sqsh
|
||||
CDN=https://client-update.fastly.steamstatic.com
|
||||
MANIFEST=steam_client_publicbeta_ubuntu12
|
||||
|
||||
REAL_HOME=${HOME:-/root}
|
||||
X64_HOME=${BL_X64_HOME:-$REAL_HOME/.droiddeck-x64}
|
||||
ROOTFS=$X64_HOME/rootfs
|
||||
STEAM_X64=$X64_HOME/.local/share/Steam
|
||||
ARM_STEAM=${XDG_DATA_HOME:-$REAL_HOME/.local/share}/Steam
|
||||
LOG=$X64_HOME/steam-x64.log
|
||||
mkdir -p "$X64_HOME"
|
||||
step() { echo "== $(date -u +%H:%M:%S) $*" | tee -a "$LOG"; }
|
||||
|
||||
# --- FEX -------------------------------------------------------------------------------------
|
||||
if [ ! -x /usr/local/bin/FEX ] || [ "$(cat /usr/local/share/fex-emu/.droiddeck-tag 2>/dev/null)" != "$FEX_TAG" ]; then
|
||||
step "downloading FEX ($FEX_TAG)"
|
||||
tmp=$(mktemp -d)
|
||||
curl -fL --progress-bar "$FEX_URL" -o "$tmp/fex.tzst"
|
||||
if [ "$FEX_SHA256" != PENDING ]; then echo "$FEX_SHA256 $tmp/fex.tzst" | sha256sum -c --quiet; fi
|
||||
zstd -dc "$tmp/fex.tzst" | tar -C / -x
|
||||
rm -rf "$tmp"
|
||||
mkdir -p /usr/local/share/fex-emu && echo "$FEX_TAG" > /usr/local/share/fex-emu/.droiddeck-tag
|
||||
fi
|
||||
step "FEX ready ($FEX_TAG)"
|
||||
|
||||
# --- x86 rootfs --------------------------------------------------------------------------------
|
||||
if [ ! -f "$ROOTFS/.droiddeck-complete" ]; then
|
||||
step "downloading FEX's Ubuntu 24.04 x86 rootfs"
|
||||
# Resumes a part-done download; a finished one answers 416, which is not a failure here.
|
||||
curl -fL --progress-bar -C - "$ROOTFS_URL" -o "$X64_HOME/rootfs.sqsh" || {
|
||||
rc=$?
|
||||
[ "$rc" = 22 ] && [ -s "$X64_HOME/rootfs.sqsh" ] || { step "rootfs download failed (curl $rc)"; exit 1; }
|
||||
}
|
||||
step "unpacking the rootfs"
|
||||
rm -rf "$ROOTFS"
|
||||
# Ownership and xattrs mean nothing in this guest; device nodes cannot be made here and are not
|
||||
# needed (FEX passes /dev through from the host).
|
||||
/usr/local/bin/unsquashfs -no-xattrs -no-progress -ignore-errors -d "$ROOTFS" "$X64_HOME/rootfs.sqsh" >>"$LOG" 2>&1 || true
|
||||
[ -x "$ROOTFS/usr/bin/bash" ] || { step "rootfs unpack failed (no usr/bin/bash); see $LOG"; exit 1; }
|
||||
rm -f "$X64_HOME/rootfs.sqsh"
|
||||
touch "$ROOTFS/.droiddeck-complete"
|
||||
fi
|
||||
# A path missing from the rootfs falls through to the guest: without its own, the x86 loader
|
||||
# reads the guest's /etc/ld.so.preload and tries to load the session's arm64 preloads.
|
||||
if [ ! -e "$ROOTFS/etc/ld.so.preload" ]; then
|
||||
: > "$ROOTFS/etc/ld.so.preload"
|
||||
fi
|
||||
|
||||
# --- the x86-64 client -------------------------------------------------------------------------
|
||||
if [ ! -x "$STEAM_X64/steamrt64/steam" ] || [ ! -f "$STEAM_X64/package/droiddeck-installed" ]; then
|
||||
step "downloading the x86-64 Steam client ($MANIFEST)"
|
||||
work=$(mktemp -d)
|
||||
curl -fsSL "$CDN/$MANIFEST" -o "$work/manifest"
|
||||
version=$(awk -F'"' '$2 == "version" { print $4; exit }' "$work/manifest")
|
||||
# Same parsing as bannerlator-steam-install: every component block's plain zip and sha256.
|
||||
awk -F'"' '
|
||||
/^\t"/ && NF >= 3 && $4 == "" { block = $2 }
|
||||
$2 == "file" { file[block] = $4 }
|
||||
$2 == "sha2" { sha[block] = $4 }
|
||||
END { for (b in file) if (b ~ /_all$/ || b ~ /_ubuntu12$/) print b, file[b], sha[b] }
|
||||
' "$work/manifest" | sort > "$work/parts"
|
||||
[ -s "$work/parts" ] || { step "no client components in $MANIFEST"; exit 1; }
|
||||
mkdir -p "$STEAM_X64/package"
|
||||
total=$(grep -c . "$work/parts")
|
||||
i=0
|
||||
while read -r block file sum; do
|
||||
i=$((i + 1))
|
||||
step "client: $block ($i/$total)"
|
||||
curl -fsSL "$CDN/$file" -o "$work/$file"
|
||||
echo "$sum $work/$file" | sha256sum -c --quiet
|
||||
unzip -qo "$work/$file" -d "$STEAM_X64"
|
||||
rm -f "$work/$file"
|
||||
done < "$work/parts"
|
||||
rm -rf "$work"
|
||||
echo publicbeta > "$STEAM_X64/package/beta"
|
||||
echo "$version" > "$STEAM_X64/package/droiddeck-installed"
|
||||
chmod +x "$STEAM_X64/steam.sh" "$STEAM_X64/steamrt64/steam" "$STEAM_X64/ubuntu12_32/steam" 2>/dev/null || true
|
||||
fi
|
||||
# Shared games: the arm64 client's library, as long as it is not running at the same time.
|
||||
if [ -d "$ARM_STEAM/steamapps" ] && [ ! -e "$STEAM_X64/steamapps" ]; then
|
||||
ln -s "$ARM_STEAM/steamapps" "$STEAM_X64/steamapps"
|
||||
fi
|
||||
|
||||
# --- one client at a time ----------------------------------------------------------------------
|
||||
if pgrep -f 'steamrtarm64/steam( |$)' >/dev/null 2>&1; then
|
||||
step "shutting down the arm64 client first"
|
||||
"$ARM_STEAM/steamrtarm64/steam" -shutdown >/dev/null 2>&1 || true
|
||||
for _ in $(seq 1 30); do pgrep -f 'steamrtarm64/steam( |$)' >/dev/null 2>&1 || break; sleep 1; done
|
||||
fi
|
||||
|
||||
# --- run ---------------------------------------------------------------------------------------
|
||||
# The arm64 session's library paths and preloads are aarch64 and mean nothing to x86 processes.
|
||||
unset LD_LIBRARY_PATH LD_PRELOAD STEAM_RUNTIME STEAM_RUNTIME_PREFER_HOST_LIBRARIES
|
||||
export HOME=$X64_HOME
|
||||
export FEX_ROOTFS=$ROOTFS
|
||||
# A FEX process takes its rootfs from FEXServer, not from its own environment, and a server
|
||||
# started earlier without FEX_ROOTFS (any FEX run in this guest) answers with no rootfs at all:
|
||||
# every x86 library lookup then falls through to the arm64 guest. Stop it, so the next FEX
|
||||
# starts one with this rootfs.
|
||||
/usr/local/bin/FEXServer -k >/dev/null 2>&1 || true
|
||||
export STEAM_EXTRA_COMPAT_TOOLS_PATHS=
|
||||
step "starting the x86-64 client under FEX: steam.sh -no-cef-sandbox $*"
|
||||
cd "$STEAM_X64"
|
||||
exec /usr/local/bin/FEX "$ROOTFS/usr/bin/bash" "$STEAM_X64/steam.sh" -no-cef-sandbox "$@" >>"$LOG" 2>&1
|
||||
@@ -229,6 +229,50 @@ def release_entry(
|
||||
}
|
||||
|
||||
|
||||
def preview_history_entry(release: dict, preview: dict, variants: list[tuple[str, str]]):
|
||||
"""Return compact history metadata for one complete, signed main build."""
|
||||
tag = release.get("tag_name") or ""
|
||||
tag_match = MAIN_TAG.fullmatch(tag)
|
||||
commit = (preview.get("commit") or "").lower()
|
||||
expected_packages = {package for package, _ in variants}
|
||||
apks = preview.get("apks") or {}
|
||||
if (
|
||||
release.get("draft")
|
||||
or not release.get("prerelease")
|
||||
or not tag_match
|
||||
or not re.fullmatch(r"[0-9a-f]{40}", commit)
|
||||
or not commit.startswith(tag_match.group(1))
|
||||
or set(apks) != expected_packages
|
||||
or any(
|
||||
not SHA256.fullmatch((apk.get("sha256") or "").lower())
|
||||
or not SHA256.fullmatch((apk.get("signerSha256") or "").lower())
|
||||
for apk in apks.values()
|
||||
)
|
||||
):
|
||||
return None
|
||||
return {
|
||||
"commit": commit,
|
||||
"title": preview["title"],
|
||||
"summary": preview["summary"][:400],
|
||||
"publishedAt": preview["publishedAt"],
|
||||
}
|
||||
|
||||
|
||||
def recent_previews(entries: list[dict], limit: int = 10) -> list[dict]:
|
||||
"""Keep the newest distinct Preview commits, newest first."""
|
||||
result = []
|
||||
seen = set()
|
||||
for entry in sorted(entries, key=lambda item: item["publishedAt"], reverse=True):
|
||||
commit = entry["commit"].lower()
|
||||
if commit in seen:
|
||||
continue
|
||||
seen.add(commit)
|
||||
result.append({**entry, "commit": commit})
|
||||
if len(result) >= limit:
|
||||
break
|
||||
return result
|
||||
|
||||
|
||||
def release_body_value(body: str, key: str):
|
||||
match = re.search(rf"(?mi)^\s*{re.escape(key)}:\s*`?([^\s`]+)", body or "")
|
||||
return match.group(1) if match else None
|
||||
@@ -276,6 +320,7 @@ def build_catalog(source: GitHub, ci: GitHub, source_repo: str, ci_repo: str) ->
|
||||
|
||||
releases = ci.get(f"/repos/{ci_repo}/releases?per_page=100")
|
||||
previews = []
|
||||
preview_history = []
|
||||
tests = []
|
||||
for release in releases:
|
||||
if release.get("draft"):
|
||||
@@ -291,9 +336,11 @@ def build_catalog(source: GitHub, ci: GitHub, source_repo: str, ci_repo: str) ->
|
||||
except ApiError:
|
||||
continue
|
||||
title, summary = ci_description(release)
|
||||
previews.append(
|
||||
release_entry(release, commit, 0, None, code, variants, signer, title, summary)
|
||||
)
|
||||
preview = release_entry(release, commit, 0, None, code, variants, signer, title, summary)
|
||||
previews.append(preview)
|
||||
history_entry = preview_history_entry(release, preview, variants)
|
||||
if history_entry:
|
||||
preview_history.append(history_entry)
|
||||
continue
|
||||
|
||||
pr_match = PR_TAG.fullmatch(tag)
|
||||
@@ -356,6 +403,7 @@ def build_catalog(source: GitHub, ci: GitHub, source_repo: str, ci_repo: str) ->
|
||||
"generatedAt": int(time.time() * 1000),
|
||||
"stable": stable,
|
||||
"preview": previews[0] if previews else None,
|
||||
"recentPreviews": recent_previews(preview_history),
|
||||
"tests": tests,
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
"""Real login1 sleep handshakes; run with dbus-run-session and python3-gi."""
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import signal
|
||||
import tempfile
|
||||
import time
|
||||
import unittest
|
||||
|
||||
try:
|
||||
import gi
|
||||
gi.require_version("Gio", "2.0")
|
||||
from gi.repository import Gio, GLib
|
||||
except ImportError:
|
||||
Gio = GLib = None
|
||||
|
||||
SCRIPT = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/bannerlator-login1"
|
||||
NAME = "org.freedesktop.login1"
|
||||
ROOT = "/org/freedesktop/login1"
|
||||
IFACE = NAME + ".Manager"
|
||||
|
||||
|
||||
@unittest.skipUnless(Gio and os.environ.get("DBUS_SESSION_BUS_ADDRESS"), "requires dbus-run-session and PyGObject")
|
||||
class SleepHandshakeTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.directory = tempfile.TemporaryDirectory()
|
||||
self.dir = Path(self.directory.name)
|
||||
self.signals = []
|
||||
self.bus = Gio.DBusConnection.new_for_address_sync(
|
||||
os.environ["DBUS_SESSION_BUS_ADDRESS"],
|
||||
Gio.DBusConnectionFlags.AUTHENTICATION_CLIENT | Gio.DBusConnectionFlags.MESSAGE_BUS_CONNECTION,
|
||||
None, None)
|
||||
self.subscription = self.bus.signal_subscribe(
|
||||
NAME, IFACE, "PrepareForSleep", ROOT, None, Gio.DBusSignalFlags.NONE,
|
||||
lambda bus, sender, path, interface, name, body: self.signals.append(body.unpack()[0]))
|
||||
env = dict(os.environ, BL_LAUNCH_DIR=str(self.dir),
|
||||
DBUS_SYSTEM_BUS_ADDRESS=os.environ["DBUS_SESSION_BUS_ADDRESS"])
|
||||
self.process = subprocess.Popen(["/usr/bin/python3", str(SCRIPT)], env=env,
|
||||
stdout=subprocess.DEVNULL)
|
||||
self.wait_for(lambda: (self.dir / "steam-sleep-ready").exists())
|
||||
|
||||
def tearDown(self):
|
||||
os.kill(self.process.pid, signal.SIGCONT)
|
||||
self.process.terminate()
|
||||
self.process.wait(timeout=5)
|
||||
self.bus.signal_unsubscribe(self.subscription)
|
||||
self.bus.close_sync(None)
|
||||
self.directory.cleanup()
|
||||
|
||||
def wait_for(self, condition, timeout=8):
|
||||
deadline = time.monotonic() + timeout
|
||||
while not condition():
|
||||
while GLib.MainContext.default().pending():
|
||||
GLib.MainContext.default().iteration(False)
|
||||
if time.monotonic() >= deadline:
|
||||
self.fail("timed out waiting for login1")
|
||||
time.sleep(0.01)
|
||||
|
||||
def call(self, interface, method, args=None):
|
||||
return self.bus.call_sync(NAME, ROOT, interface, method, args, None,
|
||||
Gio.DBusCallFlags.NONE, 2000, None).unpack()
|
||||
|
||||
def preparing(self):
|
||||
return self.call("org.freedesktop.DBus.Properties", "Get",
|
||||
GLib.Variant("(ss)", (IFACE, "PreparingForSleep")))[0]
|
||||
|
||||
def suspend(self):
|
||||
self.call(IFACE, "Suspend", GLib.Variant("(b)", (True,)))
|
||||
self.wait_for(lambda: (self.dir / "steam-sleep").exists())
|
||||
self.wait_for(lambda: self.signals == [True])
|
||||
return (self.dir / "steam-sleep").read_text().strip()
|
||||
|
||||
def state(self, token, state):
|
||||
staged = self.dir / "steam-sleep-state.tmp"
|
||||
staged.write_text(token + ":" + state + "\n")
|
||||
staged.replace(self.dir / "steam-sleep-state")
|
||||
|
||||
def test_resume_and_second_sleep(self):
|
||||
self.assertEqual(self.call(IFACE, "CanSuspend"), ("yes",))
|
||||
token = self.suspend()
|
||||
self.assertTrue(self.preparing())
|
||||
self.state(token, "paused")
|
||||
self.state("0" * 32, "awake") # stale session acknowledgments cannot wake this one
|
||||
time.sleep(0.1)
|
||||
self.assertTrue(self.preparing())
|
||||
self.state(token, "awake")
|
||||
self.wait_for(lambda: self.signals == [True, False])
|
||||
self.assertFalse(self.preparing())
|
||||
self.signals.clear()
|
||||
second = self.suspend()
|
||||
self.assertNotEqual(token, second)
|
||||
self.state(second, "awake")
|
||||
self.wait_for(lambda: self.signals == [True, False])
|
||||
|
||||
def test_missing_host_recovers(self):
|
||||
self.suspend()
|
||||
self.wait_for(lambda: self.signals == [True, False])
|
||||
self.assertFalse(self.preparing())
|
||||
self.assertFalse((self.dir / "steam-sleep").exists())
|
||||
|
||||
def test_wake_after_service_was_frozen_past_ack_timeout(self):
|
||||
token = self.suspend()
|
||||
self.state(token, "paused")
|
||||
os.kill(self.process.pid, signal.SIGSTOP)
|
||||
time.sleep(6)
|
||||
self.state(token, "awake")
|
||||
os.kill(self.process.pid, signal.SIGCONT)
|
||||
self.wait_for(lambda: self.signals == [True, False])
|
||||
self.assertFalse(self.preparing())
|
||||
|
||||
def test_suspend_after_service_was_frozen(self):
|
||||
os.kill(self.process.pid, signal.SIGSTOP)
|
||||
time.sleep(0.1)
|
||||
os.kill(self.process.pid, signal.SIGCONT)
|
||||
token = self.suspend()
|
||||
self.state(token, "awake")
|
||||
self.wait_for(lambda: self.signals == [True, False])
|
||||
self.assertFalse(self.preparing())
|
||||
|
||||
def test_failed_pause_recovers_and_duplicate_is_rejected(self):
|
||||
token = self.suspend()
|
||||
with self.assertRaises(GLib.Error):
|
||||
self.call(IFACE, "Suspend", GLib.Variant("(b)", (True,)))
|
||||
self.state(token, "awake")
|
||||
self.wait_for(lambda: self.signals == [True, False])
|
||||
with self.assertRaises(GLib.Error):
|
||||
self.call(IFACE, "PowerOff", GLib.Variant("(b)", (True,)))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,284 @@
|
||||
"""NetworkManager contract and real D-Bus handovers (requires python3-gi and dbus).
|
||||
|
||||
Run on Linux: dbus-run-session -- python3 -m unittest discover -s tools/tests -p test_netmanager.py
|
||||
"""
|
||||
import importlib.machinery
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import unittest
|
||||
|
||||
try:
|
||||
import gi
|
||||
gi.require_version("Gio", "2.0")
|
||||
from gi.repository import Gio, GLib
|
||||
except ImportError:
|
||||
Gio = GLib = None
|
||||
|
||||
SCRIPT = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/bannerlator-netmanager"
|
||||
if Gio:
|
||||
loader = importlib.machinery.SourceFileLoader("netmanager", str(SCRIPT))
|
||||
spec = importlib.util.spec_from_loader(loader.name, loader)
|
||||
nm = importlib.util.module_from_spec(spec)
|
||||
loader.exec_module(nm)
|
||||
|
||||
WIFI = {
|
||||
"connected": True, "transport": "wifi", "interface": "wlan0", "wifiEnabled": True,
|
||||
"validated": True, "captivePortal": False, "metered": False,
|
||||
"ssid": "Test \"Wi-Fi\" ☃", "strength": 73, "frequency": 5180, "bitrate": 866000,
|
||||
"addresses": [{"address": "192.0.2.2", "prefix": 24}, {"address": "2001:db8::2", "prefix": 64}],
|
||||
"gateways": ["192.0.2.1", "2001:db8::1"], "dns": ["192.0.2.1", "2001:db8::1"],
|
||||
}
|
||||
CELLULAR = {
|
||||
"connected": True, "transport": "cellular", "interface": "rmnet_data0", "wifiEnabled": True,
|
||||
"validated": True, "metered": True,
|
||||
"addresses": [{"address": "2001:db8:1::2", "prefix": 64}],
|
||||
"gateways": ["2001:db8:1::1"], "dns": ["2001:db8:1::1"],
|
||||
}
|
||||
OFFLINE = {"connected": False, "transport": "none", "wifiEnabled": True, "metered": None}
|
||||
|
||||
|
||||
@unittest.skipUnless(Gio, "requires PyGObject")
|
||||
class NetworkObjectsTest(unittest.TestCase):
|
||||
def test_wifi_graph(self):
|
||||
found = nm.objects(WIFI)
|
||||
manager = found[nm.ROOT][nm.NAME]
|
||||
device = found[nm.device_path(WIFI)]
|
||||
self.assertEqual(manager["PrimaryConnectionType"].unpack(), "802-11-wireless")
|
||||
self.assertTrue(manager["WirelessEnabled"].unpack())
|
||||
self.assertEqual(device[nm.NAME + ".Device"]["DeviceType"].unpack(), 2)
|
||||
self.assertEqual(device[nm.NAME + ".Device.Wireless"]["ActiveAccessPoint"].unpack(), nm.AP)
|
||||
ap = found[nm.AP][nm.NAME + ".AccessPoint"]
|
||||
self.assertEqual(bytes(ap["Ssid"].unpack()).decode(), WIFI["ssid"])
|
||||
self.assertEqual(ap["Strength"].unpack(), 73)
|
||||
self.assertEqual(manager["Metered"].unpack(), 2)
|
||||
for interfaces in found.values():
|
||||
for values in interfaces.values():
|
||||
for value in values.values():
|
||||
if value.get_type_string() == "o" and value.unpack() != "/":
|
||||
self.assertIn(value.unpack(), found)
|
||||
|
||||
def test_cellular_ipv6_only(self):
|
||||
found = nm.objects(CELLULAR)
|
||||
manager = found[nm.ROOT][nm.NAME]
|
||||
device = found[nm.device_path(CELLULAR)]
|
||||
active = found[nm.ACTIVE][nm.NAME + ".Connection.Active"]
|
||||
self.assertEqual(manager["PrimaryConnectionType"].unpack(), "gsm")
|
||||
self.assertEqual(manager["Metered"].unpack(), 1)
|
||||
self.assertEqual(device[nm.NAME + ".Device"]["DeviceType"].unpack(), 8)
|
||||
self.assertIn(nm.NAME + ".Device.Modem", device)
|
||||
self.assertNotIn(nm.AP, found)
|
||||
self.assertNotIn(nm.IP4, found)
|
||||
self.assertEqual(active["Ip4Config"].unpack(), "/")
|
||||
self.assertEqual(active["Ip6Config"].unpack(), nm.IP6)
|
||||
self.assertTrue(active["Default6"].unpack())
|
||||
self.assertFalse(active["Default"].unpack())
|
||||
self.assertNotEqual(nm.device_path(WIFI), nm.device_path(CELLULAR))
|
||||
|
||||
def test_offline_and_captive_portal(self):
|
||||
offline = nm.objects(OFFLINE)
|
||||
self.assertEqual(offline[nm.ROOT][nm.NAME]["State"].unpack(), 20)
|
||||
self.assertEqual(offline[nm.ROOT][nm.NAME]["ActiveConnections"].unpack(), [])
|
||||
self.assertNotIn(nm.AP, offline)
|
||||
self.assertEqual(nm.connectivity(dict(WIFI, validated=False, captivePortal=True)), 2)
|
||||
self.assertEqual(nm.connectivity(dict(WIFI, validated=False, captivePortal=False)), 3)
|
||||
self.assertEqual(nm.metered(OFFLINE), 0)
|
||||
|
||||
def test_redacted_name_and_wired_vpn(self):
|
||||
redacted = dict(WIFI)
|
||||
del redacted["ssid"]
|
||||
self.assertEqual(nm.connection_name(redacted), "Wi-Fi")
|
||||
self.assertEqual(bytes(nm.settings(redacted)["802-11-wireless"]["ssid"].unpack()), b"Wi-Fi")
|
||||
for transport, kind, device_type in (("ethernet", "802-3-ethernet", 1), ("vpn", "tun", 16)):
|
||||
state = dict(WIFI, transport=transport)
|
||||
found = nm.objects(state)
|
||||
self.assertEqual(found[nm.ROOT][nm.NAME]["PrimaryConnectionType"].unpack(), kind)
|
||||
self.assertEqual(found[nm.device_path(state)][nm.NAME + ".Device"]["DeviceType"].unpack(), device_type)
|
||||
self.assertNotIn(nm.AP, found)
|
||||
|
||||
def test_named_current_and_nearby_access_points(self):
|
||||
current = {"ssid": "Current Wi-Fi", "bssid": "00:11:22:33:44:55", "strength": 75,
|
||||
"capabilities": "[WPA2-PSK-CCMP][RSN-PSK+SAE-CCMP][ESS]"}
|
||||
other = {"ssid": "Other Wi-Fi", "bssid": "00:11:22:33:44:66", "strength": 42,
|
||||
"capabilities": "[ESS]"}
|
||||
state = dict(WIFI, ssid=current["ssid"], bssid=current["bssid"], accessPoints=[current, other], lastScan=123456)
|
||||
found = nm.objects(state)
|
||||
wireless = found[nm.device_path(state)][nm.NAME + ".Device.Wireless"]
|
||||
self.assertEqual(wireless["ActiveAccessPoint"].unpack(), nm.ap_path(current["bssid"]))
|
||||
self.assertEqual(set(wireless["AccessPoints"].unpack()), {nm.ap_path(current["bssid"]), nm.ap_path(other["bssid"])})
|
||||
self.assertEqual(wireless["LastScan"].unpack(), 123456)
|
||||
secured = found[nm.ap_path(current["bssid"])][nm.NAME + ".AccessPoint"]
|
||||
self.assertEqual(secured["Flags"].unpack(), 1)
|
||||
self.assertTrue(secured["RsnFlags"].unpack() & 0x100)
|
||||
self.assertTrue(secured["RsnFlags"].unpack() & 0x400)
|
||||
self.assertEqual(found[nm.ap_path(other["bssid"])][nm.NAME + ".AccessPoint"]["Flags"].unpack(), 0)
|
||||
# Keep nearby-network discovery while a cellular connection provides the default route.
|
||||
cellular = nm.objects(dict(CELLULAR, accessPoints=[other]))
|
||||
self.assertIn(nm.ap_path(other["bssid"]), cellular)
|
||||
self.assertEqual(cellular[nm.ROOT + "/Devices/Wifi"][nm.NAME + ".Device.Wireless"]["ActiveAccessPoint"].unpack(), "/")
|
||||
|
||||
|
||||
@unittest.skipUnless(Gio and os.environ.get("DBUS_SESSION_BUS_ADDRESS"), "requires dbus-run-session and PyGObject")
|
||||
class NetworkBusTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.snapshot = Path(self.temp.name) / "network.json"
|
||||
self.write(WIFI)
|
||||
self.bus = Gio.bus_get_sync(Gio.BusType.SESSION, None)
|
||||
env = dict(os.environ, DBUS_SYSTEM_BUS_ADDRESS=os.environ["DBUS_SESSION_BUS_ADDRESS"])
|
||||
# Use the production service and only redirect its input file for the fixture.
|
||||
launch = "import runpy,sys; from pathlib import Path; n=runpy.run_path(sys.argv[1]); g=n['main'].__globals__; g['SNAPSHOT']=Path(sys.argv[2]); g['SCAN_REQUEST']=Path(sys.argv[2]).with_suffix('.request'); n['main']()"
|
||||
self.process = subprocess.Popen([sys.executable, "-c", launch, str(SCRIPT), str(self.snapshot)], env=env,
|
||||
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
||||
self.await_type("802-11-wireless")
|
||||
|
||||
def tearDown(self):
|
||||
self.process.terminate()
|
||||
_, stderr = self.process.communicate(timeout=5)
|
||||
self.temp.cleanup()
|
||||
self.assertEqual(stderr, b"", stderr.decode())
|
||||
|
||||
def write(self, state):
|
||||
staged = self.snapshot.with_suffix(".staged")
|
||||
staged.write_text(json.dumps(state))
|
||||
staged.replace(self.snapshot)
|
||||
|
||||
def call(self, path, interface, method, parameters=None):
|
||||
return self.bus.call_sync(nm.NAME, path, interface, method, parameters, None,
|
||||
Gio.DBusCallFlags.NONE, 1000, None).unpack()
|
||||
|
||||
def prop(self, path, interface, name):
|
||||
return self.call(path, nm.PROPERTIES, "Get", GLib.Variant("(ss)", (interface, name)))[0]
|
||||
|
||||
def await_type(self, expected):
|
||||
deadline = time.monotonic() + 6
|
||||
while time.monotonic() < deadline:
|
||||
if self.process.poll() is not None:
|
||||
self.fail(self.process.communicate()[1].decode())
|
||||
try:
|
||||
if self.prop(nm.ROOT, nm.NAME, "PrimaryConnectionType") == expected:
|
||||
return
|
||||
except GLib.Error:
|
||||
pass
|
||||
time.sleep(0.05)
|
||||
self.fail("network type did not change to " + expected)
|
||||
|
||||
def test_direct_properties_methods_and_handover(self):
|
||||
signals = []
|
||||
subscription = self.bus.signal_subscribe(
|
||||
nm.NAME, None, None, None, None, Gio.DBusSignalFlags.NONE,
|
||||
lambda bus, sender, path, interface, member, args: signals.append((path, interface, member, args.unpack())))
|
||||
self.addCleanup(self.bus.signal_unsubscribe, subscription)
|
||||
wifi_path = nm.device_path(WIFI)
|
||||
self.assertEqual(self.prop(wifi_path, nm.NAME + ".Device", "DeviceType"), 2)
|
||||
self.assertEqual(self.prop(nm.AP, nm.NAME + ".AccessPoint", "Strength"), 73)
|
||||
self.assertEqual(self.call(wifi_path, nm.NAME + ".Device.Wireless", "GetAccessPoints"), ([nm.AP],))
|
||||
self.assertEqual(self.call(wifi_path, nm.NAME + ".Device.Wireless", "RequestScan", GLib.Variant("(a{sv})", ({},))), ())
|
||||
all_props = self.call(nm.ROOT, nm.PROPERTIES, "GetAll", GLib.Variant("(s)", (nm.NAME,)))[0]
|
||||
self.assertTrue(all_props["WirelessEnabled"])
|
||||
introspection = self.call(wifi_path, "org.freedesktop.DBus.Introspectable", "Introspect")[0]
|
||||
self.assertIn("GetAllAccessPoints", introspection)
|
||||
self.write(dict(WIFI, strength=21, ssid="Other Wi-Fi"))
|
||||
deadline = time.monotonic() + 4
|
||||
while self.prop(nm.AP, nm.NAME + ".AccessPoint", "Strength") != 21 and time.monotonic() < deadline:
|
||||
time.sleep(0.05)
|
||||
self.assertEqual(self.prop(nm.AP, nm.NAME + ".AccessPoint", "Strength"), 21)
|
||||
self.assertEqual(self.call(nm.PROFILE, nm.NAME + ".Settings.Connection", "GetSettings")[0]["connection"]["id"], "Other Wi-Fi")
|
||||
self.write(CELLULAR)
|
||||
self.await_type("gsm")
|
||||
cell_path = nm.device_path(CELLULAR)
|
||||
self.assertEqual(self.call(nm.ROOT, nm.NAME, "GetDevices"), ([cell_path, nm.ROOT + "/Devices/Wifi"],))
|
||||
self.assertEqual(self.prop(cell_path, nm.NAME + ".Device", "DeviceType"), 8)
|
||||
self.assertEqual(self.prop(nm.ROOT, nm.NAME, "Metered"), 1)
|
||||
managed = self.call(nm.ROOT, nm.OBJECT_MANAGER, "GetManagedObjects")[0]
|
||||
self.assertIn(wifi_path, managed)
|
||||
self.assertEqual(managed[wifi_path][nm.NAME + ".Device"]["State"], 30)
|
||||
self.assertNotIn(nm.AP, managed)
|
||||
self.assertNotIn(nm.IP4, managed)
|
||||
self.assertIn(nm.IP6, managed)
|
||||
self.assertEqual(self.prop(wifi_path, nm.NAME + ".Device.Wireless", "ActiveAccessPoint"), "/")
|
||||
self.write(OFFLINE)
|
||||
self.await_type("")
|
||||
self.assertEqual(self.call(nm.ROOT, nm.NAME, "CheckConnectivity"), (1,))
|
||||
self.write(WIFI)
|
||||
self.await_type("802-11-wireless")
|
||||
self.assertEqual(self.prop(nm.AP, nm.NAME + ".AccessPoint", "Strength"), 73)
|
||||
context = GLib.MainContext.default()
|
||||
while context.pending():
|
||||
context.iteration(False)
|
||||
self.assertTrue(any(interface == nm.PROPERTIES and member == "PropertiesChanged" and
|
||||
args[1].get("PrimaryConnectionType") == "gsm"
|
||||
for _, interface, member, args in signals))
|
||||
self.assertTrue(any(interface == nm.OBJECT_MANAGER and member == "InterfacesRemoved" and args[0] == nm.AP
|
||||
for _, interface, member, args in signals))
|
||||
self.assertTrue(any(member == "AccessPointAdded" for _, _, member, _ in signals))
|
||||
# A missing/invalid snapshot is a transient input error, never a fake Ethernet handover.
|
||||
self.snapshot.write_text("{")
|
||||
time.sleep(1.2)
|
||||
self.assertEqual(self.prop(nm.ROOT, nm.NAME, "PrimaryConnectionType"), "802-11-wireless")
|
||||
|
||||
def test_scan_requests_and_live_results(self):
|
||||
wifi_path = nm.device_path(WIFI)
|
||||
self.call(wifi_path, nm.NAME + ".Device.Wireless", "RequestScan", GLib.Variant("(a{sv})", ({},)))
|
||||
self.assertTrue(self.snapshot.with_suffix(".request").is_file())
|
||||
current = {"ssid": "Named Current", "bssid": "00:11:22:33:44:55", "capabilities": "[WPA2-PSK-CCMP]"}
|
||||
other = {"ssid": "Nearby", "bssid": "00:11:22:33:44:66", "strength": 37, "capabilities": "[ESS]"}
|
||||
self.write(dict(WIFI, ssid=current["ssid"], bssid=current["bssid"], accessPoints=[current, other], scanAllowed=True))
|
||||
deadline = time.monotonic() + 4
|
||||
while time.monotonic() < deadline:
|
||||
aps = self.call(wifi_path, nm.NAME + ".Device.Wireless", "GetAllAccessPoints")[0]
|
||||
if nm.ap_path(other["bssid"]) in aps:
|
||||
break
|
||||
time.sleep(0.05)
|
||||
self.assertIn(nm.ap_path(other["bssid"]), aps)
|
||||
self.assertEqual(self.prop(wifi_path, nm.NAME + ".Device.Wireless", "ActiveAccessPoint"), nm.ap_path(current["bssid"]))
|
||||
self.assertEqual(bytes(self.prop(nm.ap_path(other["bssid"]), nm.NAME + ".AccessPoint", "Ssid")).decode(), "Nearby")
|
||||
self.assertEqual(self.call(nm.PROFILE, nm.NAME + ".Settings.Connection", "GetSettings")[0]["connection"]["id"], "Named Current")
|
||||
self.write(dict(WIFI, scanAllowed=False))
|
||||
time.sleep(1.2)
|
||||
with self.assertRaises(GLib.Error):
|
||||
self.call(wifi_path, nm.NAME + ".Device.Wireless", "RequestScan", GLib.Variant("(a{sv})", ({},)))
|
||||
|
||||
def test_libnm_client(self):
|
||||
try:
|
||||
gi.require_version("NM", "1.0")
|
||||
from gi.repository import NM
|
||||
except ValueError:
|
||||
self.skipTest("requires gir1.2-nm-1.0")
|
||||
# libnm is a real consumer of the same API Steam reads. It caches objects by path,
|
||||
# so the handover must replace the Wi-Fi device with a modem rather than mutate its type.
|
||||
previous = os.environ.get("DBUS_SYSTEM_BUS_ADDRESS")
|
||||
os.environ["DBUS_SYSTEM_BUS_ADDRESS"] = os.environ["DBUS_SESSION_BUS_ADDRESS"]
|
||||
try:
|
||||
client = NM.Client.new(None)
|
||||
self.assertTrue(client.get_nm_running())
|
||||
wifi = client.get_devices()[0]
|
||||
self.assertIsInstance(wifi, NM.DeviceWifi)
|
||||
self.assertEqual(wifi.get_active_access_point().get_strength(), 73)
|
||||
self.assertEqual(client.get_primary_connection().get_connection_type(), "802-11-wireless")
|
||||
self.write(CELLULAR)
|
||||
self.await_type("gsm")
|
||||
context = GLib.MainContext.default()
|
||||
deadline = time.monotonic() + 4
|
||||
while time.monotonic() < deadline:
|
||||
while context.pending():
|
||||
context.iteration(False)
|
||||
if client.get_devices() and isinstance(client.get_devices()[0], NM.DeviceModem):
|
||||
break
|
||||
time.sleep(0.05)
|
||||
self.assertIsInstance(client.get_devices()[0], NM.DeviceModem)
|
||||
self.assertEqual(client.get_primary_connection().get_connection_type(), "gsm")
|
||||
finally:
|
||||
if previous is None:
|
||||
os.environ.pop("DBUS_SYSTEM_BUS_ADDRESS", None)
|
||||
else:
|
||||
os.environ["DBUS_SYSTEM_BUS_ADDRESS"] = previous
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,94 @@
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
SESSION = Path(__file__).resolve().parents[1] / 'linuxfs/overlay/usr/local/bin/bannerlator-session'
|
||||
GRAPHICS_ENV = ('VK_DRIVER_FILES', 'VK_ICD_FILENAMES', 'LIBGL_ALWAYS_SOFTWARE',
|
||||
'GALLIUM_DRIVER', 'MESA_LOADER_DRIVER_OVERRIDE', 'SDL_VIDEODRIVER')
|
||||
|
||||
|
||||
class SoftwareGraphicsTest(unittest.TestCase):
|
||||
def launch(self, **settings):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
home = Path(tmp)
|
||||
binary = home / 'bin'
|
||||
binary.mkdir()
|
||||
capture = home / 'capture.json'
|
||||
gamescope = binary / 'gamescope'
|
||||
gamescope.write_text(f'#!{sys.executable}\nimport json, os, sys\n'
|
||||
'from pathlib import Path\n'
|
||||
'Path(os.environ["TEST_CAPTURE"]).write_text(json.dumps({"argv": sys.argv[1:], "env": dict(os.environ)}))\n')
|
||||
gamescope.chmod(0o755)
|
||||
for name in ('wayland-info', 'mangoapp'):
|
||||
probe = binary / name
|
||||
probe.write_text('#!/bin/sh\nexit 0\n')
|
||||
probe.chmod(0o755)
|
||||
library = home / 'custom.so'
|
||||
library.touch()
|
||||
manifest = home / 'icd.json'
|
||||
manifest.write_text(json.dumps({'ICD': {'library_path': str(library)}}))
|
||||
env = {'PATH': str(binary) + os.pathsep + os.defpath, 'HOME': str(home),
|
||||
'TEST_CAPTURE': str(capture), 'BL_WIDTH': '960', 'BL_HEIGHT': '544',
|
||||
'BL_STEAMDECK': '1', 'BL_REFRESH': '120', 'BL_HDR': '1'}
|
||||
env.update(settings)
|
||||
if env.pop('TEST_CUSTOM_DRIVER', ''):
|
||||
env['BL_VK_DRIVER'] = str(manifest)
|
||||
subprocess.run([shutil.which('bash'), str(SESSION), 'steam', 'argument with spaces'],
|
||||
env=env, check=True, capture_output=True, text=True)
|
||||
result = json.loads(capture.read_text())
|
||||
config = result['env'].get('MANGOHUD_CONFIGFILE')
|
||||
if config:
|
||||
Path(config).unlink()
|
||||
return result, str(manifest)
|
||||
|
||||
def test_default_keeps_accelerated_backend_overlay_and_session_options(self):
|
||||
result, _ = self.launch(VK_DRIVER_FILES='/selected/turnip.json', GALLIUM_DRIVER='zink')
|
||||
args, env = result['argv'], result['env']
|
||||
self.assertEqual(args[:2], ['--backend', 'wayland'])
|
||||
self.assertEqual(env['VK_DRIVER_FILES'], '/selected/turnip.json')
|
||||
self.assertEqual(env['GALLIUM_DRIVER'], 'zink')
|
||||
self.assertNotIn('LIBGL_ALWAYS_SOFTWARE', env)
|
||||
self.assertNotIn('MESA_LOADER_DRIVER_OVERRIDE', env)
|
||||
self.assertNotIn('SDL_VIDEODRIVER', env)
|
||||
self.assertIn('--mangoapp', args)
|
||||
self.assertIn('--hdr-enabled', args)
|
||||
self.assertEqual(args[args.index('-r') + 1], '120')
|
||||
self.assertEqual(args[-1], 'argument with spaces')
|
||||
|
||||
def test_only_explicit_one_selects_software(self):
|
||||
for value in ('', '0', 'true', 'yes'):
|
||||
with self.subTest(value=value):
|
||||
result, _ = self.launch(BL_STEAM_SOFTWARE=value)
|
||||
self.assertEqual(result['argv'][:2], ['--backend', 'wayland'])
|
||||
self.assertNotIn('LIBGL_ALWAYS_SOFTWARE', result['env'])
|
||||
self.assertIn('--mangoapp', result['argv'])
|
||||
result, _ = self.launch(BL_STEAM_SOFTWARE='1')
|
||||
env = result['env']
|
||||
self.assertEqual(result['argv'][:2], ['--backend', 'sdl'])
|
||||
self.assertNotIn('--mangoapp', result['argv'])
|
||||
self.assertEqual(env['VK_DRIVER_FILES'], '/usr/share/vulkan/icd.d/lvp_icd.json')
|
||||
self.assertEqual(env['VK_ICD_FILENAMES'], env['VK_DRIVER_FILES'])
|
||||
self.assertEqual(env['LIBGL_ALWAYS_SOFTWARE'], '1')
|
||||
self.assertEqual(env['GALLIUM_DRIVER'], 'llvmpipe')
|
||||
self.assertEqual(env['SDL_VIDEODRIVER'], 'wayland')
|
||||
|
||||
def test_custom_driver_is_preserved_except_when_software_is_requested(self):
|
||||
for software in ('0', '1'):
|
||||
result, manifest = self.launch(TEST_CUSTOM_DRIVER='1', BL_STEAM_SOFTWARE=software)
|
||||
expected = manifest if software == '0' else '/usr/share/vulkan/icd.d/lvp_icd.json'
|
||||
self.assertEqual(result['env']['VK_DRIVER_FILES'], expected)
|
||||
self.assertEqual(result['env']['VK_ICD_FILENAMES'], expected)
|
||||
|
||||
def test_invalid_custom_driver_does_not_replace_inherited_selection(self):
|
||||
result, _ = self.launch(BL_VK_DRIVER='/missing/manifest.json', VK_DRIVER_FILES='/selected/turnip.json')
|
||||
self.assertEqual(result['env']['VK_DRIVER_FILES'], '/selected/turnip.json')
|
||||
self.assertEqual(result['argv'][:2], ['--backend', 'wayland'])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -6,6 +6,8 @@ from tools.release.update_catalog import (
|
||||
parse_gradle,
|
||||
parse_variants,
|
||||
published_millis,
|
||||
preview_history_entry,
|
||||
recent_previews,
|
||||
release_body_value,
|
||||
stable_app_release,
|
||||
)
|
||||
@@ -87,6 +89,53 @@ pubg com.tencent.ig -pubg
|
||||
published_millis(release, prefer_updated=True),
|
||||
)
|
||||
|
||||
def test_preview_history_keeps_only_complete_signed_main_releases(self):
|
||||
variants = [("com.droiddeck.launcher", ""), ("com.example.variant", "-variant")]
|
||||
commit = "a" * 40
|
||||
entry = {
|
||||
"commit": commit,
|
||||
"title": "Fix Steam resume",
|
||||
"summary": "Steam stays open after resuming.",
|
||||
"publishedAt": 123,
|
||||
"apks": {
|
||||
package: {"sha256": "a" * 64, "signerSha256": "b" * 64}
|
||||
for package, _ in variants
|
||||
},
|
||||
}
|
||||
release = {"tag_name": "main-aaaaaaa", "draft": False, "prerelease": True}
|
||||
self.assertEqual(
|
||||
{
|
||||
"commit": commit,
|
||||
"title": "Fix Steam resume",
|
||||
"summary": "Steam stays open after resuming.",
|
||||
"publishedAt": 123,
|
||||
},
|
||||
preview_history_entry(release, entry, variants),
|
||||
)
|
||||
|
||||
for invalid_release in (
|
||||
{**release, "draft": True},
|
||||
{**release, "prerelease": False},
|
||||
{**release, "tag_name": "pr-42"},
|
||||
):
|
||||
self.assertIsNone(preview_history_entry(invalid_release, entry, variants))
|
||||
self.assertIsNone(preview_history_entry(release, {**entry, "commit": "a" * 12}, variants))
|
||||
self.assertIsNone(preview_history_entry(release, {**entry, "apks": {"com.droiddeck.launcher": {}}}, variants))
|
||||
unsigned = {**entry, "apks": {package: {"sha256": "a" * 64} for package, _ in variants}}
|
||||
self.assertIsNone(preview_history_entry(release, unsigned, variants))
|
||||
|
||||
def test_preview_history_is_newest_first_deduplicated_and_limited(self):
|
||||
entries = [
|
||||
{"commit": f"{i:040x}", "title": str(i), "summary": "", "publishedAt": i}
|
||||
for i in range(12)
|
||||
]
|
||||
entries.append({**entries[-1], "title": "duplicate", "publishedAt": 99})
|
||||
recent = recent_previews(entries)
|
||||
self.assertEqual(10, len(recent))
|
||||
self.assertEqual("duplicate", recent[0]["title"])
|
||||
self.assertEqual("000000000000000000000000000000000000000a", recent[1]["commit"])
|
||||
self.assertEqual(1, len([item for item in recent if item["commit"].endswith("000b")]))
|
||||
|
||||
def test_stable_is_the_newest_app_release_not_github_latest(self):
|
||||
def release(tag, at, *assets, **flags):
|
||||
return {"tag_name": tag, "published_at": at, "assets": [{"name": a} for a in assets], **flags}
|
||||
|
||||
Reference in new issue
Block a user