Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
197fc3f163 | ||
|
|
0e0f133496 | ||
|
|
d98c211168 | ||
|
|
614b4d4de4 | ||
|
|
43a19a831a | ||
|
|
0d308af024 | ||
|
|
128f73da8f | ||
|
|
e22a55e949 | ||
|
|
67cb005e6c | ||
|
|
73f76f6799 | ||
|
|
961a060461 | ||
|
|
dadbbf841a | ||
|
|
1ce8280371 | ||
|
|
78bdc0e3b5 | ||
|
|
ce5f2f5513 | ||
|
|
0f2792c7ac | ||
|
|
7185b775d4 | ||
|
|
cda6e89c12 | ||
|
|
5f80898c27 | ||
|
|
85560d6471 | ||
|
|
be6c875277 | ||
|
|
91beced154 | ||
|
|
ebc3da08b4 | ||
|
|
41eb780495 | ||
|
|
65fc2a38a3 | ||
|
|
359d1535ac | ||
|
|
4c3a9f027c | ||
|
|
5a6cc3c76e | ||
|
|
89bd7deceb | ||
|
|
169f2c3e34 | ||
|
|
e6a797695a | ||
|
|
f1a2ecc857 | ||
|
|
36916f6bde | ||
|
|
1b96d13a51 | ||
|
|
cb1d70bb14 | ||
|
|
37af590ca2 | ||
|
|
02f356f8c0 | ||
|
|
5448177814 | ||
|
|
ed6ce0ca41 | ||
|
|
9b440686c5 | ||
|
|
e7b7e9dc43 | ||
|
|
1120040aee | ||
|
|
3506a272da | ||
|
|
b752748b7d | ||
|
|
8990e7d7a4 | ||
|
|
c92a423ba1 | ||
|
|
3b82b3e1f8 | ||
|
|
e985ce1975 | ||
|
|
8496ce3e51 | ||
|
|
47188f40ed | ||
|
|
e186c9bc4c | ||
|
|
7705f3c222 | ||
|
|
5675b4897f | ||
|
|
1c87d92ef7 | ||
|
|
031e64dfe1 | ||
|
|
f590dd9763 | ||
|
|
af7dc40538 | ||
|
|
a28aae6e4a | ||
|
|
c024470cc7 | ||
|
|
16ae5ab84a | ||
|
|
144947305a | ||
|
|
c104e1c276 |
No files matched your search
@@ -26,7 +26,7 @@ concurrency:
|
|||||||
cancel-in-progress: true
|
cancel-in-progress: true
|
||||||
|
|
||||||
env:
|
env:
|
||||||
PRELOAD_CACHE_VERSION: v1
|
PRELOAD_CACHE_VERSION: v2
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
build:
|
build:
|
||||||
@@ -160,7 +160,7 @@ jobs:
|
|||||||
D=app/src/main/assets/linuxfs
|
D=app/src/main/assets/linuxfs
|
||||||
mkdir -p "$D"
|
mkdir -p "$D"
|
||||||
aarch64-linux-gnu-g++ -shared -fPIC -O2 -Wall -Wno-attributes -Wno-nonnull-compare \
|
aarch64-linux-gnu-g++ -shared -fPIC -O2 -Wall -Wno-attributes -Wno-nonnull-compare \
|
||||||
-pthread -std=c++17 -static-libstdc++ -static-libgcc \
|
-pthread -std=c++17 -static-libstdc++ -static-libgcc -Wl,--exclude-libs,ALL \
|
||||||
-o "$D/libfakeinput.so" app/src/main/cpp/fakeinput_steam.cpp -ldl
|
-o "$D/libfakeinput.so" app/src/main/cpp/fakeinput_steam.cpp -ldl
|
||||||
aarch64-linux-gnu-strip --strip-unneeded "$D/libfakeinput.so"
|
aarch64-linux-gnu-strip --strip-unneeded "$D/libfakeinput.so"
|
||||||
aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -pthread \
|
aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -pthread \
|
||||||
@@ -270,6 +270,12 @@ jobs:
|
|||||||
for sym in open openat ioctl read close poll ppoll select stat fstat access scandir; do
|
for sym in open openat ioctl read close poll ppoll select stat fstat access scandir; do
|
||||||
grep -qx "$sym" <<<"$FAKE" || { echo "::error::libfakeinput.so does not export $sym"; exit 1; }
|
grep -qx "$sym" <<<"$FAKE" || { echo "::error::libfakeinput.so does not export $sym"; exit 1; }
|
||||||
done
|
done
|
||||||
|
# The static C++ runtime stays private: every session process preloads this library,
|
||||||
|
# and an exported personality routine takes over other programs' unwinding (shadPS4
|
||||||
|
# aborted in pthread_exit).
|
||||||
|
if grep -qxE '__gxx_personality_v0|__cxa_throw|_Unwind_Resume' <<<"$FAKE"; then
|
||||||
|
echo "::error::libfakeinput.so exports the C++ runtime"; exit 1
|
||||||
|
fi
|
||||||
SESSION=$(syms "$D/libblsession.so")
|
SESSION=$(syms "$D/libblsession.so")
|
||||||
for sym in socket bind getsockname setsockopt statfs statvfs; do
|
for sym in socket bind getsockname setsockopt statfs statvfs; do
|
||||||
grep -qx "$sym" <<<"$SESSION" || { echo "::error::libblsession.so does not export $sym"; exit 1; }
|
grep -qx "$sym" <<<"$SESSION" || { echo "::error::libblsession.so does not export $sym"; exit 1; }
|
||||||
@@ -295,6 +301,9 @@ jobs:
|
|||||||
set -o pipefail
|
set -o pipefail
|
||||||
./gradlew assembleRelease --console=plain -PndkVersion="$NDK_VERSION" 2>&1 | tee /tmp/build.log
|
./gradlew assembleRelease --console=plain -PndkVersion="$NDK_VERSION" 2>&1 | tee /tmp/build.log
|
||||||
|
|
||||||
|
- name: Unit tests
|
||||||
|
run: ./gradlew testReleaseUnitTest --console=plain -PndkVersion="$NDK_VERSION"
|
||||||
|
|
||||||
- name: Check the native dependency closure
|
- name: Check the native dependency closure
|
||||||
run: |
|
run: |
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
|
|||||||
@@ -79,8 +79,9 @@ jobs:
|
|||||||
}
|
}
|
||||||
stable=$(package_line "$RUNNER_TEMP/stable/DroidDeck-$stable_tag.apk")
|
stable=$(package_line "$RUNNER_TEMP/stable/DroidDeck-$stable_tag.apk")
|
||||||
candidate=$(package_line "${apks[0]}")
|
candidate=$(package_line "${apks[0]}")
|
||||||
[[ "$stable" =~ ^com\.droiddeck\.launcher\ [0-9]+$ && "$candidate" == "$stable" ]] || {
|
[[ "$stable" =~ ^com\.droiddeck\.launcher\ [0-9]+$ && "$candidate" =~ ^com\.droiddeck\.launcher\ [0-9]+$ &&
|
||||||
echo "::error::PR package/versionCode '$candidate' differs from stable '$stable'"; exit 1;
|
${candidate##* } -ge ${stable##* } ]] || {
|
||||||
|
echo "::error::PR package/versionCode '$candidate' cannot install over stable '$stable'"; exit 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
current=$(gh api "repos/$GITHUB_REPOSITORY/pulls/$PR_NUMBER")
|
current=$(gh api "repos/$GITHUB_REPOSITORY/pulls/$PR_NUMBER")
|
||||||
|
|||||||
@@ -35,6 +35,10 @@ jobs:
|
|||||||
run: |
|
run: |
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
[[ $VERSION =~ ^[0-9A-Za-z._-]+$ ]] || { echo "::error::version '$VERSION': letters, digits, . _ - only"; exit 1; }
|
[[ $VERSION =~ ^[0-9A-Za-z._-]+$ ]] || { echo "::error::version '$VERSION': letters, digits, . _ - only"; exit 1; }
|
||||||
|
name=$(sed -n 's/^ *versionName "\(.*\)"$/\1/p' app/build.gradle)
|
||||||
|
[[ $VERSION == "$name" || $VERSION == "$name"-* ]] || {
|
||||||
|
echo "::error::version '$VERSION' does not match versionName '$name' in app/build.gradle: bump versionName and versionCode first"; exit 1;
|
||||||
|
}
|
||||||
runs=$(gh run list -R "$GITHUB_REPOSITORY" --workflow build.yml --branch main --commit "$GITHUB_SHA" \
|
runs=$(gh run list -R "$GITHUB_REPOSITORY" --workflow build.yml --branch main --commit "$GITHUB_SHA" \
|
||||||
--status success --json databaseId,event,headSha -L 20)
|
--status success --json databaseId,event,headSha -L 20)
|
||||||
id=$(jq -r --arg sha "$GITHUB_SHA" \
|
id=$(jq -r --arg sha "$GITHUB_SHA" \
|
||||||
|
|||||||
@@ -5,7 +5,9 @@
|
|||||||
</picture>
|
</picture>
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
Run Valve's native ARM64 Steam client on an Adreno Android device. Steam runs in a Linux runtime under proot, with gamescope and an in-app Vulkan compositor. Windows games use Valve's ARM64 Proton and FEX. A desktop with LXQt, Firefox, and emulators is also available.
|
DroidDeck brings the SteamOS experience to Android: Valve's Steam client in Big Picture on your Adreno handheld, with Windows games through Valve's ARM64 Proton.
|
||||||
|
|
||||||
|
<p align="center"><img src="docs/releases/media/0.2.0/launch-into-steam.gif" width="80%" alt="Tapping DroidDeck on the Android home screen and landing in Steam Big Picture"></p>
|
||||||
|
|
||||||
## Requirements and install
|
## Requirements and install
|
||||||
|
|
||||||
|
|||||||
@@ -63,8 +63,8 @@ android {
|
|||||||
// file out of its own data directory, and this app's entire job is to exec a rootfs:
|
// file out of its own data directory, and this app's entire job is to exec a rootfs:
|
||||||
// proot, gamescope, the Steam client and everything it launches all live under files/.
|
// proot, gamescope, the Steam client and everything it launches all live under files/.
|
||||||
targetSdkVersion 28
|
targetSdkVersion 28
|
||||||
versionCode 8
|
versionCode 9
|
||||||
versionName "0.1.7"
|
versionName "0.2.0"
|
||||||
buildConfigField "String", "BUILD_LABEL", "\"${escapedBuildLabel}\""
|
buildConfigField "String", "BUILD_LABEL", "\"${escapedBuildLabel}\""
|
||||||
|
|
||||||
ndk {
|
ndk {
|
||||||
@@ -140,6 +140,11 @@ android {
|
|||||||
buildConfig true
|
buildConfig true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
testOptions {
|
||||||
|
// Plain JVM tests: a stray android.util.Log call returns a default instead of throwing.
|
||||||
|
unitTests.returnDefaultValues = true
|
||||||
|
}
|
||||||
|
|
||||||
compileOptions {
|
compileOptions {
|
||||||
sourceCompatibility JavaVersion.VERSION_17
|
sourceCompatibility JavaVersion.VERSION_17
|
||||||
targetCompatibility JavaVersion.VERSION_17
|
targetCompatibility JavaVersion.VERSION_17
|
||||||
@@ -152,7 +157,7 @@ android {
|
|||||||
dependencies {
|
dependencies {
|
||||||
// The runtime tarball is a zstd-compressed tar.
|
// The runtime tarball is a zstd-compressed tar.
|
||||||
implementation 'com.github.luben:zstd-jni:1.5.2-3@aar'
|
implementation 'com.github.luben:zstd-jni:1.5.2-3@aar'
|
||||||
implementation 'org.apache.commons:commons-compress:1.20'
|
implementation 'org.apache.commons:commons-compress:1.27.1'
|
||||||
// The UI: every menu, dialog and overlay is Compose. The session's SurfaceView and the
|
// The UI: every menu, dialog and overlay is Compose. The session's SurfaceView and the
|
||||||
// on-screen pad are Views underneath it, which is what they are in every Compose app.
|
// on-screen pad are Views underneath it, which is what they are in every Compose app.
|
||||||
implementation platform('androidx.compose:compose-bom:2024.02.00')
|
implementation platform('androidx.compose:compose-bom:2024.02.00')
|
||||||
@@ -169,4 +174,6 @@ dependencies {
|
|||||||
implementation 'com.flyfishxu:kadb-android:1.2.1'
|
implementation 'com.flyfishxu:kadb-android:1.2.1'
|
||||||
// Android terminal view/emulator used by the in-session secondary-display Linux shell.
|
// Android terminal view/emulator used by the in-session secondary-display Linux shell.
|
||||||
implementation 'com.termux.termux-app:terminal-view:0.118.0'
|
implementation 'com.termux.termux-app:terminal-view:0.118.0'
|
||||||
|
|
||||||
|
testImplementation 'junit:junit:4.13.2'
|
||||||
}
|
}
|
||||||
@@ -48,7 +48,8 @@
|
|||||||
<activity
|
<activity
|
||||||
android:name=".MainActivity"
|
android:name=".MainActivity"
|
||||||
android:exported="true"
|
android:exported="true"
|
||||||
android:screenOrientation="sensorLandscape">
|
android:screenOrientation="sensorLandscape"
|
||||||
|
android:configChanges="keyboard|keyboardHidden|navigation">
|
||||||
<intent-filter>
|
<intent-filter>
|
||||||
<action android:name="android.intent.action.MAIN" />
|
<action android:name="android.intent.action.MAIN" />
|
||||||
<category android:name="android.intent.category.LAUNCHER" />
|
<category android:name="android.intent.category.LAUNCHER" />
|
||||||
@@ -125,6 +126,10 @@
|
|||||||
android:name=".session.SessionService"
|
android:name=".session.SessionService"
|
||||||
android:exported="false"
|
android:exported="false"
|
||||||
android:stopWithTask="false" />
|
android:stopWithTask="false" />
|
||||||
|
<!-- Holds the process in the foreground while the Linux runtime downloads and unpacks. -->
|
||||||
|
<service
|
||||||
|
android:name=".runtime.RuntimeInstallService"
|
||||||
|
android:exported="false" />
|
||||||
<!-- Hands a zipped session folder to the share sheet; nothing else is exposed. -->
|
<!-- Hands a zipped session folder to the share sheet; nothing else is exposed. -->
|
||||||
<provider
|
<provider
|
||||||
android:name="androidx.core.content.FileProvider"
|
android:name="androidx.core.content.FileProvider"
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ add_library(bannerwayland SHARED
|
|||||||
src/ahb_swapchain.c
|
src/ahb_swapchain.c
|
||||||
src/waylandcomp_jni.c
|
src/waylandcomp_jni.c
|
||||||
src/banner_ext.c
|
src/banner_ext.c
|
||||||
|
src/wl_dmabuf.c
|
||||||
src/wl_clipboard.c
|
src/wl_clipboard.c
|
||||||
src/wl_text_input.c
|
src/wl_text_input.c
|
||||||
src/wl_toplevel_icon.c
|
src/wl_toplevel_icon.c
|
||||||
@@ -33,6 +34,9 @@ add_library(bannerwayland SHARED
|
|||||||
src/framegen_bridge.c
|
src/framegen_bridge.c
|
||||||
src/framegen_jni.c
|
src/framegen_jni.c
|
||||||
)
|
)
|
||||||
|
# Warnings on for the compositor's own C. They do not fail the build; they are there to be read.
|
||||||
|
target_compile_options(bannerwayland PRIVATE
|
||||||
|
$<$<COMPILE_LANGUAGE:C>:-Wall -Wextra -Wno-unused-parameter -Wno-missing-field-initializers>)
|
||||||
target_include_directories(bannerwayland PRIVATE
|
target_include_directories(bannerwayland PRIVATE
|
||||||
generated
|
generated
|
||||||
prebuilt/include
|
prebuilt/include
|
||||||
|
|||||||
@@ -51,6 +51,7 @@
|
|||||||
#include "effects_chain.h"
|
#include "effects_chain.h"
|
||||||
#include "banner_ext.h"
|
#include "banner_ext.h"
|
||||||
#include "banner_color.h"
|
#include "banner_color.h"
|
||||||
|
#include "compositor_internal.h"
|
||||||
|
|
||||||
#define WLOGI(...) __android_log_print(ANDROID_LOG_INFO, "BannerWayland", __VA_ARGS__)
|
#define WLOGI(...) __android_log_print(ANDROID_LOG_INFO, "BannerWayland", __VA_ARGS__)
|
||||||
#define WLOGE(...) __android_log_print(ANDROID_LOG_ERROR, "BannerWayland", __VA_ARGS__)
|
#define WLOGE(...) __android_log_print(ANDROID_LOG_ERROR, "BannerWayland", __VA_ARGS__)
|
||||||
@@ -161,21 +162,9 @@ static int log_budget(void) {
|
|||||||
|
|
||||||
static struct wl_display *g_display;
|
static struct wl_display *g_display;
|
||||||
|
|
||||||
/* Which program each Wayland client is (from /proc/<pid>/cmdline), for the session log. */
|
|
||||||
struct client_info {
|
|
||||||
struct wl_client *client;
|
|
||||||
struct wl_listener destroy;
|
|
||||||
pid_t pid;
|
|
||||||
char name[64];
|
|
||||||
/* An OpenGL program whose EGL gave up on the GPU: it asked for dma-buf feedback (EGL's
|
|
||||||
* Wayland GPU path always does), never made a dma-buf buffer, and draws wl_shm frames. */
|
|
||||||
unsigned asked_feedback : 1, shm_gl_said : 1;
|
|
||||||
unsigned dmabuf_buffers, shm_frames;
|
|
||||||
struct client_info *next;
|
|
||||||
};
|
|
||||||
static struct client_info *g_clients;
|
static struct client_info *g_clients;
|
||||||
|
|
||||||
static struct client_info *client_info_of(struct wl_client *client) {
|
struct client_info *client_info_of(struct wl_client *client) {
|
||||||
for (struct client_info *ci = g_clients; ci; ci = ci->next)
|
for (struct client_info *ci = g_clients; ci; ci = ci->next)
|
||||||
if (ci->client == client) return ci;
|
if (ci->client == client) return ci;
|
||||||
return NULL;
|
return NULL;
|
||||||
@@ -500,7 +489,7 @@ static void cursor_publish_hidden(void) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
static void cursor_publish_pixels(const uint8_t *src, int w, int h, size_t stride, int hx, int hy) {
|
static void cursor_publish_pixels(const uint8_t *src, int w, int h, size_t stride, int hx, int hy) {
|
||||||
if (w <= 0 || h <= 0 || w * h > CURSOR_MAX_PX) return;
|
if (w <= 0 || h <= 0 || (int64_t)w * h > CURSOR_MAX_PX) return;
|
||||||
pthread_mutex_lock(&g_cursor_lock);
|
pthread_mutex_lock(&g_cursor_lock);
|
||||||
for (int y = 0; y < h; y++)
|
for (int y = 0; y < h; y++)
|
||||||
memcpy(&g_cursor_px[y * w], src + (size_t)y * stride, (size_t)w * 4);
|
memcpy(&g_cursor_px[y * w], src + (size_t)y * stride, (size_t)w * 4);
|
||||||
@@ -513,10 +502,13 @@ static void cursor_publish_pixels(const uint8_t *src, int w, int h, size_t strid
|
|||||||
|
|
||||||
static void cursor_publish_shm(struct wl_shm_buffer *shm, int hx, int hy) {
|
static void cursor_publish_shm(struct wl_shm_buffer *shm, int hx, int hy) {
|
||||||
int32_t w = wl_shm_buffer_get_width(shm), h = wl_shm_buffer_get_height(shm);
|
int32_t w = wl_shm_buffer_get_width(shm), h = wl_shm_buffer_get_height(shm);
|
||||||
if (w <= 0 || h <= 0 || w * h > CURSOR_MAX_PX) return;
|
int32_t stride = wl_shm_buffer_get_stride(shm);
|
||||||
|
if (w <= 0 || h <= 0 || (int64_t)w * h > CURSOR_MAX_PX) return;
|
||||||
|
/* libwayland only promises stride >= width; each row copied here is width * 4 bytes, so a
|
||||||
|
* shorter stride would read past the end of the client's pool. */
|
||||||
|
if ((int64_t)stride < (int64_t)w * 4) return;
|
||||||
wl_shm_buffer_begin_access(shm);
|
wl_shm_buffer_begin_access(shm);
|
||||||
cursor_publish_pixels((const uint8_t *)wl_shm_buffer_get_data(shm), w, h,
|
cursor_publish_pixels((const uint8_t *)wl_shm_buffer_get_data(shm), w, h, (size_t)stride, hx, hy);
|
||||||
(size_t)wl_shm_buffer_get_stride(shm), hx, hy);
|
|
||||||
wl_shm_buffer_end_access(shm);
|
wl_shm_buffer_end_access(shm);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -557,40 +549,7 @@ static void constraints_focus_entered(struct wl_resource *target, struct wl_clie
|
|||||||
|
|
||||||
/* ------------------------------------------------------------------ dmabuf buffers */
|
/* ------------------------------------------------------------------ dmabuf buffers */
|
||||||
|
|
||||||
#define FOURCC(a, b, c, d) \
|
void dmabuf_buffer_unref(struct dmabuf_buffer *b) {
|
||||||
((uint32_t)(a) | ((uint32_t)(b) << 8) | ((uint32_t)(c) << 16) | ((uint32_t)(d) << 24))
|
|
||||||
#define DRM_ARGB8888 FOURCC('A', 'R', '2', '4')
|
|
||||||
#define DRM_XRGB8888 FOURCC('X', 'R', '2', '4')
|
|
||||||
#define DRM_ABGR8888 FOURCC('A', 'B', '2', '4')
|
|
||||||
#define DRM_XBGR8888 FOURCC('X', 'B', '2', '4')
|
|
||||||
#define MOD_LINEAR VKP_MOD_LINEAR
|
|
||||||
#define MOD_INVALID VKP_MOD_INVALID
|
|
||||||
#define MAX_PLANES 4
|
|
||||||
|
|
||||||
struct dmabuf_params {
|
|
||||||
int fd[MAX_PLANES];
|
|
||||||
uint32_t offset[MAX_PLANES], stride[MAX_PLANES];
|
|
||||||
uint64_t modifier[MAX_PLANES];
|
|
||||||
int n_planes;
|
|
||||||
};
|
|
||||||
struct dmabuf_buffer {
|
|
||||||
int fd[MAX_PLANES];
|
|
||||||
uint32_t offset[MAX_PLANES], stride[MAX_PLANES];
|
|
||||||
int n_planes;
|
|
||||||
int32_t width, height;
|
|
||||||
uint32_t format;
|
|
||||||
uint64_t modifier;
|
|
||||||
struct vkp_image *img; /* imported once, reused for every frame */
|
|
||||||
int import_failed;
|
|
||||||
/* One reference for the wl_buffer resource, one per surface showing the buffer. Mesa destroys
|
|
||||||
* a swapchain's wl_buffers the moment the game rebuilds its swapchain, i.e. while the last
|
|
||||||
* committed one is still what is on screen: the import (and the dma-buf memory it pins) stays
|
|
||||||
* until the surface commits something newer, so the picture never blinks to black. */
|
|
||||||
int refs;
|
|
||||||
void *ahb_state; /* zero-copy: ahb_swapchain.c's record (the game's AHardwareBuffer) */
|
|
||||||
};
|
|
||||||
|
|
||||||
static void dmabuf_buffer_unref(struct dmabuf_buffer *b) {
|
|
||||||
if (!b || --b->refs > 0) return;
|
if (!b || --b->refs > 0) return;
|
||||||
vkp_image_destroy(b->img);
|
vkp_image_destroy(b->img);
|
||||||
for (int i = 0; i < b->n_planes; i++)
|
for (int i = 0; i < b->n_planes; i++)
|
||||||
@@ -601,7 +560,7 @@ static void dmabuf_buffer_unref(struct dmabuf_buffer *b) {
|
|||||||
static void dbuf_buffer_destroy_req(struct wl_client *c, struct wl_resource *r) {
|
static void dbuf_buffer_destroy_req(struct wl_client *c, struct wl_resource *r) {
|
||||||
wl_resource_destroy(r);
|
wl_resource_destroy(r);
|
||||||
}
|
}
|
||||||
static const struct wl_buffer_interface dbuf_buffer_impl = {
|
const struct wl_buffer_interface dbuf_buffer_impl = {
|
||||||
.destroy = dbuf_buffer_destroy_req,
|
.destroy = dbuf_buffer_destroy_req,
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -1018,7 +977,8 @@ static void surface_commit(struct wl_client *c, struct wl_resource *r) {
|
|||||||
cursor_publish_hidden(); /* wlroots clears its cursor surface to hide the pointer */
|
cursor_publish_hidden(); /* wlroots clears its cursor surface to hide the pointer */
|
||||||
} else if (shm) {
|
} else if (shm) {
|
||||||
cursor_publish_shm(shm, g_cursor_hx, g_cursor_hy);
|
cursor_publish_shm(shm, g_cursor_hx, g_cursor_hy);
|
||||||
} else if (db && db->n_planes >= 1 && db->width * db->height <= CURSOR_MAX_PX) {
|
} else if (db && db->n_planes >= 1 && db->width > 0 && db->height > 0 &&
|
||||||
|
(int64_t)db->width * db->height <= CURSOR_MAX_PX) {
|
||||||
if (!db->img && !db->import_failed) {
|
if (!db->img && !db->import_failed) {
|
||||||
db->img = vkp_image_from_dmabuf(db->fd[0], db->format, db->modifier, db->width, db->height,
|
db->img = vkp_image_from_dmabuf(db->fd[0], db->format, db->modifier, db->width, db->height,
|
||||||
db->stride[0], db->offset[0]);
|
db->stride[0], db->offset[0]);
|
||||||
@@ -1570,319 +1530,6 @@ static void bind_desktop(struct wl_client *c, void *data, uint32_t ver, uint32_t
|
|||||||
wl_resource_set_implementation(r, &desktop_impl, NULL, NULL);
|
wl_resource_set_implementation(r, &desktop_impl, NULL, NULL);
|
||||||
}
|
}
|
||||||
|
|
||||||
/* ------------------------------------------------------------ zwp_linux_dmabuf_v1 */
|
|
||||||
|
|
||||||
static void dbuf_buffer_resource_destroy(struct wl_resource *r) {
|
|
||||||
dmabuf_buffer_unref(wl_resource_get_user_data(r));
|
|
||||||
}
|
|
||||||
|
|
||||||
static void params_destroy(struct wl_client *c, struct wl_resource *r) { wl_resource_destroy(r); }
|
|
||||||
static void params_add(struct wl_client *c, struct wl_resource *r, int32_t fd, uint32_t plane,
|
|
||||||
uint32_t offset, uint32_t stride, uint32_t mod_hi, uint32_t mod_lo) {
|
|
||||||
struct dmabuf_params *p = wl_resource_get_user_data(r);
|
|
||||||
if (plane >= MAX_PLANES) { close(fd); return; }
|
|
||||||
if (p->fd[plane] >= 0) close(p->fd[plane]);
|
|
||||||
p->fd[plane] = fd;
|
|
||||||
p->offset[plane] = offset;
|
|
||||||
p->stride[plane] = stride;
|
|
||||||
p->modifier[plane] = ((uint64_t)mod_hi << 32) | mod_lo;
|
|
||||||
if ((int)plane + 1 > p->n_planes) p->n_planes = plane + 1;
|
|
||||||
}
|
|
||||||
static struct wl_resource *params_do_create(struct wl_client *c, struct wl_resource *r, uint32_t id,
|
|
||||||
int32_t w, int32_t h, uint32_t format, uint32_t flags) {
|
|
||||||
struct dmabuf_params *p = wl_resource_get_user_data(r);
|
|
||||||
struct dmabuf_buffer *b = calloc(1, sizeof(*b));
|
|
||||||
if (!b) return NULL;
|
|
||||||
b->n_planes = p->n_planes;
|
|
||||||
b->refs = 1; /* the wl_buffer resource's */
|
|
||||||
b->width = w; b->height = h; b->format = format;
|
|
||||||
b->modifier = p->modifier[0];
|
|
||||||
for (int i = 0; i < MAX_PLANES; i++) b->fd[i] = -1;
|
|
||||||
for (int i = 0; i < p->n_planes; i++) {
|
|
||||||
b->fd[i] = p->fd[i];
|
|
||||||
b->offset[i] = p->offset[i];
|
|
||||||
b->stride[i] = p->stride[i];
|
|
||||||
p->fd[i] = -1; /* ownership moves to the buffer */
|
|
||||||
}
|
|
||||||
struct wl_resource *buf = wl_resource_create(c, &wl_buffer_interface, 1, id);
|
|
||||||
if (!buf) {
|
|
||||||
for (int i = 0; i < b->n_planes; i++) if (b->fd[i] >= 0) close(b->fd[i]);
|
|
||||||
free(b);
|
|
||||||
wl_client_post_no_memory(c);
|
|
||||||
return NULL;
|
|
||||||
}
|
|
||||||
wl_resource_set_implementation(buf, &dbuf_buffer_impl, b, dbuf_buffer_resource_destroy);
|
|
||||||
struct client_info *ci = client_info_of(c);
|
|
||||||
if (ci) ci->dmabuf_buffers++;
|
|
||||||
return buf;
|
|
||||||
}
|
|
||||||
static void params_create(struct wl_client *c, struct wl_resource *r, int32_t w, int32_t h,
|
|
||||||
uint32_t format, uint32_t flags) {
|
|
||||||
struct wl_resource *buf = params_do_create(c, r, 0, w, h, format, flags);
|
|
||||||
if (buf) zwp_linux_buffer_params_v1_send_created(r, buf);
|
|
||||||
else zwp_linux_buffer_params_v1_send_failed(r);
|
|
||||||
}
|
|
||||||
static void params_create_immed(struct wl_client *c, struct wl_resource *r, uint32_t buffer_id,
|
|
||||||
int32_t w, int32_t h, uint32_t format, uint32_t flags) {
|
|
||||||
params_do_create(c, r, buffer_id, w, h, format, flags);
|
|
||||||
}
|
|
||||||
static const struct zwp_linux_buffer_params_v1_interface params_impl = {
|
|
||||||
.destroy = params_destroy,
|
|
||||||
.add = params_add,
|
|
||||||
.create = params_create,
|
|
||||||
.create_immed = params_create_immed,
|
|
||||||
};
|
|
||||||
static void params_resource_destroy(struct wl_resource *r) {
|
|
||||||
struct dmabuf_params *p = wl_resource_get_user_data(r);
|
|
||||||
if (!p) return;
|
|
||||||
for (int i = 0; i < MAX_PLANES; i++)
|
|
||||||
if (p->fd[i] >= 0) close(p->fd[i]);
|
|
||||||
free(p);
|
|
||||||
}
|
|
||||||
|
|
||||||
static void dmabuf_destroy(struct wl_client *c, struct wl_resource *r) { wl_resource_destroy(r); }
|
|
||||||
static void dmabuf_create_params(struct wl_client *c, struct wl_resource *r, uint32_t id) {
|
|
||||||
struct dmabuf_params *p = calloc(1, sizeof(*p));
|
|
||||||
if (!p) { wl_client_post_no_memory(c); return; }
|
|
||||||
for (int i = 0; i < MAX_PLANES; i++) p->fd[i] = -1;
|
|
||||||
struct wl_resource *pr = wl_resource_create(c, &zwp_linux_buffer_params_v1_interface,
|
|
||||||
wl_resource_get_version(r), id);
|
|
||||||
if (!pr) { free(p); wl_client_post_no_memory(c); return; }
|
|
||||||
wl_resource_set_implementation(pr, ¶ms_impl, p, params_resource_destroy);
|
|
||||||
}
|
|
||||||
static void dmabuf_get_default_feedback(struct wl_client *c, struct wl_resource *r, uint32_t id);
|
|
||||||
static void dmabuf_get_surface_feedback(struct wl_client *c, struct wl_resource *r, uint32_t id,
|
|
||||||
struct wl_resource *surface);
|
|
||||||
static const struct zwp_linux_dmabuf_v1_interface dmabuf_impl = {
|
|
||||||
.destroy = dmabuf_destroy,
|
|
||||||
.create_params = dmabuf_create_params,
|
|
||||||
.get_default_feedback = dmabuf_get_default_feedback,
|
|
||||||
.get_surface_feedback = dmabuf_get_surface_feedback,
|
|
||||||
};
|
|
||||||
/* The advertised format/modifier table, built at the first bind from what the renderer's driver
|
|
||||||
* can import (vkp_dmabuf_modifiers). INVALID is always offered too (Mesa drops it; other clients
|
|
||||||
* may use it for the implicit path). Without a renderer the list is LINEAR + INVALID, as before. */
|
|
||||||
/* The last two rows are HDR10's (banner_color.h): A2B10G10R10 as AB30 (alpha) + XB30 (opaque) - Mesa
|
|
||||||
* lists a VkFormat only when both are advertised, and it is the one 10-bit layout our zero-copy WSI
|
|
||||||
* can put in a gralloc buffer (AHARDWAREBUFFER_FORMAT_R10G10B10A2_UNORM). They are advertised ONLY
|
|
||||||
* while the HDR gate is open, and after the 8-bit rows, so every other session - and every client that
|
|
||||||
* takes the first format it sees - gets exactly the table it always had. */
|
|
||||||
#define DMABUF_NFMT_MAX 6
|
|
||||||
#define DMABUF_NFMT_SDR 4
|
|
||||||
#define DMABUF_NMOD 4
|
|
||||||
#define DRM_ABGR2101010 FOURCC('A', 'B', '3', '0')
|
|
||||||
#define DRM_XBGR2101010 FOURCC('X', 'B', '3', '0')
|
|
||||||
static struct { uint32_t fmt; uint64_t mods[DMABUF_NMOD]; int n; } g_dmabuf_fmts[DMABUF_NFMT_MAX] = {
|
|
||||||
{DRM_ARGB8888}, {DRM_XRGB8888}, {DRM_ABGR8888}, {DRM_XBGR8888}, {DRM_ABGR2101010}, {DRM_XBGR2101010}};
|
|
||||||
static int g_dmabuf_nfmt = DMABUF_NFMT_SDR; /* rows advertised: the SDR four, + 2 with the HDR gate open */
|
|
||||||
static int g_dmabuf_fmts_ready;
|
|
||||||
static void dmabuf_build_feedback(void);
|
|
||||||
|
|
||||||
static void dmabuf_build_formats(void) {
|
|
||||||
char line[320];
|
|
||||||
int pos = 0, compressed = 0;
|
|
||||||
g_dmabuf_fmts_ready = 1;
|
|
||||||
g_dmabuf_nfmt = banner_color_hdr_open() ? DMABUF_NFMT_MAX : DMABUF_NFMT_SDR;
|
|
||||||
for (int f = 0; f < g_dmabuf_nfmt; f++) {
|
|
||||||
uint64_t got[DMABUF_NMOD];
|
|
||||||
int n = vkp_dmabuf_modifiers(g_dmabuf_fmts[f].fmt, got, DMABUF_NMOD), k = 0;
|
|
||||||
/* LINEAR first: it is the layout every client and the shm fallback agree on, and the one
|
|
||||||
* we advertised before this table existed. */
|
|
||||||
g_dmabuf_fmts[f].mods[k++] = MOD_LINEAR;
|
|
||||||
for (int i = 0; i < n && k < DMABUF_NMOD - 1; i++) {
|
|
||||||
if (got[i] == MOD_LINEAR) continue;
|
|
||||||
if (got[i] == VKP_MOD_QCOM_COMPRESSED && !g_ubwc) continue;
|
|
||||||
g_dmabuf_fmts[f].mods[k++] = got[i];
|
|
||||||
if (got[i] == VKP_MOD_QCOM_COMPRESSED) compressed++;
|
|
||||||
}
|
|
||||||
g_dmabuf_fmts[f].mods[k++] = MOD_INVALID;
|
|
||||||
g_dmabuf_fmts[f].n = k;
|
|
||||||
uint32_t fmt = g_dmabuf_fmts[f].fmt;
|
|
||||||
pos += snprintf(line + pos, sizeof(line) - (size_t)pos, "%s%c%c%c%c", f ? ", " : "",
|
|
||||||
fmt & 0xff, (fmt >> 8) & 0xff, (fmt >> 16) & 0xff, (fmt >> 24) & 0xff);
|
|
||||||
for (int i = 0; i < k - 1 && pos < (int)sizeof(line); i++)
|
|
||||||
pos += snprintf(line + pos, sizeof(line) - (size_t)pos, "%s%s", i ? "+" : " ",
|
|
||||||
vkp_modifier_name(g_dmabuf_fmts[f].mods[i]));
|
|
||||||
if (pos >= (int)sizeof(line)) pos = (int)sizeof(line) - 1;
|
|
||||||
}
|
|
||||||
banner_log("dmabuf", "formats: %s%s", line,
|
|
||||||
!g_ubwc ? " (BANNER_WAYLAND_UBWC=0: qcom_compressed not advertised)" : "");
|
|
||||||
if (g_ubwc && !compressed)
|
|
||||||
banner_log("dmabuf", "the compositor's driver (%s) reports no importable qcom_compressed layout: "
|
|
||||||
"game swapchains stay linear", vkp_gpu_name());
|
|
||||||
if (g_dmabuf_nfmt > DMABUF_NFMT_SDR) {
|
|
||||||
/* The rows above always carry LINEAR; say what the compositor's own driver can really import
|
|
||||||
* for 10-bit, since a gralloc buffer it cannot import is shown on the display layer only. */
|
|
||||||
uint64_t got[DMABUF_NMOD];
|
|
||||||
int n = vkp_dmabuf_modifiers(DRM_XBGR2101010, got, DMABUF_NMOD), ubwc10 = 0;
|
|
||||||
for (int i = 0; i < n; i++) if (got[i] == VKP_MOD_QCOM_COMPRESSED) ubwc10 = 1;
|
|
||||||
banner_log("color", "10-bit dma-buf formats AB30/XB30 advertised for HDR10; the compositor's driver (%s) "
|
|
||||||
"imports XB30 %s", vkp_gpu_name(),
|
|
||||||
n == 0 ? "with no layout it reports (copy path unlikely; display layer only)"
|
|
||||||
: ubwc10 ? "linear and UBWC" : "linear only (UBWC 10-bit frames: display layer only)");
|
|
||||||
}
|
|
||||||
dmabuf_build_feedback();
|
|
||||||
}
|
|
||||||
|
|
||||||
/* ---- dmabuf feedback (zwp_linux_dmabuf_v1 version 4)
|
|
||||||
*
|
|
||||||
* Turnip's Vulkan WSI is happy with the version 3 format/modifier events, so every Vulkan game
|
|
||||||
* worked while we only advertised 3. Mesa's EGL is not: its Wayland platform only takes the GPU
|
|
||||||
* (kopper/Zink) path when it can bind this interface with FEEDBACK, and with 3 it silently drops
|
|
||||||
* to its wl_shm software path. On this Proton layer that path has no software rasteriser to fall
|
|
||||||
* back to (the gallium build is zink+kopper+swrast, no llvmpipe), so the shm buffer it commits is
|
|
||||||
* never written: a native OpenGL window came out solid black, ~30 shm commits/s and no GPU frame
|
|
||||||
* at all (Wizardry: The Labyrinth of Lost Souls). Feedback is what makes that path work.
|
|
||||||
*
|
|
||||||
* What a client needs from us is one tranche describing "everything the compositor can import":
|
|
||||||
* a format table it mmaps read-only, the device to allocate on, and the indices it may use.
|
|
||||||
* Clients binding versions 1-3 keep getting the old format/modifier events instead. */
|
|
||||||
|
|
||||||
#ifndef MFD_CLOEXEC
|
|
||||||
#define MFD_CLOEXEC 0x0001U
|
|
||||||
#endif
|
|
||||||
#ifndef MFD_ALLOW_SEALING
|
|
||||||
#define MFD_ALLOW_SEALING 0x0002U
|
|
||||||
#endif
|
|
||||||
#ifndef F_ADD_SEALS
|
|
||||||
#define F_ADD_SEALS 1033
|
|
||||||
#define F_SEAL_SEAL 0x0001
|
|
||||||
#define F_SEAL_SHRINK 0x0002
|
|
||||||
#define F_SEAL_GROW 0x0004
|
|
||||||
#define F_SEAL_WRITE 0x0008
|
|
||||||
#endif
|
|
||||||
|
|
||||||
struct dmabuf_fmt_entry { uint32_t format; uint32_t pad; uint64_t modifier; }; /* the wire layout */
|
|
||||||
|
|
||||||
static int g_fmt_table_fd = -1; /* sealed read-only memfd of dmabuf_fmt_entry[] */
|
|
||||||
static size_t g_fmt_table_size;
|
|
||||||
static uint16_t g_fmt_table_n; /* entries, == the indices a tranche may name */
|
|
||||||
static dev_t g_main_device; /* the render node clients should allocate on */
|
|
||||||
|
|
||||||
/* The GPU we import through is reached with KGSL, not DRM, so there is no render node of our own
|
|
||||||
* to name. Clients only use main_device to match "the same device as the compositor" and to pick
|
|
||||||
* a driver; the one DRM render node this platform has is the right answer, and Zink ignores it
|
|
||||||
* anyway (it renders on the Vulkan device it already has). 0 if the platform has none. */
|
|
||||||
static dev_t dmabuf_render_node(void) {
|
|
||||||
static const char *nodes[] = {"/dev/dri/renderD128", "/dev/dri/renderD129", "/dev/dri/card0"};
|
|
||||||
struct stat st;
|
|
||||||
if (g_no_render_node) return 0;
|
|
||||||
for (size_t i = 0; i < sizeof(nodes) / sizeof(nodes[0]); i++)
|
|
||||||
if (!stat(nodes[i], &st) && S_ISCHR(st.st_mode)) return st.st_rdev;
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
static void dmabuf_build_feedback(void) {
|
|
||||||
struct dmabuf_fmt_entry entries[DMABUF_NFMT_MAX * DMABUF_NMOD];
|
|
||||||
int n = 0;
|
|
||||||
|
|
||||||
g_main_device = dmabuf_render_node();
|
|
||||||
for (int f = 0; f < g_dmabuf_nfmt; f++)
|
|
||||||
for (int m = 0; m < g_dmabuf_fmts[f].n; m++) {
|
|
||||||
if (g_dmabuf_fmts[f].mods[m] == MOD_INVALID) continue; /* never offer INVALID here */
|
|
||||||
entries[n].format = g_dmabuf_fmts[f].fmt;
|
|
||||||
entries[n].pad = 0;
|
|
||||||
entries[n].modifier = g_dmabuf_fmts[f].mods[m];
|
|
||||||
n++;
|
|
||||||
}
|
|
||||||
if (!n) return;
|
|
||||||
|
|
||||||
int fd = (int)syscall(__NR_memfd_create, "banner-dmabuf-formats",
|
|
||||||
MFD_CLOEXEC | MFD_ALLOW_SEALING);
|
|
||||||
if (fd < 0) { WLOGE("dmabuf feedback: memfd_create failed (%s)", strerror(errno)); return; }
|
|
||||||
size_t size = (size_t)n * sizeof(entries[0]);
|
|
||||||
if (write(fd, entries, size) != (ssize_t)size) {
|
|
||||||
WLOGE("dmabuf feedback: could not write the format table (%s)", strerror(errno));
|
|
||||||
close(fd);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
/* The client mmaps this read-only and trusts it not to change under it. */
|
|
||||||
fcntl(fd, F_ADD_SEALS, F_SEAL_SEAL | F_SEAL_SHRINK | F_SEAL_GROW | F_SEAL_WRITE);
|
|
||||||
g_fmt_table_fd = fd;
|
|
||||||
g_fmt_table_size = size;
|
|
||||||
g_fmt_table_n = (uint16_t)n;
|
|
||||||
banner_log("dmabuf", "feedback ready: %d format/modifier pairs, main device %u:%u",
|
|
||||||
n, (unsigned)major(g_main_device), (unsigned)minor(g_main_device));
|
|
||||||
/* Vulkan games never need the node. Mesa's EGL did until Wayland layer versionCode 9: without
|
|
||||||
* one it fell back to a software path that draws nothing here (black window, sound plays). */
|
|
||||||
if (!g_main_device)
|
|
||||||
banner_log("dmabuf", "%s: OpenGL games need Wayland layer versionCode 9 or newer, "
|
|
||||||
"which runs OpenGL on the GPU without a DRM node; older layers show a black window",
|
|
||||||
g_no_render_node ? "no DRM device named (forced by BANNER_WAYLAND_NO_RENDER_NODE=1)"
|
|
||||||
: "this device gives apps no display (DRM) device (/dev/dri)");
|
|
||||||
}
|
|
||||||
|
|
||||||
/* One tranche: our device, every pair in the table, no scanout flag. */
|
|
||||||
static void dmabuf_feedback_send(struct wl_resource *fb) {
|
|
||||||
struct wl_array dev, idx;
|
|
||||||
uint16_t *ind;
|
|
||||||
|
|
||||||
if (g_fmt_table_fd < 0) { zwp_linux_dmabuf_feedback_v1_send_done(fb); return; }
|
|
||||||
|
|
||||||
zwp_linux_dmabuf_feedback_v1_send_format_table(fb, g_fmt_table_fd, (uint32_t)g_fmt_table_size);
|
|
||||||
|
|
||||||
wl_array_init(&dev);
|
|
||||||
memcpy(wl_array_add(&dev, sizeof(dev_t)), &g_main_device, sizeof(dev_t));
|
|
||||||
zwp_linux_dmabuf_feedback_v1_send_main_device(fb, &dev);
|
|
||||||
zwp_linux_dmabuf_feedback_v1_send_tranche_target_device(fb, &dev);
|
|
||||||
wl_array_release(&dev);
|
|
||||||
|
|
||||||
wl_array_init(&idx);
|
|
||||||
ind = wl_array_add(&idx, (size_t)g_fmt_table_n * sizeof(uint16_t));
|
|
||||||
if (ind) for (uint16_t i = 0; i < g_fmt_table_n; i++) ind[i] = i;
|
|
||||||
zwp_linux_dmabuf_feedback_v1_send_tranche_formats(fb, &idx);
|
|
||||||
wl_array_release(&idx);
|
|
||||||
|
|
||||||
zwp_linux_dmabuf_feedback_v1_send_tranche_flags(fb, 0);
|
|
||||||
zwp_linux_dmabuf_feedback_v1_send_tranche_done(fb);
|
|
||||||
zwp_linux_dmabuf_feedback_v1_send_done(fb);
|
|
||||||
}
|
|
||||||
|
|
||||||
static void dmabuf_feedback_destroy(struct wl_client *c, struct wl_resource *r) {
|
|
||||||
wl_resource_destroy(r);
|
|
||||||
}
|
|
||||||
static const struct zwp_linux_dmabuf_feedback_v1_interface dmabuf_feedback_impl = {
|
|
||||||
.destroy = dmabuf_feedback_destroy,
|
|
||||||
};
|
|
||||||
|
|
||||||
static void dmabuf_new_feedback(struct wl_client *c, struct wl_resource *parent, uint32_t id) {
|
|
||||||
struct wl_resource *fb = wl_resource_create(c, &zwp_linux_dmabuf_feedback_v1_interface,
|
|
||||||
wl_resource_get_version(parent), id);
|
|
||||||
if (!fb) { wl_client_post_no_memory(c); return; }
|
|
||||||
wl_resource_set_implementation(fb, &dmabuf_feedback_impl, NULL, NULL);
|
|
||||||
if (!g_dmabuf_fmts_ready) dmabuf_build_formats();
|
|
||||||
dmabuf_feedback_send(fb);
|
|
||||||
}
|
|
||||||
|
|
||||||
static void dmabuf_get_default_feedback(struct wl_client *c, struct wl_resource *r, uint32_t id) {
|
|
||||||
struct client_info *ci = client_info_of(c);
|
|
||||||
if (ci) ci->asked_feedback = 1;
|
|
||||||
dmabuf_new_feedback(c, r, id);
|
|
||||||
}
|
|
||||||
/* Per-surface feedback would let us hint a different tranche for a window on its own display
|
|
||||||
* layer; we have nothing better to say per surface, so it is the default one. */
|
|
||||||
static void dmabuf_get_surface_feedback(struct wl_client *c, struct wl_resource *r, uint32_t id,
|
|
||||||
struct wl_resource *surface) {
|
|
||||||
dmabuf_new_feedback(c, r, id);
|
|
||||||
}
|
|
||||||
|
|
||||||
static void bind_dmabuf(struct wl_client *c, void *data, uint32_t ver, uint32_t id) {
|
|
||||||
struct wl_resource *r = wl_resource_create(c, &zwp_linux_dmabuf_v1_interface, ver, id);
|
|
||||||
wl_resource_set_implementation(r, &dmabuf_impl, NULL, NULL);
|
|
||||||
if (!g_dmabuf_fmts_ready) dmabuf_build_formats();
|
|
||||||
/* From version 4 the format and modifier events are gone: the client asks for feedback
|
|
||||||
* instead, and sending both would only confuse it about which list is authoritative. */
|
|
||||||
if (ver >= 4) return;
|
|
||||||
for (int f = 0; f < g_dmabuf_nfmt; f++) {
|
|
||||||
zwp_linux_dmabuf_v1_send_format(r, g_dmabuf_fmts[f].fmt);
|
|
||||||
if (ver >= 3)
|
|
||||||
for (int m = 0; m < g_dmabuf_fmts[f].n; m++)
|
|
||||||
zwp_linux_dmabuf_v1_send_modifier(r, g_dmabuf_fmts[f].fmt,
|
|
||||||
(uint32_t)(g_dmabuf_fmts[f].mods[m] >> 32),
|
|
||||||
(uint32_t)(g_dmabuf_fmts[f].mods[m] & 0xffffffff));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/* ------------------------------------------------------------------ wl_output */
|
/* ------------------------------------------------------------------ wl_output */
|
||||||
|
|
||||||
/* wl_output v3+ has a request (release); without an implementation the first client to send it
|
/* wl_output v3+ has a request (release); without an implementation the first client to send it
|
||||||
|
|||||||
@@ -0,0 +1,76 @@
|
|||||||
|
/*
|
||||||
|
* What compositor.c shares with the protocol modules split out of it (wl_dmabuf.c): the dma-buf
|
||||||
|
* buffer records, the per-client bookkeeping and the few functions and globals both sides use.
|
||||||
|
* Everything declared here is hidden: it is internal to libbannerwayland, not part of its ABI.
|
||||||
|
*/
|
||||||
|
#pragma once
|
||||||
|
#include <stdint.h>
|
||||||
|
#include <sys/types.h>
|
||||||
|
#include <android/log.h>
|
||||||
|
#include <wayland-server.h>
|
||||||
|
#include "vk_present.h"
|
||||||
|
|
||||||
|
#define COMPOSITOR_INTERNAL __attribute__((visibility("hidden")))
|
||||||
|
|
||||||
|
#ifndef WLOGE
|
||||||
|
#define WLOGE(...) __android_log_print(ANDROID_LOG_ERROR, "BannerWayland", __VA_ARGS__)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/* ------------------------------------------------------------------ dmabuf buffers */
|
||||||
|
|
||||||
|
#define FOURCC(a, b, c, d) \
|
||||||
|
((uint32_t)(a) | ((uint32_t)(b) << 8) | ((uint32_t)(c) << 16) | ((uint32_t)(d) << 24))
|
||||||
|
#define DRM_ARGB8888 FOURCC('A', 'R', '2', '4')
|
||||||
|
#define DRM_XRGB8888 FOURCC('X', 'R', '2', '4')
|
||||||
|
#define DRM_ABGR8888 FOURCC('A', 'B', '2', '4')
|
||||||
|
#define DRM_XBGR8888 FOURCC('X', 'B', '2', '4')
|
||||||
|
#define MOD_LINEAR VKP_MOD_LINEAR
|
||||||
|
#define MOD_INVALID VKP_MOD_INVALID
|
||||||
|
#define MAX_PLANES 4
|
||||||
|
|
||||||
|
struct dmabuf_params {
|
||||||
|
int fd[MAX_PLANES];
|
||||||
|
uint32_t offset[MAX_PLANES], stride[MAX_PLANES];
|
||||||
|
uint64_t modifier[MAX_PLANES];
|
||||||
|
int n_planes;
|
||||||
|
};
|
||||||
|
struct dmabuf_buffer {
|
||||||
|
int fd[MAX_PLANES];
|
||||||
|
uint32_t offset[MAX_PLANES], stride[MAX_PLANES];
|
||||||
|
int n_planes;
|
||||||
|
int32_t width, height;
|
||||||
|
uint32_t format;
|
||||||
|
uint64_t modifier;
|
||||||
|
struct vkp_image *img; /* imported once, reused for every frame */
|
||||||
|
int import_failed;
|
||||||
|
/* One reference for the wl_buffer resource, one per surface showing the buffer. Mesa destroys
|
||||||
|
* a swapchain's wl_buffers the moment the game rebuilds its swapchain, i.e. while the last
|
||||||
|
* committed one is still what is on screen: the import (and the dma-buf memory it pins) stays
|
||||||
|
* until the surface commits something newer, so the picture never blinks to black. */
|
||||||
|
int refs;
|
||||||
|
void *ahb_state; /* zero-copy: ahb_swapchain.c's record (the game's AHardwareBuffer) */
|
||||||
|
};
|
||||||
|
|
||||||
|
/* Which program each Wayland client is (from /proc/<pid>/cmdline), for the session log. */
|
||||||
|
struct client_info {
|
||||||
|
struct wl_client *client;
|
||||||
|
struct wl_listener destroy;
|
||||||
|
pid_t pid;
|
||||||
|
char name[64];
|
||||||
|
/* An OpenGL program whose EGL gave up on the GPU: it asked for dma-buf feedback (EGL's
|
||||||
|
* Wayland GPU path always does), never made a dma-buf buffer, and draws wl_shm frames. */
|
||||||
|
unsigned asked_feedback : 1, shm_gl_said : 1;
|
||||||
|
unsigned dmabuf_buffers, shm_frames;
|
||||||
|
struct client_info *next;
|
||||||
|
};
|
||||||
|
|
||||||
|
/* ---- compositor.c */
|
||||||
|
COMPOSITOR_INTERNAL struct client_info *client_info_of(struct wl_client *client);
|
||||||
|
COMPOSITOR_INTERNAL void dmabuf_buffer_unref(struct dmabuf_buffer *b);
|
||||||
|
COMPOSITOR_INTERNAL extern const struct wl_buffer_interface dbuf_buffer_impl;
|
||||||
|
extern volatile int g_ubwc; /* BANNER_WAYLAND_UBWC (waylandcomp_jni.c sets it) */
|
||||||
|
extern volatile int g_no_render_node; /* BANNER_WAYLAND_NO_RENDER_NODE */
|
||||||
|
|
||||||
|
/* ---- wl_dmabuf.c */
|
||||||
|
COMPOSITOR_INTERNAL extern dev_t g_main_device; /* the render node clients are told to allocate on */
|
||||||
|
COMPOSITOR_INTERNAL void bind_dmabuf(struct wl_client *c, void *data, uint32_t ver, uint32_t id);
|
||||||
@@ -0,0 +1,334 @@
|
|||||||
|
/*
|
||||||
|
* zwp_linux_dmabuf_v1: the buffer params a client builds a dma-buf wl_buffer from, the format and
|
||||||
|
* modifier table the renderer can import, and dma-buf feedback (version 4). Split out of
|
||||||
|
* compositor.c; the buffer records themselves are in compositor_internal.h.
|
||||||
|
*/
|
||||||
|
#include <stdio.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include <string.h>
|
||||||
|
#include <unistd.h>
|
||||||
|
#include <fcntl.h>
|
||||||
|
#include <errno.h>
|
||||||
|
#include <sys/stat.h>
|
||||||
|
#include <sys/syscall.h>
|
||||||
|
#include <sys/sysmacros.h>
|
||||||
|
#include <wayland-server.h>
|
||||||
|
|
||||||
|
#include "linux-dmabuf-v1-server-protocol.h"
|
||||||
|
#include "vk_present.h"
|
||||||
|
#include "banner_ext.h"
|
||||||
|
#include "banner_color.h"
|
||||||
|
#include "compositor_internal.h"
|
||||||
|
|
||||||
|
/* ------------------------------------------------------------ zwp_linux_dmabuf_v1 */
|
||||||
|
|
||||||
|
static void dbuf_buffer_resource_destroy(struct wl_resource *r) {
|
||||||
|
dmabuf_buffer_unref(wl_resource_get_user_data(r));
|
||||||
|
}
|
||||||
|
|
||||||
|
static void params_destroy(struct wl_client *c, struct wl_resource *r) { wl_resource_destroy(r); }
|
||||||
|
static void params_add(struct wl_client *c, struct wl_resource *r, int32_t fd, uint32_t plane,
|
||||||
|
uint32_t offset, uint32_t stride, uint32_t mod_hi, uint32_t mod_lo) {
|
||||||
|
struct dmabuf_params *p = wl_resource_get_user_data(r);
|
||||||
|
if (plane >= MAX_PLANES) { close(fd); return; }
|
||||||
|
if (p->fd[plane] >= 0) close(p->fd[plane]);
|
||||||
|
p->fd[plane] = fd;
|
||||||
|
p->offset[plane] = offset;
|
||||||
|
p->stride[plane] = stride;
|
||||||
|
p->modifier[plane] = ((uint64_t)mod_hi << 32) | mod_lo;
|
||||||
|
if ((int)plane + 1 > p->n_planes) p->n_planes = plane + 1;
|
||||||
|
}
|
||||||
|
static struct wl_resource *params_do_create(struct wl_client *c, struct wl_resource *r, uint32_t id,
|
||||||
|
int32_t w, int32_t h, uint32_t format, uint32_t flags) {
|
||||||
|
struct dmabuf_params *p = wl_resource_get_user_data(r);
|
||||||
|
struct dmabuf_buffer *b = calloc(1, sizeof(*b));
|
||||||
|
if (!b) return NULL;
|
||||||
|
b->n_planes = p->n_planes;
|
||||||
|
b->refs = 1; /* the wl_buffer resource's */
|
||||||
|
b->width = w; b->height = h; b->format = format;
|
||||||
|
b->modifier = p->modifier[0];
|
||||||
|
for (int i = 0; i < MAX_PLANES; i++) b->fd[i] = -1;
|
||||||
|
for (int i = 0; i < p->n_planes; i++) {
|
||||||
|
b->fd[i] = p->fd[i];
|
||||||
|
b->offset[i] = p->offset[i];
|
||||||
|
b->stride[i] = p->stride[i];
|
||||||
|
p->fd[i] = -1; /* ownership moves to the buffer */
|
||||||
|
}
|
||||||
|
struct wl_resource *buf = wl_resource_create(c, &wl_buffer_interface, 1, id);
|
||||||
|
if (!buf) {
|
||||||
|
for (int i = 0; i < b->n_planes; i++) if (b->fd[i] >= 0) close(b->fd[i]);
|
||||||
|
free(b);
|
||||||
|
wl_client_post_no_memory(c);
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
wl_resource_set_implementation(buf, &dbuf_buffer_impl, b, dbuf_buffer_resource_destroy);
|
||||||
|
struct client_info *ci = client_info_of(c);
|
||||||
|
if (ci) ci->dmabuf_buffers++;
|
||||||
|
return buf;
|
||||||
|
}
|
||||||
|
static void params_create(struct wl_client *c, struct wl_resource *r, int32_t w, int32_t h,
|
||||||
|
uint32_t format, uint32_t flags) {
|
||||||
|
struct wl_resource *buf = params_do_create(c, r, 0, w, h, format, flags);
|
||||||
|
if (buf) zwp_linux_buffer_params_v1_send_created(r, buf);
|
||||||
|
else zwp_linux_buffer_params_v1_send_failed(r);
|
||||||
|
}
|
||||||
|
static void params_create_immed(struct wl_client *c, struct wl_resource *r, uint32_t buffer_id,
|
||||||
|
int32_t w, int32_t h, uint32_t format, uint32_t flags) {
|
||||||
|
params_do_create(c, r, buffer_id, w, h, format, flags);
|
||||||
|
}
|
||||||
|
static const struct zwp_linux_buffer_params_v1_interface params_impl = {
|
||||||
|
.destroy = params_destroy,
|
||||||
|
.add = params_add,
|
||||||
|
.create = params_create,
|
||||||
|
.create_immed = params_create_immed,
|
||||||
|
};
|
||||||
|
static void params_resource_destroy(struct wl_resource *r) {
|
||||||
|
struct dmabuf_params *p = wl_resource_get_user_data(r);
|
||||||
|
if (!p) return;
|
||||||
|
for (int i = 0; i < MAX_PLANES; i++)
|
||||||
|
if (p->fd[i] >= 0) close(p->fd[i]);
|
||||||
|
free(p);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void dmabuf_destroy(struct wl_client *c, struct wl_resource *r) { wl_resource_destroy(r); }
|
||||||
|
static void dmabuf_create_params(struct wl_client *c, struct wl_resource *r, uint32_t id) {
|
||||||
|
struct dmabuf_params *p = calloc(1, sizeof(*p));
|
||||||
|
if (!p) { wl_client_post_no_memory(c); return; }
|
||||||
|
for (int i = 0; i < MAX_PLANES; i++) p->fd[i] = -1;
|
||||||
|
struct wl_resource *pr = wl_resource_create(c, &zwp_linux_buffer_params_v1_interface,
|
||||||
|
wl_resource_get_version(r), id);
|
||||||
|
if (!pr) { free(p); wl_client_post_no_memory(c); return; }
|
||||||
|
wl_resource_set_implementation(pr, ¶ms_impl, p, params_resource_destroy);
|
||||||
|
}
|
||||||
|
static void dmabuf_get_default_feedback(struct wl_client *c, struct wl_resource *r, uint32_t id);
|
||||||
|
static void dmabuf_get_surface_feedback(struct wl_client *c, struct wl_resource *r, uint32_t id,
|
||||||
|
struct wl_resource *surface);
|
||||||
|
static const struct zwp_linux_dmabuf_v1_interface dmabuf_impl = {
|
||||||
|
.destroy = dmabuf_destroy,
|
||||||
|
.create_params = dmabuf_create_params,
|
||||||
|
.get_default_feedback = dmabuf_get_default_feedback,
|
||||||
|
.get_surface_feedback = dmabuf_get_surface_feedback,
|
||||||
|
};
|
||||||
|
/* The advertised format/modifier table, built at the first bind from what the renderer's driver
|
||||||
|
* can import (vkp_dmabuf_modifiers). INVALID is always offered too (Mesa drops it; other clients
|
||||||
|
* may use it for the implicit path). Without a renderer the list is LINEAR + INVALID, as before. */
|
||||||
|
/* The last two rows are HDR10's (banner_color.h): A2B10G10R10 as AB30 (alpha) + XB30 (opaque) - Mesa
|
||||||
|
* lists a VkFormat only when both are advertised, and it is the one 10-bit layout our zero-copy WSI
|
||||||
|
* can put in a gralloc buffer (AHARDWAREBUFFER_FORMAT_R10G10B10A2_UNORM). They are advertised ONLY
|
||||||
|
* while the HDR gate is open, and after the 8-bit rows, so every other session - and every client that
|
||||||
|
* takes the first format it sees - gets exactly the table it always had. */
|
||||||
|
#define DMABUF_NFMT_MAX 6
|
||||||
|
#define DMABUF_NFMT_SDR 4
|
||||||
|
#define DMABUF_NMOD 4
|
||||||
|
#define DRM_ABGR2101010 FOURCC('A', 'B', '3', '0')
|
||||||
|
#define DRM_XBGR2101010 FOURCC('X', 'B', '3', '0')
|
||||||
|
static struct { uint32_t fmt; uint64_t mods[DMABUF_NMOD]; int n; } g_dmabuf_fmts[DMABUF_NFMT_MAX] = {
|
||||||
|
{DRM_ARGB8888}, {DRM_XRGB8888}, {DRM_ABGR8888}, {DRM_XBGR8888}, {DRM_ABGR2101010}, {DRM_XBGR2101010}};
|
||||||
|
static int g_dmabuf_nfmt = DMABUF_NFMT_SDR; /* rows advertised: the SDR four, + 2 with the HDR gate open */
|
||||||
|
static int g_dmabuf_fmts_ready;
|
||||||
|
static void dmabuf_build_feedback(void);
|
||||||
|
|
||||||
|
static void dmabuf_build_formats(void) {
|
||||||
|
char line[320];
|
||||||
|
int pos = 0, compressed = 0;
|
||||||
|
g_dmabuf_fmts_ready = 1;
|
||||||
|
g_dmabuf_nfmt = banner_color_hdr_open() ? DMABUF_NFMT_MAX : DMABUF_NFMT_SDR;
|
||||||
|
for (int f = 0; f < g_dmabuf_nfmt; f++) {
|
||||||
|
uint64_t got[DMABUF_NMOD];
|
||||||
|
int n = vkp_dmabuf_modifiers(g_dmabuf_fmts[f].fmt, got, DMABUF_NMOD), k = 0;
|
||||||
|
/* LINEAR first: it is the layout every client and the shm fallback agree on, and the one
|
||||||
|
* we advertised before this table existed. */
|
||||||
|
g_dmabuf_fmts[f].mods[k++] = MOD_LINEAR;
|
||||||
|
for (int i = 0; i < n && k < DMABUF_NMOD - 1; i++) {
|
||||||
|
if (got[i] == MOD_LINEAR) continue;
|
||||||
|
if (got[i] == VKP_MOD_QCOM_COMPRESSED && !g_ubwc) continue;
|
||||||
|
g_dmabuf_fmts[f].mods[k++] = got[i];
|
||||||
|
if (got[i] == VKP_MOD_QCOM_COMPRESSED) compressed++;
|
||||||
|
}
|
||||||
|
g_dmabuf_fmts[f].mods[k++] = MOD_INVALID;
|
||||||
|
g_dmabuf_fmts[f].n = k;
|
||||||
|
uint32_t fmt = g_dmabuf_fmts[f].fmt;
|
||||||
|
pos += snprintf(line + pos, sizeof(line) - (size_t)pos, "%s%c%c%c%c", f ? ", " : "",
|
||||||
|
fmt & 0xff, (fmt >> 8) & 0xff, (fmt >> 16) & 0xff, (fmt >> 24) & 0xff);
|
||||||
|
for (int i = 0; i < k - 1 && pos < (int)sizeof(line); i++)
|
||||||
|
pos += snprintf(line + pos, sizeof(line) - (size_t)pos, "%s%s", i ? "+" : " ",
|
||||||
|
vkp_modifier_name(g_dmabuf_fmts[f].mods[i]));
|
||||||
|
if (pos >= (int)sizeof(line)) pos = (int)sizeof(line) - 1;
|
||||||
|
}
|
||||||
|
banner_log("dmabuf", "formats: %s%s", line,
|
||||||
|
!g_ubwc ? " (BANNER_WAYLAND_UBWC=0: qcom_compressed not advertised)" : "");
|
||||||
|
if (g_ubwc && !compressed)
|
||||||
|
banner_log("dmabuf", "the compositor's driver (%s) reports no importable qcom_compressed layout: "
|
||||||
|
"game swapchains stay linear", vkp_gpu_name());
|
||||||
|
if (g_dmabuf_nfmt > DMABUF_NFMT_SDR) {
|
||||||
|
/* The rows above always carry LINEAR; say what the compositor's own driver can really import
|
||||||
|
* for 10-bit, since a gralloc buffer it cannot import is shown on the display layer only. */
|
||||||
|
uint64_t got[DMABUF_NMOD];
|
||||||
|
int n = vkp_dmabuf_modifiers(DRM_XBGR2101010, got, DMABUF_NMOD), ubwc10 = 0;
|
||||||
|
for (int i = 0; i < n; i++) if (got[i] == VKP_MOD_QCOM_COMPRESSED) ubwc10 = 1;
|
||||||
|
banner_log("color", "10-bit dma-buf formats AB30/XB30 advertised for HDR10; the compositor's driver (%s) "
|
||||||
|
"imports XB30 %s", vkp_gpu_name(),
|
||||||
|
n == 0 ? "with no layout it reports (copy path unlikely; display layer only)"
|
||||||
|
: ubwc10 ? "linear and UBWC" : "linear only (UBWC 10-bit frames: display layer only)");
|
||||||
|
}
|
||||||
|
dmabuf_build_feedback();
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---- dmabuf feedback (zwp_linux_dmabuf_v1 version 4)
|
||||||
|
*
|
||||||
|
* Turnip's Vulkan WSI is happy with the version 3 format/modifier events, so every Vulkan game
|
||||||
|
* worked while we only advertised 3. Mesa's EGL is not: its Wayland platform only takes the GPU
|
||||||
|
* (kopper/Zink) path when it can bind this interface with FEEDBACK, and with 3 it silently drops
|
||||||
|
* to its wl_shm software path. On this Proton layer that path has no software rasteriser to fall
|
||||||
|
* back to (the gallium build is zink+kopper+swrast, no llvmpipe), so the shm buffer it commits is
|
||||||
|
* never written: a native OpenGL window came out solid black, ~30 shm commits/s and no GPU frame
|
||||||
|
* at all (Wizardry: The Labyrinth of Lost Souls). Feedback is what makes that path work.
|
||||||
|
*
|
||||||
|
* What a client needs from us is one tranche describing "everything the compositor can import":
|
||||||
|
* a format table it mmaps read-only, the device to allocate on, and the indices it may use.
|
||||||
|
* Clients binding versions 1-3 keep getting the old format/modifier events instead. */
|
||||||
|
|
||||||
|
#ifndef MFD_CLOEXEC
|
||||||
|
#define MFD_CLOEXEC 0x0001U
|
||||||
|
#endif
|
||||||
|
#ifndef MFD_ALLOW_SEALING
|
||||||
|
#define MFD_ALLOW_SEALING 0x0002U
|
||||||
|
#endif
|
||||||
|
#ifndef F_ADD_SEALS
|
||||||
|
#define F_ADD_SEALS 1033
|
||||||
|
#define F_SEAL_SEAL 0x0001
|
||||||
|
#define F_SEAL_SHRINK 0x0002
|
||||||
|
#define F_SEAL_GROW 0x0004
|
||||||
|
#define F_SEAL_WRITE 0x0008
|
||||||
|
#endif
|
||||||
|
|
||||||
|
struct dmabuf_fmt_entry { uint32_t format; uint32_t pad; uint64_t modifier; }; /* the wire layout */
|
||||||
|
|
||||||
|
static int g_fmt_table_fd = -1; /* sealed read-only memfd of dmabuf_fmt_entry[] */
|
||||||
|
static size_t g_fmt_table_size;
|
||||||
|
static uint16_t g_fmt_table_n; /* entries, == the indices a tranche may name */
|
||||||
|
dev_t g_main_device; /* the render node clients should allocate on */
|
||||||
|
|
||||||
|
/* The GPU we import through is reached with KGSL, not DRM, so there is no render node of our own
|
||||||
|
* to name. Clients only use main_device to match "the same device as the compositor" and to pick
|
||||||
|
* a driver; the one DRM render node this platform has is the right answer, and Zink ignores it
|
||||||
|
* anyway (it renders on the Vulkan device it already has). 0 if the platform has none. */
|
||||||
|
static dev_t dmabuf_render_node(void) {
|
||||||
|
static const char *nodes[] = {"/dev/dri/renderD128", "/dev/dri/renderD129", "/dev/dri/card0"};
|
||||||
|
struct stat st;
|
||||||
|
if (g_no_render_node) return 0;
|
||||||
|
for (size_t i = 0; i < sizeof(nodes) / sizeof(nodes[0]); i++)
|
||||||
|
if (!stat(nodes[i], &st) && S_ISCHR(st.st_mode)) return st.st_rdev;
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
static void dmabuf_build_feedback(void) {
|
||||||
|
struct dmabuf_fmt_entry entries[DMABUF_NFMT_MAX * DMABUF_NMOD];
|
||||||
|
int n = 0;
|
||||||
|
|
||||||
|
g_main_device = dmabuf_render_node();
|
||||||
|
for (int f = 0; f < g_dmabuf_nfmt; f++)
|
||||||
|
for (int m = 0; m < g_dmabuf_fmts[f].n; m++) {
|
||||||
|
if (g_dmabuf_fmts[f].mods[m] == MOD_INVALID) continue; /* never offer INVALID here */
|
||||||
|
entries[n].format = g_dmabuf_fmts[f].fmt;
|
||||||
|
entries[n].pad = 0;
|
||||||
|
entries[n].modifier = g_dmabuf_fmts[f].mods[m];
|
||||||
|
n++;
|
||||||
|
}
|
||||||
|
if (!n) return;
|
||||||
|
|
||||||
|
int fd = (int)syscall(__NR_memfd_create, "banner-dmabuf-formats",
|
||||||
|
MFD_CLOEXEC | MFD_ALLOW_SEALING);
|
||||||
|
if (fd < 0) { WLOGE("dmabuf feedback: memfd_create failed (%s)", strerror(errno)); return; }
|
||||||
|
size_t size = (size_t)n * sizeof(entries[0]);
|
||||||
|
if (write(fd, entries, size) != (ssize_t)size) {
|
||||||
|
WLOGE("dmabuf feedback: could not write the format table (%s)", strerror(errno));
|
||||||
|
close(fd);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
/* The client mmaps this read-only and trusts it not to change under it. */
|
||||||
|
fcntl(fd, F_ADD_SEALS, F_SEAL_SEAL | F_SEAL_SHRINK | F_SEAL_GROW | F_SEAL_WRITE);
|
||||||
|
g_fmt_table_fd = fd;
|
||||||
|
g_fmt_table_size = size;
|
||||||
|
g_fmt_table_n = (uint16_t)n;
|
||||||
|
banner_log("dmabuf", "feedback ready: %d format/modifier pairs, main device %u:%u",
|
||||||
|
n, (unsigned)major(g_main_device), (unsigned)minor(g_main_device));
|
||||||
|
/* Vulkan games never need the node. Mesa's EGL did until Wayland layer versionCode 9: without
|
||||||
|
* one it fell back to a software path that draws nothing here (black window, sound plays). */
|
||||||
|
if (!g_main_device)
|
||||||
|
banner_log("dmabuf", "%s: OpenGL games need Wayland layer versionCode 9 or newer, "
|
||||||
|
"which runs OpenGL on the GPU without a DRM node; older layers show a black window",
|
||||||
|
g_no_render_node ? "no DRM device named (forced by BANNER_WAYLAND_NO_RENDER_NODE=1)"
|
||||||
|
: "this device gives apps no display (DRM) device (/dev/dri)");
|
||||||
|
}
|
||||||
|
|
||||||
|
/* One tranche: our device, every pair in the table, no scanout flag. */
|
||||||
|
static void dmabuf_feedback_send(struct wl_resource *fb) {
|
||||||
|
struct wl_array dev, idx;
|
||||||
|
uint16_t *ind;
|
||||||
|
|
||||||
|
if (g_fmt_table_fd < 0) { zwp_linux_dmabuf_feedback_v1_send_done(fb); return; }
|
||||||
|
|
||||||
|
zwp_linux_dmabuf_feedback_v1_send_format_table(fb, g_fmt_table_fd, (uint32_t)g_fmt_table_size);
|
||||||
|
|
||||||
|
wl_array_init(&dev);
|
||||||
|
memcpy(wl_array_add(&dev, sizeof(dev_t)), &g_main_device, sizeof(dev_t));
|
||||||
|
zwp_linux_dmabuf_feedback_v1_send_main_device(fb, &dev);
|
||||||
|
zwp_linux_dmabuf_feedback_v1_send_tranche_target_device(fb, &dev);
|
||||||
|
wl_array_release(&dev);
|
||||||
|
|
||||||
|
wl_array_init(&idx);
|
||||||
|
ind = wl_array_add(&idx, (size_t)g_fmt_table_n * sizeof(uint16_t));
|
||||||
|
if (ind) for (uint16_t i = 0; i < g_fmt_table_n; i++) ind[i] = i;
|
||||||
|
zwp_linux_dmabuf_feedback_v1_send_tranche_formats(fb, &idx);
|
||||||
|
wl_array_release(&idx);
|
||||||
|
|
||||||
|
zwp_linux_dmabuf_feedback_v1_send_tranche_flags(fb, 0);
|
||||||
|
zwp_linux_dmabuf_feedback_v1_send_tranche_done(fb);
|
||||||
|
zwp_linux_dmabuf_feedback_v1_send_done(fb);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void dmabuf_feedback_destroy(struct wl_client *c, struct wl_resource *r) {
|
||||||
|
wl_resource_destroy(r);
|
||||||
|
}
|
||||||
|
static const struct zwp_linux_dmabuf_feedback_v1_interface dmabuf_feedback_impl = {
|
||||||
|
.destroy = dmabuf_feedback_destroy,
|
||||||
|
};
|
||||||
|
|
||||||
|
static void dmabuf_new_feedback(struct wl_client *c, struct wl_resource *parent, uint32_t id) {
|
||||||
|
struct wl_resource *fb = wl_resource_create(c, &zwp_linux_dmabuf_feedback_v1_interface,
|
||||||
|
wl_resource_get_version(parent), id);
|
||||||
|
if (!fb) { wl_client_post_no_memory(c); return; }
|
||||||
|
wl_resource_set_implementation(fb, &dmabuf_feedback_impl, NULL, NULL);
|
||||||
|
if (!g_dmabuf_fmts_ready) dmabuf_build_formats();
|
||||||
|
dmabuf_feedback_send(fb);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void dmabuf_get_default_feedback(struct wl_client *c, struct wl_resource *r, uint32_t id) {
|
||||||
|
struct client_info *ci = client_info_of(c);
|
||||||
|
if (ci) ci->asked_feedback = 1;
|
||||||
|
dmabuf_new_feedback(c, r, id);
|
||||||
|
}
|
||||||
|
/* Per-surface feedback would let us hint a different tranche for a window on its own display
|
||||||
|
* layer; we have nothing better to say per surface, so it is the default one. */
|
||||||
|
static void dmabuf_get_surface_feedback(struct wl_client *c, struct wl_resource *r, uint32_t id,
|
||||||
|
struct wl_resource *surface) {
|
||||||
|
dmabuf_new_feedback(c, r, id);
|
||||||
|
}
|
||||||
|
|
||||||
|
void bind_dmabuf(struct wl_client *c, void *data, uint32_t ver, uint32_t id) {
|
||||||
|
struct wl_resource *r = wl_resource_create(c, &zwp_linux_dmabuf_v1_interface, ver, id);
|
||||||
|
wl_resource_set_implementation(r, &dmabuf_impl, NULL, NULL);
|
||||||
|
if (!g_dmabuf_fmts_ready) dmabuf_build_formats();
|
||||||
|
/* From version 4 the format and modifier events are gone: the client asks for feedback
|
||||||
|
* instead, and sending both would only confuse it about which list is authoritative. */
|
||||||
|
if (ver >= 4) return;
|
||||||
|
for (int f = 0; f < g_dmabuf_nfmt; f++) {
|
||||||
|
zwp_linux_dmabuf_v1_send_format(r, g_dmabuf_fmts[f].fmt);
|
||||||
|
if (ver >= 3)
|
||||||
|
for (int m = 0; m < g_dmabuf_fmts[f].n; m++)
|
||||||
|
zwp_linux_dmabuf_v1_send_modifier(r, g_dmabuf_fmts[f].fmt,
|
||||||
|
(uint32_t)(g_dmabuf_fmts[f].mods[m] >> 32),
|
||||||
|
(uint32_t)(g_dmabuf_fmts[f].mods[m] & 0xffffffff));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
package com.droiddeck.launcher
|
||||||
|
|
||||||
|
import android.os.Handler
|
||||||
|
import android.util.Log
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.mutableStateOf
|
||||||
|
import androidx.compose.runtime.setValue
|
||||||
|
import com.droiddeck.launcher.session.ComponentsManager
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The Components page's state and work: the Protons and their DXVK/VKD3D sets, the Nightlies
|
||||||
|
* catalog, downloads and the swap/restore actions. The launcher screen keeps one and shows it.
|
||||||
|
*/
|
||||||
|
internal class ComponentsMenu(private val activity: android.app.Activity, private val ui: android.os.Handler) {
|
||||||
|
var compSnapshot by mutableStateOf<ComponentsManager.Snapshot?>(null)
|
||||||
|
var compCatalog by mutableStateOf<List<ComponentsManager.CatalogItem>>(emptyList())
|
||||||
|
var compCatalogAt by mutableStateOf(0L)
|
||||||
|
var compProton by mutableStateOf<String?>(null)
|
||||||
|
var compComp by mutableStateOf("dxvk")
|
||||||
|
var compChecking by mutableStateOf(false)
|
||||||
|
var compBusy by mutableStateOf<String?>(null)
|
||||||
|
var compDownloads by mutableStateOf<Map<String, Int>>(emptyMap())
|
||||||
|
|
||||||
|
/** Reads the Protons (and on first open saves their originals) off the UI thread; the Nightlies list comes from its cache. */
|
||||||
|
fun refreshComponents(snapshotFirst: Boolean = false) {
|
||||||
|
Thread({
|
||||||
|
if (snapshotFirst) runCatching { ComponentsManager.snapshotAll(activity) }
|
||||||
|
runCatching { ComponentsManager.applyQueued(activity) }
|
||||||
|
val snap = runCatching { ComponentsManager.snapshot(activity) }.onFailure { Log.w(TAG, "components", it) }.getOrNull()
|
||||||
|
val cat = runCatching { ComponentsManager.catalog(activity, false) }.getOrNull()
|
||||||
|
ui.post {
|
||||||
|
compSnapshot = snap ?: ComponentsManager.Snapshot(emptyList(), emptyList())
|
||||||
|
if (cat != null && cat.fetchedAt > 0) { compCatalog = cat.items; compCatalogAt = cat.fetchedAt }
|
||||||
|
if (compProton == null || snap?.protons?.none { it.proton.id == compProton } == true) compProton = snap?.protons?.firstOrNull()?.proton?.id
|
||||||
|
}
|
||||||
|
}, "components").start()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun componentAction(label: String, work: () -> String) {
|
||||||
|
if (compBusy != null) return
|
||||||
|
compBusy = label
|
||||||
|
Thread({
|
||||||
|
val message = runCatching(work).getOrElse { e -> "$label failed: ${e.message ?: e.javaClass.simpleName}" }
|
||||||
|
ui.post {
|
||||||
|
compBusy = null
|
||||||
|
android.widget.Toast.makeText(activity, message, android.widget.Toast.LENGTH_LONG).show()
|
||||||
|
refreshComponents()
|
||||||
|
}
|
||||||
|
}, "components-action").start()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun refreshComponentCatalog() {
|
||||||
|
if (compChecking) return
|
||||||
|
compChecking = true
|
||||||
|
Thread({
|
||||||
|
val cat = runCatching { ComponentsManager.catalog(activity, true) }.getOrNull()
|
||||||
|
ui.post {
|
||||||
|
compChecking = false
|
||||||
|
if (cat == null || cat.items.isEmpty()) android.widget.Toast.makeText(activity, "The Nightlies could not be reached", android.widget.Toast.LENGTH_LONG).show()
|
||||||
|
else { compCatalog = cat.items; compCatalogAt = cat.fetchedAt }
|
||||||
|
}
|
||||||
|
}, "components-catalog").start()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun downloadComponent(item: ComponentsManager.CatalogItem) {
|
||||||
|
if (compDownloads.containsKey(item.file)) return
|
||||||
|
compDownloads = compDownloads + (item.file to -1)
|
||||||
|
Thread({
|
||||||
|
val message = runCatching {
|
||||||
|
val pkg = ComponentsManager.download(activity, item) { pc -> ui.post { if (compDownloads.containsKey(item.file)) compDownloads = compDownloads + (item.file to pc) } }
|
||||||
|
"Stored ${pkg.version}"
|
||||||
|
}.getOrElse { e -> "Download failed: ${e.message ?: e.javaClass.simpleName}" }
|
||||||
|
ui.post {
|
||||||
|
compDownloads = compDownloads - item.file
|
||||||
|
android.widget.Toast.makeText(activity, message, android.widget.Toast.LENGTH_SHORT).show()
|
||||||
|
refreshComponents()
|
||||||
|
}
|
||||||
|
}, "components-download").start()
|
||||||
|
}
|
||||||
|
|
||||||
|
private companion object {
|
||||||
|
const val TAG = "MainActivity"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
package com.droiddeck.launcher
|
||||||
|
|
||||||
|
import android.os.Handler
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.mutableIntStateOf
|
||||||
|
import androidx.compose.runtime.mutableStateOf
|
||||||
|
import androidx.compose.runtime.setValue
|
||||||
|
import com.droiddeck.launcher.runtime.DeckyManager
|
||||||
|
import com.droiddeck.launcher.session.SessionState
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Decky Loader's state in the launcher: what is installed, the releases on offer and an install
|
||||||
|
* in progress. The launcher screen keeps one and shows it.
|
||||||
|
*/
|
||||||
|
internal class DeckyMenu(private val activity: android.app.Activity, private val ui: android.os.Handler) {
|
||||||
|
var deckyInstalled by mutableStateOf<String?>(null)
|
||||||
|
var deckyReleases by mutableStateOf<List<DeckyManager.Release>>(emptyList())
|
||||||
|
var deckyChecking by mutableStateOf(false)
|
||||||
|
var deckyStage by mutableStateOf<String?>(null)
|
||||||
|
var deckyPercent by mutableIntStateOf(-1)
|
||||||
|
var deckySupervisor by mutableStateOf(false)
|
||||||
|
var deckyReleaseRequest = 0
|
||||||
|
|
||||||
|
fun refreshDecky() {
|
||||||
|
val request = ++deckyReleaseRequest
|
||||||
|
deckyChecking = true
|
||||||
|
Thread({
|
||||||
|
val channels = runCatching { DeckyManager.releaseChannels(activity) }
|
||||||
|
.getOrElse { DeckyManager.ReleaseChannels(emptyList(), emptyList()) }
|
||||||
|
ui.post {
|
||||||
|
if (request == deckyReleaseRequest) {
|
||||||
|
// Use the newest compatible stable build, or the newest compatible
|
||||||
|
// prerelease when the fork has not published a stable ARM64 asset.
|
||||||
|
deckyReleases = channels.stable.ifEmpty { channels.prerelease }
|
||||||
|
deckyChecking = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, "decky-releases").start()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun installDecky(release: DeckyManager.Release) {
|
||||||
|
if (deckyStage != null || SessionState.running) return
|
||||||
|
deckyStage = "Starting…"; deckyPercent = -1
|
||||||
|
Thread({
|
||||||
|
val problem = runCatching {
|
||||||
|
DeckyManager.install(activity, release) { label, value -> ui.post { deckyStage = label; deckyPercent = value } }
|
||||||
|
}.getOrElse { error -> "Decky install failed: ${error.message ?: error.javaClass.simpleName}" }
|
||||||
|
ui.post {
|
||||||
|
deckyStage = null; deckyPercent = -1; deckyInstalled = DeckyManager.installed(activity)
|
||||||
|
if (problem != null) android.widget.Toast.makeText(activity, problem, android.widget.Toast.LENGTH_LONG).show()
|
||||||
|
}
|
||||||
|
}, "install-decky").start()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,217 @@
|
|||||||
|
package com.droiddeck.launcher
|
||||||
|
|
||||||
|
import android.app.Activity
|
||||||
|
import android.content.Context
|
||||||
|
import java.io.File
|
||||||
|
import android.net.Uri
|
||||||
|
import android.provider.OpenableColumns
|
||||||
|
import android.os.Handler
|
||||||
|
import android.util.Log
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.mutableStateOf
|
||||||
|
import androidx.compose.runtime.setValue
|
||||||
|
import com.droiddeck.launcher.gpu.LinuxVulkanDriver
|
||||||
|
import com.droiddeck.launcher.gpu.LinuxVulkanDriverManager
|
||||||
|
import com.droiddeck.launcher.gpu.TurnipDriver
|
||||||
|
import com.droiddeck.launcher.gpu.TurnipReleases
|
||||||
|
import com.droiddeck.launcher.session.SessionService
|
||||||
|
import com.droiddeck.launcher.session.SessionPrefs
|
||||||
|
import com.droiddeck.launcher.ui.DriverRow
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The Linux and Android driver menus: the drivers each can pick from, the release downloads the
|
||||||
|
* last check found, and what each mode is set to. The launcher screen keeps one and hands its
|
||||||
|
* rows to the mode settings dialog.
|
||||||
|
*/
|
||||||
|
internal class DriverMenus(private val activity: Activity, private val ui: Handler) {
|
||||||
|
var linuxRows by mutableStateOf<List<DriverRow>>(emptyList())
|
||||||
|
/** The latest Banners-Turnip release as each driver menu offers it (see [refreshReleaseRows]). */
|
||||||
|
var linuxDownloads by mutableStateOf<List<com.droiddeck.launcher.ui.DownloadRow>>(emptyList())
|
||||||
|
var androidDownloads by mutableStateOf<List<com.droiddeck.launcher.ui.DownloadRow>>(emptyList())
|
||||||
|
var releaseStatus by mutableStateOf("Not checked yet - tap refresh to look for new drivers")
|
||||||
|
var releaseChecking by mutableStateOf(false)
|
||||||
|
var canRestoreBundled by mutableStateOf(false)
|
||||||
|
/** Asset name -> download percent, while it downloads. */
|
||||||
|
private val releaseProgress = HashMap<String, Int>()
|
||||||
|
var linuxSteam by mutableStateOf("")
|
||||||
|
var linuxDesktop by mutableStateOf("")
|
||||||
|
var androidRows by mutableStateOf<List<DriverRow>>(emptyList())
|
||||||
|
var androidSelected by mutableStateOf("")
|
||||||
|
|
||||||
|
fun refreshDrivers() {
|
||||||
|
val lm = LinuxVulkanDriverManager(activity)
|
||||||
|
fun origin(id: String) = if (TurnipReleases.isDownloaded(activity, id)) DriverRow.DOWNLOADED else DriverRow.IMPORTED
|
||||||
|
linuxRows = LinuxVulkanDriver.optionValues(activity).map { id ->
|
||||||
|
if (id.isEmpty()) DriverRow("", "Runtime default", "the Turnip built into the runtime", false)
|
||||||
|
else DriverRow(
|
||||||
|
id, lm.getDriverName(id),
|
||||||
|
listOfNotNull(
|
||||||
|
lm.getDriverVersion(id).takeIf { it.isNotEmpty() },
|
||||||
|
lm.getMinGlibc(id).takeIf { it.isNotEmpty() }?.let { "glibc $it+" },
|
||||||
|
).joinToString(" · "),
|
||||||
|
true, origin(id),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
linuxSteam = SessionPrefs.linuxDriver(activity, SessionService.MODE_STEAM)
|
||||||
|
linuxDesktop = SessionPrefs.linuxDriver(activity, SessionService.MODE_DESKTOP)
|
||||||
|
val td = TurnipDriver(activity)
|
||||||
|
val auto = td.autoId()
|
||||||
|
androidRows = buildList {
|
||||||
|
add(DriverRow(
|
||||||
|
TurnipDriver.AUTO, "Auto - picked by GPU",
|
||||||
|
if (auto == "system") "system Vulkan: no bundled build for this GPU" else "${td.displayName(auto)} (bundled)",
|
||||||
|
false,
|
||||||
|
))
|
||||||
|
for (id in td.visibleBundled()) add(DriverRow(id, td.displayName(id), td.driverVersion(id), true, DriverRow.BUNDLED))
|
||||||
|
for (id in td.enumerateImported()) add(DriverRow(id, td.displayName(id), td.driverVersion(id), true, origin(id)))
|
||||||
|
}
|
||||||
|
canRestoreBundled = td.hiddenBundled().isNotEmpty()
|
||||||
|
androidSelected = SessionPrefs.androidDriver(activity)
|
||||||
|
refreshReleaseRows()
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Import off the main thread - a driver zip is a few MB and the glibc check reads the whole
|
||||||
|
* library - then say what happened. A refusal's message is the user-facing reason.
|
||||||
|
*/
|
||||||
|
fun importDriver(uri: Uri, linux: Boolean) {
|
||||||
|
val name = activity.displayNameOf(uri)
|
||||||
|
Thread({
|
||||||
|
val problem = try {
|
||||||
|
if (linux) LinuxVulkanDriverManager(activity).installDriver(uri, name)
|
||||||
|
else TurnipDriver(activity).installFromZip(uri, name)
|
||||||
|
null
|
||||||
|
} catch (e: IllegalArgumentException) {
|
||||||
|
e.message
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.w(TAG, "driver import", e)
|
||||||
|
"Import failed: ${e.message}"
|
||||||
|
}
|
||||||
|
ui.post {
|
||||||
|
android.widget.Toast.makeText(
|
||||||
|
activity, problem ?: "Imported ${name ?: "driver"}",
|
||||||
|
if (problem != null) android.widget.Toast.LENGTH_LONG else android.widget.Toast.LENGTH_SHORT,
|
||||||
|
).show()
|
||||||
|
refreshDrivers()
|
||||||
|
}
|
||||||
|
}, "import-driver").start()
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Delete an imported or downloaded driver. A mode still set to it goes back to its default, so a
|
||||||
|
* session never starts on a driver that is gone; a release download is forgotten, so the menu
|
||||||
|
* offers it again.
|
||||||
|
*/
|
||||||
|
fun deleteDriver(id: String, linux: Boolean) {
|
||||||
|
if (linux) {
|
||||||
|
LinuxVulkanDriverManager(activity).removeDriver(id)
|
||||||
|
for (mode in listOf(SessionService.MODE_STEAM, SessionService.MODE_DESKTOP)) {
|
||||||
|
if (SessionPrefs.linuxDriver(activity, mode) == id) SessionPrefs.setLinuxDriver(activity, mode, "")
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
val td = TurnipDriver(activity)
|
||||||
|
if (id in TurnipDriver.BUNDLED) td.hideBundled(id) else td.remove(id)
|
||||||
|
if (SessionPrefs.androidDriver(activity) == id) SessionPrefs.setAndroidDriver(activity, TurnipDriver.AUTO)
|
||||||
|
}
|
||||||
|
TurnipReleases.forget(activity, id)
|
||||||
|
android.widget.Toast.makeText(activity, "Deleted ${id}", android.widget.Toast.LENGTH_SHORT).show()
|
||||||
|
refreshDrivers()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The download entries and the refresh line, from what the last check found. */
|
||||||
|
fun refreshReleaseRows() {
|
||||||
|
val check = TurnipReleases.cached(activity)
|
||||||
|
val lm = LinuxVulkanDriverManager(activity)
|
||||||
|
val td = TurnipDriver(activity)
|
||||||
|
fun rows(linux: Boolean) = check?.assets.orEmpty()
|
||||||
|
.filter { it.linux == linux }
|
||||||
|
.filter { a -> TurnipReleases.installedId(activity, a) { id -> if (linux) lm.isInstalled(id) else td.isInstalled(id) } == null }
|
||||||
|
.map { a ->
|
||||||
|
val mb = "%.1f MB".format(a.size / 1_048_576.0)
|
||||||
|
com.droiddeck.launcher.ui.DownloadRow(a.name, "${a.source} ${a.tag}", "${a.label} · $mb", releaseProgress[a.name])
|
||||||
|
}
|
||||||
|
linuxDownloads = rows(linux = true)
|
||||||
|
androidDownloads = rows(linux = false)
|
||||||
|
if (!releaseChecking) releaseStatus = when (check) {
|
||||||
|
null -> "Not checked yet - tap refresh to look for new drivers"
|
||||||
|
else -> "Latest: " + check.latest.joinToString(" · ") { "${it.first} ${it.second}" } +
|
||||||
|
(if (check.failed.isEmpty()) "" else " · ${check.failed.joinToString()} unreachable") +
|
||||||
|
" · checked ${ago(check.checkedAt)}"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun ago(t: Long): String {
|
||||||
|
val m = ((System.currentTimeMillis() - t) / 60_000).coerceAtLeast(0)
|
||||||
|
return when {
|
||||||
|
m < 1 -> "just now"
|
||||||
|
m < 60 -> "$m min ago"
|
||||||
|
m < 48 * 60 -> "${m / 60} h ago"
|
||||||
|
else -> "${m / (24 * 60)} days ago"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Only when the user taps refresh: nothing goes online on its own. */
|
||||||
|
fun checkLatestTurnip() {
|
||||||
|
if (releaseChecking) return
|
||||||
|
releaseChecking = true
|
||||||
|
releaseStatus = "Checking Banners-Turnip and WinNative…"
|
||||||
|
Thread({
|
||||||
|
val problem = try { TurnipReleases.refresh(activity); null } catch (e: Exception) {
|
||||||
|
Log.w(TAG, "latest Turnip check", e); e.message ?: "check failed"
|
||||||
|
}
|
||||||
|
ui.post {
|
||||||
|
releaseChecking = false
|
||||||
|
refreshReleaseRows()
|
||||||
|
if (problem != null) releaseStatus = "Couldn't check: $problem"
|
||||||
|
}
|
||||||
|
}, "turnip-release-check").start()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Download one release driver and import it through the same importer a picked zip uses. */
|
||||||
|
fun downloadReleaseDriver(assetName: String) {
|
||||||
|
val asset = TurnipReleases.cached(activity)?.assets?.firstOrNull { it.name == assetName } ?: return
|
||||||
|
if (releaseProgress.containsKey(assetName)) return
|
||||||
|
releaseProgress[assetName] = 0
|
||||||
|
refreshReleaseRows()
|
||||||
|
Thread({
|
||||||
|
var file: java.io.File? = null
|
||||||
|
val problem = try {
|
||||||
|
file = TurnipReleases.download(activity, asset) { pct ->
|
||||||
|
ui.post { releaseProgress[assetName] = pct; refreshReleaseRows() }
|
||||||
|
}
|
||||||
|
val uri = Uri.fromFile(file)
|
||||||
|
val id = if (asset.linux) LinuxVulkanDriverManager(activity).installDriver(uri, asset.name)
|
||||||
|
else TurnipDriver(activity).installFromZip(uri, asset.name)
|
||||||
|
TurnipReleases.recordDownload(activity, asset, id)
|
||||||
|
null
|
||||||
|
} catch (e: IllegalArgumentException) {
|
||||||
|
e.message
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.w(TAG, "release driver download", e)
|
||||||
|
"Download failed: ${e.message}"
|
||||||
|
} finally {
|
||||||
|
file?.let { com.droiddeck.launcher.core.FileUtils.delete(it) }
|
||||||
|
}
|
||||||
|
ui.post {
|
||||||
|
releaseProgress.remove(assetName)
|
||||||
|
android.widget.Toast.makeText(
|
||||||
|
activity, problem ?: "Installed ${asset.name.removeSuffix(".zip")} - pick it in the menu",
|
||||||
|
android.widget.Toast.LENGTH_LONG,
|
||||||
|
).show()
|
||||||
|
refreshDrivers()
|
||||||
|
}
|
||||||
|
}, "download-turnip").start()
|
||||||
|
}
|
||||||
|
|
||||||
|
private companion object {
|
||||||
|
const val TAG = "MainActivity"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun Context.displayNameOf(uri: Uri): String? = if (uri.scheme == "file") uri.lastPathSegment else try {
|
||||||
|
contentResolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)
|
||||||
|
?.use { c -> if (c.moveToFirst()) c.getString(0) else null }
|
||||||
|
} catch (e: Exception) {
|
||||||
|
null
|
||||||
|
}
|
||||||
|
|
||||||
@@ -97,13 +97,11 @@ object HomeApp {
|
|||||||
val intent = Intent(Intent.ACTION_MAIN)
|
val intent = Intent(Intent.ACTION_MAIN)
|
||||||
.addCategory(Intent.CATEGORY_LAUNCHER)
|
.addCategory(Intent.CATEGORY_LAUNCHER)
|
||||||
.setComponent(ComponentName(app.packageName, app.className))
|
.setComponent(ComponentName(app.packageName, app.className))
|
||||||
|
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||||
if (displayId == null) {
|
if (displayId == null) {
|
||||||
context.startActivity(intent)
|
context.startActivity(intent)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
// Keep the target app's task separate from DroidDeck. Without this, Android can put the
|
|
||||||
// app on top of the caller's task and move the entire task to the chosen display.
|
|
||||||
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
|
||||||
val options = ActivityOptions.makeBasic().setLaunchDisplayId(displayId)
|
val options = ActivityOptions.makeBasic().setLaunchDisplayId(displayId)
|
||||||
context.startActivity(intent, options.toBundle())
|
context.startActivity(intent, options.toBundle())
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,7 +9,6 @@ import java.io.File
|
|||||||
import android.content.pm.PackageManager
|
import android.content.pm.PackageManager
|
||||||
import android.hardware.display.DisplayManager
|
import android.hardware.display.DisplayManager
|
||||||
import android.net.Uri
|
import android.net.Uri
|
||||||
import android.provider.OpenableColumns
|
|
||||||
import android.os.Bundle
|
import android.os.Bundle
|
||||||
import android.os.Handler
|
import android.os.Handler
|
||||||
import android.os.Looper
|
import android.os.Looper
|
||||||
@@ -25,11 +24,9 @@ import androidx.compose.runtime.getValue
|
|||||||
import androidx.compose.runtime.mutableIntStateOf
|
import androidx.compose.runtime.mutableIntStateOf
|
||||||
import androidx.compose.runtime.mutableStateOf
|
import androidx.compose.runtime.mutableStateOf
|
||||||
import androidx.compose.runtime.setValue
|
import androidx.compose.runtime.setValue
|
||||||
|
import androidx.compose.ui.graphics.toArgb
|
||||||
import com.droiddeck.launcher.gpu.FrameGen
|
import com.droiddeck.launcher.gpu.FrameGen
|
||||||
import com.droiddeck.launcher.gpu.LinuxVulkanDriver
|
|
||||||
import com.droiddeck.launcher.gpu.LinuxVulkanDriverManager
|
|
||||||
import com.droiddeck.launcher.gpu.TurnipDriver
|
import com.droiddeck.launcher.gpu.TurnipDriver
|
||||||
import com.droiddeck.launcher.gpu.TurnipReleases
|
|
||||||
import com.droiddeck.launcher.gpu.LsfgNative
|
import com.droiddeck.launcher.gpu.LsfgNative
|
||||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||||
import com.droiddeck.launcher.runtime.DesktopCatalog
|
import com.droiddeck.launcher.runtime.DesktopCatalog
|
||||||
@@ -44,7 +41,6 @@ import com.droiddeck.launcher.ui.ComponentsPage
|
|||||||
import com.droiddeck.launcher.session.SessionLogShare
|
import com.droiddeck.launcher.session.SessionLogShare
|
||||||
import com.droiddeck.launcher.session.SessionPrefs
|
import com.droiddeck.launcher.session.SessionPrefs
|
||||||
import com.droiddeck.launcher.ui.ProtonPage
|
import com.droiddeck.launcher.ui.ProtonPage
|
||||||
import com.droiddeck.launcher.ui.ProtonRow
|
|
||||||
import com.droiddeck.launcher.core.CpuCores
|
import com.droiddeck.launcher.core.CpuCores
|
||||||
import com.droiddeck.launcher.core.PhantomProcessLimit
|
import com.droiddeck.launcher.core.PhantomProcessLimit
|
||||||
import com.droiddeck.launcher.core.PhantomProcessStatus
|
import com.droiddeck.launcher.core.PhantomProcessStatus
|
||||||
@@ -54,7 +50,6 @@ import com.droiddeck.launcher.ui.PerformancePage
|
|||||||
import com.droiddeck.launcher.ui.ModeSettingsPage
|
import com.droiddeck.launcher.ui.ModeSettingsPage
|
||||||
import com.droiddeck.launcher.ui.ModeSettings
|
import com.droiddeck.launcher.ui.ModeSettings
|
||||||
import com.droiddeck.launcher.ui.ModeSettingsActions
|
import com.droiddeck.launcher.ui.ModeSettingsActions
|
||||||
import com.droiddeck.launcher.ui.DriverRow
|
|
||||||
import com.droiddeck.launcher.ui.ConfirmDialog
|
import com.droiddeck.launcher.ui.ConfirmDialog
|
||||||
import com.droiddeck.launcher.ui.ControllerActions
|
import com.droiddeck.launcher.ui.ControllerActions
|
||||||
import com.droiddeck.launcher.ui.ControllerMappingPage
|
import com.droiddeck.launcher.ui.ControllerMappingPage
|
||||||
@@ -82,9 +77,17 @@ import com.droiddeck.launcher.input.SecondScreenDisplays
|
|||||||
*/
|
*/
|
||||||
class MainActivity : ComponentActivity() {
|
class MainActivity : ComponentActivity() {
|
||||||
private val ui = Handler(Looper.getMainLooper())
|
private val ui = Handler(Looper.getMainLooper())
|
||||||
|
private val drivers = DriverMenus(this, ui)
|
||||||
|
private val components = ComponentsMenu(this, ui)
|
||||||
|
private val decky = DeckyMenu(this, ui)
|
||||||
|
private val protons = ProtonMenu(this, ui)
|
||||||
|
|
||||||
// The screen's state. Compose redraws whatever reads these when they change.
|
// The screen's state. Compose redraws whatever reads these when they change.
|
||||||
private var installed by mutableStateOf<String?>(null)
|
private var installed by mutableStateOf<String?>(null)
|
||||||
|
/** A session launch waiting on its button to fill the page (LaunchFlood). */
|
||||||
|
private var flood by mutableStateOf<PendingFlood?>(null)
|
||||||
|
private var floodProgress by androidx.compose.runtime.mutableFloatStateOf(0f)
|
||||||
|
private class PendingFlood(val from: androidx.compose.ui.geometry.Rect, val intent: Intent)
|
||||||
private var ready by mutableStateOf(false)
|
private var ready by mutableStateOf(false)
|
||||||
private var available by mutableStateOf<LinuxRuntimeInstaller.Release?>(null)
|
private var available by mutableStateOf<LinuxRuntimeInstaller.Release?>(null)
|
||||||
private var busy by mutableStateOf(false)
|
private var busy by mutableStateOf(false)
|
||||||
@@ -102,21 +105,6 @@ class MainActivity : ComponentActivity() {
|
|||||||
// Components page: FEX / DXVK / VKD3D-Proton per Proton (ComponentsManager).
|
// Components page: FEX / DXVK / VKD3D-Proton per Proton (ComponentsManager).
|
||||||
private var showComponents by mutableStateOf(false)
|
private var showComponents by mutableStateOf(false)
|
||||||
private var focusComponentsContent by mutableStateOf(true)
|
private var focusComponentsContent by mutableStateOf(true)
|
||||||
private var compSnapshot by mutableStateOf<ComponentsManager.Snapshot?>(null)
|
|
||||||
private var compCatalog by mutableStateOf<List<ComponentsManager.CatalogItem>>(emptyList())
|
|
||||||
private var compCatalogAt by mutableStateOf(0L)
|
|
||||||
private var compProton by mutableStateOf<String?>(null)
|
|
||||||
private var compComp by mutableStateOf("dxvk")
|
|
||||||
private var compChecking by mutableStateOf(false)
|
|
||||||
private var compBusy by mutableStateOf<String?>(null)
|
|
||||||
private var compDownloads by mutableStateOf<Map<String, Int>>(emptyMap())
|
|
||||||
private var deckyInstalled by mutableStateOf<String?>(null)
|
|
||||||
private var deckyReleases by mutableStateOf<List<DeckyManager.Release>>(emptyList())
|
|
||||||
private var deckyChecking by mutableStateOf(false)
|
|
||||||
private var deckyStage by mutableStateOf<String?>(null)
|
|
||||||
private var deckyPercent by mutableIntStateOf(-1)
|
|
||||||
private var deckySupervisor by mutableStateOf(false)
|
|
||||||
private var deckyReleaseRequest = 0
|
|
||||||
private var showMapping by mutableStateOf(false)
|
private var showMapping by mutableStateOf(false)
|
||||||
private var controllerSettings by mutableStateOf<ControllerPrefs.Settings?>(null)
|
private var controllerSettings by mutableStateOf<ControllerPrefs.Settings?>(null)
|
||||||
private var catalog by mutableStateOf<List<DesktopCatalog.Entry>?>(null)
|
private var catalog by mutableStateOf<List<DesktopCatalog.Entry>?>(null)
|
||||||
@@ -128,10 +116,6 @@ class MainActivity : ComponentActivity() {
|
|||||||
private var desktopInstalled by mutableStateOf(false)
|
private var desktopInstalled by mutableStateOf(false)
|
||||||
private var offlineAccount by mutableStateOf<String?>(null)
|
private var offlineAccount by mutableStateOf<String?>(null)
|
||||||
private var offline by mutableStateOf(false)
|
private var offline by mutableStateOf(false)
|
||||||
private var protonRows by mutableStateOf<List<ProtonRow>>(emptyList())
|
|
||||||
private var protonBusyId by mutableStateOf<String?>(null)
|
|
||||||
private var protonStage by mutableStateOf<String?>(null)
|
|
||||||
private var protonPercent by mutableIntStateOf(-1)
|
|
||||||
private var showPerformance by mutableStateOf(false)
|
private var showPerformance by mutableStateOf(false)
|
||||||
private var clientOverride by mutableStateOf(false)
|
private var clientOverride by mutableStateOf(false)
|
||||||
private var clientCores by mutableStateOf<Set<Int>>(emptySet())
|
private var clientCores by mutableStateOf<Set<Int>>(emptySet())
|
||||||
@@ -148,19 +132,6 @@ class MainActivity : ComponentActivity() {
|
|||||||
private var forceFullscreen by mutableStateOf(true)
|
private var forceFullscreen by mutableStateOf(true)
|
||||||
private var launcherFullscreen by mutableStateOf(true)
|
private var launcherFullscreen by mutableStateOf(true)
|
||||||
private var mic by mutableStateOf(false)
|
private var mic by mutableStateOf(false)
|
||||||
private var linuxRows by mutableStateOf<List<DriverRow>>(emptyList())
|
|
||||||
/** The latest Banners-Turnip release as each driver menu offers it (see [refreshReleaseRows]). */
|
|
||||||
private var linuxDownloads by mutableStateOf<List<com.droiddeck.launcher.ui.DownloadRow>>(emptyList())
|
|
||||||
private var androidDownloads by mutableStateOf<List<com.droiddeck.launcher.ui.DownloadRow>>(emptyList())
|
|
||||||
private var releaseStatus by mutableStateOf("Not checked yet - tap refresh to look for new drivers")
|
|
||||||
private var releaseChecking by mutableStateOf(false)
|
|
||||||
private var canRestoreBundled by mutableStateOf(false)
|
|
||||||
/** Asset name -> download percent, while it downloads. */
|
|
||||||
private val releaseProgress = HashMap<String, Int>()
|
|
||||||
private var linuxSteam by mutableStateOf("")
|
|
||||||
private var linuxDesktop by mutableStateOf("")
|
|
||||||
private var androidRows by mutableStateOf<List<DriverRow>>(emptyList())
|
|
||||||
private var androidSelected by mutableStateOf("")
|
|
||||||
|
|
||||||
// The app's own picker (files/), once per kind of pick: the two driver lists validate
|
// 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.
|
// differently, and the reason a zip is refused names the list it belongs in.
|
||||||
@@ -168,10 +139,10 @@ class MainActivity : ComponentActivity() {
|
|||||||
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedUri(r.data)?.let { importComponent(it) }
|
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedUri(r.data)?.let { importComponent(it) }
|
||||||
}
|
}
|
||||||
private val pickLinuxDriver = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
|
private val pickLinuxDriver = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
|
||||||
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedUri(r.data)?.let { importDriver(it, linux = true) }
|
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedUri(r.data)?.let { drivers.importDriver(it, linux = true) }
|
||||||
}
|
}
|
||||||
private val pickAndroidDriver = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
|
private val pickAndroidDriver = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
|
||||||
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedUri(r.data)?.let { importDriver(it, linux = false) }
|
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedUri(r.data)?.let { drivers.importDriver(it, linux = false) }
|
||||||
}
|
}
|
||||||
private val pickAddedGamesDir = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
|
private val pickAddedGamesDir = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
|
||||||
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedPath(r.data)?.let { path ->
|
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedPath(r.data)?.let { path ->
|
||||||
@@ -249,7 +220,7 @@ class MainActivity : ComponentActivity() {
|
|||||||
override fun startActivity(intent: Intent?) {
|
override fun startActivity(intent: Intent?) {
|
||||||
if (intent?.component?.className == SessionActivity::class.java.name) {
|
if (intent?.component?.className == SessionActivity::class.java.name) {
|
||||||
when {
|
when {
|
||||||
protonBusyId != null || ProtonExtras.installInProgress -> {
|
protons.protonBusyId != null || ProtonExtras.installInProgress -> {
|
||||||
android.widget.Toast.makeText(this, "Wait for the compatibility tool install to finish", android.widget.Toast.LENGTH_SHORT).show()
|
android.widget.Toast.makeText(this, "Wait for the compatibility tool install to finish", android.widget.Toast.LENGTH_SHORT).show()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -259,10 +230,28 @@ class MainActivity : ComponentActivity() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if (intent?.component?.className == SessionActivity::class.java.name) {
|
||||||
|
if (flood != null) return
|
||||||
|
// Started by a blue button: it floods the page first. A running session is re-joined
|
||||||
|
// as before, rising over the front end.
|
||||||
|
val from = com.droiddeck.launcher.ui.LaunchOrigin.take()
|
||||||
|
if (from != null && !SessionState.running && com.droiddeck.launcher.ui.Motion.scale != 0f) {
|
||||||
|
flood = PendingFlood(from, intent)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
com.droiddeck.launcher.ui.LaunchOrigin.flooding = null
|
||||||
|
}
|
||||||
super.startActivity(intent)
|
super.startActivity(intent)
|
||||||
if (intent?.component?.className == SessionActivity::class.java.name) overridePendingTransition(R.anim.session_rise, R.anim.session_hold)
|
if (intent?.component?.className == SessionActivity::class.java.name) overridePendingTransition(R.anim.session_rise, R.anim.session_hold)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** The page is all blue: the session opens on the same blue, with no animation of its own. */
|
||||||
|
private fun launchFlooded(f: PendingFlood) {
|
||||||
|
val signal = com.droiddeck.launcher.ui.Themes.byId(theme).signal
|
||||||
|
super.startActivity(f.intent.putExtra(com.droiddeck.launcher.ui.EXTRA_FLOOD, signal.toArgb()))
|
||||||
|
overridePendingTransition(0, 0)
|
||||||
|
}
|
||||||
|
|
||||||
override fun onCreate(savedInstanceState: Bundle?) {
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
super.onCreate(savedInstanceState)
|
super.onCreate(savedInstanceState)
|
||||||
displayManager = getSystemService(DISPLAY_SERVICE) as DisplayManager
|
displayManager = getSystemService(DISPLAY_SERVICE) as DisplayManager
|
||||||
@@ -282,6 +271,7 @@ class MainActivity : ComponentActivity() {
|
|||||||
showMapping -> { { MappingHost() } }
|
showMapping -> { { MappingHost() } }
|
||||||
else -> null
|
else -> null
|
||||||
}
|
}
|
||||||
|
com.droiddeck.launcher.ui.FloodBehind({ floodProgress }) {
|
||||||
FrontEndScreen(
|
FrontEndScreen(
|
||||||
FrontEndState(
|
FrontEndState(
|
||||||
installed = installed, ready = ready, available = available?.version,
|
installed = installed, ready = ready, available = available?.version,
|
||||||
@@ -354,6 +344,10 @@ class MainActivity : ComponentActivity() {
|
|||||||
onPerformance = { refreshCores(); showProtons = false; showComponents = false; showMapping = false; showPerformance = true },
|
onPerformance = { refreshCores(); showProtons = false; showComponents = false; showMapping = false; showPerformance = true },
|
||||||
onRoms = { showRoms = true },
|
onRoms = { showRoms = true },
|
||||||
onFiles = { startActivity(Intent(this, com.droiddeck.launcher.files.FileManagerActivity::class.java)) },
|
onFiles = { startActivity(Intent(this, com.droiddeck.launcher.files.FileManagerActivity::class.java)) },
|
||||||
|
onBrowseFiles = { dir ->
|
||||||
|
startActivity(Intent(this, com.droiddeck.launcher.files.FileManagerActivity::class.java)
|
||||||
|
.putExtra(com.droiddeck.launcher.files.FileManagerActivity.EXTRA_START_DIR, dir.absolutePath))
|
||||||
|
},
|
||||||
onLogs = {
|
onLogs = {
|
||||||
SessionPrefs.setLogsEnabled(this, !SessionPrefs.logsEnabled(this))
|
SessionPrefs.setLogsEnabled(this, !SessionPrefs.logsEnabled(this))
|
||||||
logsEnabled = SessionPrefs.logsEnabled(this)
|
logsEnabled = SessionPrefs.logsEnabled(this)
|
||||||
@@ -399,7 +393,7 @@ class MainActivity : ComponentActivity() {
|
|||||||
val result = runCatching {
|
val result = runCatching {
|
||||||
kotlinx.coroutines.runBlocking { WirelessAdbFix.pair(this@MainActivity, host, port, code) }
|
kotlinx.coroutines.runBlocking { WirelessAdbFix.pair(this@MainActivity, host, port, code) }
|
||||||
}
|
}
|
||||||
val error = result.exceptionOrNull()?.let { it.localizedMessage ?: "Wireless ADB pairing failed" }
|
val error = result.exceptionOrNull()?.let { it.localizedMessage ?: "Wireless debugging pairing failed" }
|
||||||
ui.post { complete(error) }
|
ui.post { complete(error) }
|
||||||
}, "wireless-adb-pair").start()
|
}, "wireless-adb-pair").start()
|
||||||
},
|
},
|
||||||
@@ -412,7 +406,7 @@ class MainActivity : ComponentActivity() {
|
|||||||
onWirelessAdbApply = { host, port, enabled, complete ->
|
onWirelessAdbApply = { host, port, enabled, complete ->
|
||||||
Thread({
|
Thread({
|
||||||
val result = runCatching { WirelessAdbFix.setChildProcessLimit(this@MainActivity, host, port, enabled) }
|
val result = runCatching { WirelessAdbFix.setChildProcessLimit(this@MainActivity, host, port, enabled) }
|
||||||
val error = result.exceptionOrNull()?.let { it.localizedMessage ?: "Wireless ADB command failed" }
|
val error = result.exceptionOrNull()?.let { it.localizedMessage ?: "Wireless debugging command failed" }
|
||||||
ui.post {
|
ui.post {
|
||||||
if (error == null) refreshPhantomStatus()
|
if (error == null) refreshPhantomStatus()
|
||||||
complete(error)
|
complete(error)
|
||||||
@@ -422,7 +416,7 @@ class MainActivity : ComponentActivity() {
|
|||||||
onSetPhantomProcessLimit = { enabled, complete ->
|
onSetPhantomProcessLimit = { enabled, complete ->
|
||||||
Thread({
|
Thread({
|
||||||
val result = runCatching { WirelessAdbFix.setUsingSavedPairing(this@MainActivity, enabled) }
|
val result = runCatching { WirelessAdbFix.setUsingSavedPairing(this@MainActivity, enabled) }
|
||||||
val error = result.exceptionOrNull()?.let { it.localizedMessage ?: "Wireless ADB is unavailable" }
|
val error = result.exceptionOrNull()?.let { it.localizedMessage ?: "Wireless debugging is unavailable" }
|
||||||
ui.post {
|
ui.post {
|
||||||
if (error == null) refreshPhantomStatus()
|
if (error == null) refreshPhantomStatus()
|
||||||
complete(error)
|
complete(error)
|
||||||
@@ -451,6 +445,7 @@ class MainActivity : ComponentActivity() {
|
|||||||
),
|
),
|
||||||
page = page,
|
page = page,
|
||||||
)
|
)
|
||||||
|
}
|
||||||
if (showRoms) RomsDialog(
|
if (showRoms) RomsDialog(
|
||||||
path = romsDir,
|
path = romsDir,
|
||||||
onChoose = {
|
onChoose = {
|
||||||
@@ -477,6 +472,7 @@ class MainActivity : ComponentActivity() {
|
|||||||
onDismiss = { showRemove = false },
|
onDismiss = { showRemove = false },
|
||||||
)
|
)
|
||||||
if (showCredits) CreditsDialog { showCredits = false }
|
if (showCredits) CreditsDialog { showCredits = false }
|
||||||
|
flood?.let { f -> com.droiddeck.launcher.ui.LaunchFlood(f.from, onProgress = { floodProgress = it }) { launchFlooded(f) } }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -543,7 +539,7 @@ class MainActivity : ComponentActivity() {
|
|||||||
if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) {
|
if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) {
|
||||||
val all = ComponentsManager.COMPONENTS
|
val all = ComponentsManager.COMPONENTS
|
||||||
val step = if (event.keyCode == KeyEvent.KEYCODE_BUTTON_R1) 1 else all.size - 1
|
val step = if (event.keyCode == KeyEvent.KEYCODE_BUTTON_R1) 1 else all.size - 1
|
||||||
compComp = all[(all.indexOf(compComp).coerceAtLeast(0) + step) % all.size]
|
components.compComp = all[(all.indexOf(components.compComp).coerceAtLeast(0) + step) % all.size]
|
||||||
}
|
}
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
@@ -552,6 +548,7 @@ class MainActivity : ComponentActivity() {
|
|||||||
|
|
||||||
override fun onResume() {
|
override fun onResume() {
|
||||||
super.onResume()
|
super.onResume()
|
||||||
|
com.droiddeck.launcher.ui.Motion.refresh(this)
|
||||||
refreshPhantomStatus()
|
refreshPhantomStatus()
|
||||||
// Swaps queued while a game ran on that Proton go in once nothing uses it (usually the
|
// Swaps queued while a game ran on that Proton go in once nothing uses it (usually the
|
||||||
// session has just ended). Cheap when nothing is queued.
|
// session has just ended). Cheap when nothing is queued.
|
||||||
@@ -559,7 +556,7 @@ class MainActivity : ComponentActivity() {
|
|||||||
val applied = runCatching { ComponentsManager.applyQueued(this) }.getOrDefault(emptyList())
|
val applied = runCatching { ComponentsManager.applyQueued(this) }.getOrDefault(emptyList())
|
||||||
if (applied.isNotEmpty()) ui.post {
|
if (applied.isNotEmpty()) ui.post {
|
||||||
android.widget.Toast.makeText(this, "Applied: " + applied.joinToString(", "), android.widget.Toast.LENGTH_LONG).show()
|
android.widget.Toast.makeText(this, "Applied: " + applied.joinToString(", "), android.widget.Toast.LENGTH_LONG).show()
|
||||||
if (showComponents) refreshComponents()
|
if (showComponents) components.refreshComponents()
|
||||||
}
|
}
|
||||||
}, "components-queue").start()
|
}, "components-queue").start()
|
||||||
oscMode = SessionPrefs.oscMode(this)
|
oscMode = SessionPrefs.oscMode(this)
|
||||||
@@ -567,9 +564,9 @@ class MainActivity : ComponentActivity() {
|
|||||||
refreshHomeAppState()
|
refreshHomeAppState()
|
||||||
refreshSecondScreenDisplays()
|
refreshSecondScreenDisplays()
|
||||||
refresh()
|
refresh()
|
||||||
deckyInstalled = DeckyManager.installed(this)
|
decky.deckyInstalled = DeckyManager.installed(this)
|
||||||
DeckyManager.syncCefMarker(this)
|
DeckyManager.syncCefMarker(this)
|
||||||
deckySupervisor = DeckyManager.supervisorEnabled(this)
|
decky.deckySupervisor = DeckyManager.supervisorEnabled(this)
|
||||||
// Added games' art (a store lookup for what the folders lack) starts here, not only when
|
// Added games' art (a store lookup for what the folders lack) starts here, not only when
|
||||||
// the cog opens.
|
// the cog opens.
|
||||||
refreshAddedGames()
|
refreshAddedGames()
|
||||||
@@ -585,6 +582,10 @@ class MainActivity : ComponentActivity() {
|
|||||||
|
|
||||||
override fun onStop() {
|
override fun onStop() {
|
||||||
displayManager.unregisterDisplayListener(secondScreenDisplayListener)
|
displayManager.unregisterDisplayListener(secondScreenDisplayListener)
|
||||||
|
// The session covers the page by now; coming back finds it as it was.
|
||||||
|
flood = null
|
||||||
|
floodProgress = 0f
|
||||||
|
com.droiddeck.launcher.ui.LaunchOrigin.flooding = null
|
||||||
super.onStop()
|
super.onStop()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -638,38 +639,7 @@ class MainActivity : ComponentActivity() {
|
|||||||
showComponents = false
|
showComponents = false
|
||||||
showMapping = false
|
showMapping = false
|
||||||
showProtons = true
|
showProtons = true
|
||||||
refreshProtons()
|
protons.refreshProtons()
|
||||||
}
|
|
||||||
|
|
||||||
private fun refreshDecky() {
|
|
||||||
val request = ++deckyReleaseRequest
|
|
||||||
deckyChecking = true
|
|
||||||
Thread({
|
|
||||||
val channels = runCatching { DeckyManager.releaseChannels(this) }
|
|
||||||
.getOrElse { DeckyManager.ReleaseChannels(emptyList(), emptyList()) }
|
|
||||||
ui.post {
|
|
||||||
if (request == deckyReleaseRequest) {
|
|
||||||
// Use the newest compatible stable build, or the newest compatible
|
|
||||||
// prerelease when the fork has not published a stable ARM64 asset.
|
|
||||||
deckyReleases = channels.stable.ifEmpty { channels.prerelease }
|
|
||||||
deckyChecking = false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}, "decky-releases").start()
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun installDecky(release: DeckyManager.Release) {
|
|
||||||
if (deckyStage != null || SessionState.running) return
|
|
||||||
deckyStage = "Starting…"; deckyPercent = -1
|
|
||||||
Thread({
|
|
||||||
val problem = runCatching {
|
|
||||||
DeckyManager.install(this, release) { label, value -> ui.post { deckyStage = label; deckyPercent = value } }
|
|
||||||
}.getOrElse { error -> "Decky install failed: ${error.message ?: error.javaClass.simpleName}" }
|
|
||||||
ui.post {
|
|
||||||
deckyStage = null; deckyPercent = -1; deckyInstalled = DeckyManager.installed(this)
|
|
||||||
if (problem != null) android.widget.Toast.makeText(this, problem, android.widget.Toast.LENGTH_LONG).show()
|
|
||||||
}
|
|
||||||
}, "install-decky").start()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun refreshController() {
|
private fun refreshController() {
|
||||||
@@ -694,69 +664,12 @@ class MainActivity : ComponentActivity() {
|
|||||||
showProtons = false
|
showProtons = false
|
||||||
showMapping = false
|
showMapping = false
|
||||||
showComponents = true
|
showComponents = true
|
||||||
refreshComponents(snapshotFirst = true)
|
components.refreshComponents(snapshotFirst = true)
|
||||||
}
|
|
||||||
|
|
||||||
/** Reads the Protons (and on first open saves their originals) off the UI thread; the Nightlies list comes from its cache. */
|
|
||||||
private fun refreshComponents(snapshotFirst: Boolean = false) {
|
|
||||||
Thread({
|
|
||||||
if (snapshotFirst) runCatching { ComponentsManager.snapshotAll(this) }
|
|
||||||
runCatching { ComponentsManager.applyQueued(this) }
|
|
||||||
val snap = runCatching { ComponentsManager.snapshot(this) }.onFailure { Log.w(TAG, "components", it) }.getOrNull()
|
|
||||||
val cat = runCatching { ComponentsManager.catalog(this, false) }.getOrNull()
|
|
||||||
ui.post {
|
|
||||||
compSnapshot = snap ?: ComponentsManager.Snapshot(emptyList(), emptyList())
|
|
||||||
if (cat != null && cat.fetchedAt > 0) { compCatalog = cat.items; compCatalogAt = cat.fetchedAt }
|
|
||||||
if (compProton == null || snap?.protons?.none { it.proton.id == compProton } == true) compProton = snap?.protons?.firstOrNull()?.proton?.id
|
|
||||||
}
|
|
||||||
}, "components").start()
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun componentAction(label: String, work: () -> String) {
|
|
||||||
if (compBusy != null) return
|
|
||||||
compBusy = label
|
|
||||||
Thread({
|
|
||||||
val message = runCatching(work).getOrElse { e -> "$label failed: ${e.message ?: e.javaClass.simpleName}" }
|
|
||||||
ui.post {
|
|
||||||
compBusy = null
|
|
||||||
android.widget.Toast.makeText(this, message, android.widget.Toast.LENGTH_LONG).show()
|
|
||||||
refreshComponents()
|
|
||||||
}
|
|
||||||
}, "components-action").start()
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun refreshComponentCatalog() {
|
|
||||||
if (compChecking) return
|
|
||||||
compChecking = true
|
|
||||||
Thread({
|
|
||||||
val cat = runCatching { ComponentsManager.catalog(this, true) }.getOrNull()
|
|
||||||
ui.post {
|
|
||||||
compChecking = false
|
|
||||||
if (cat == null || cat.items.isEmpty()) android.widget.Toast.makeText(this, "The Nightlies could not be reached", android.widget.Toast.LENGTH_LONG).show()
|
|
||||||
else { compCatalog = cat.items; compCatalogAt = cat.fetchedAt }
|
|
||||||
}
|
|
||||||
}, "components-catalog").start()
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun downloadComponent(item: ComponentsManager.CatalogItem) {
|
|
||||||
if (compDownloads.containsKey(item.file)) return
|
|
||||||
compDownloads = compDownloads + (item.file to -1)
|
|
||||||
Thread({
|
|
||||||
val message = runCatching {
|
|
||||||
val pkg = ComponentsManager.download(this, item) { pc -> ui.post { if (compDownloads.containsKey(item.file)) compDownloads = compDownloads + (item.file to pc) } }
|
|
||||||
"Stored ${pkg.version}"
|
|
||||||
}.getOrElse { e -> "Download failed: ${e.message ?: e.javaClass.simpleName}" }
|
|
||||||
ui.post {
|
|
||||||
compDownloads = compDownloads - item.file
|
|
||||||
android.widget.Toast.makeText(this, message, android.widget.Toast.LENGTH_SHORT).show()
|
|
||||||
refreshComponents()
|
|
||||||
}
|
|
||||||
}, "components-download").start()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun importComponent(uri: Uri) {
|
private fun importComponent(uri: Uri) {
|
||||||
val name = displayNameOf(uri) ?: "imported.wcp"
|
val name = displayNameOf(uri) ?: "imported.wcp"
|
||||||
componentAction("Importing") {
|
components.componentAction("Importing") {
|
||||||
val tmp = File(cacheDir, "component-import.wcp")
|
val tmp = File(cacheDir, "component-import.wcp")
|
||||||
contentResolver.openInputStream(uri)?.use { input -> tmp.outputStream().use { input.copyTo(it) } } ?: error("cannot read the file")
|
contentResolver.openInputStream(uri)?.use { input -> tmp.outputStream().use { input.copyTo(it) } } ?: error("cannot read the file")
|
||||||
try { "Imported ${ComponentsManager.importPackage(this, tmp, name).version}" } finally { tmp.delete() }
|
try { "Imported ${ComponentsManager.importPackage(this, tmp, name).version}" } finally { tmp.delete() }
|
||||||
@@ -766,24 +679,24 @@ class MainActivity : ComponentActivity() {
|
|||||||
@Composable
|
@Composable
|
||||||
private fun ComponentsHost() {
|
private fun ComponentsHost() {
|
||||||
ComponentsPage(
|
ComponentsPage(
|
||||||
snapshot = compSnapshot,
|
snapshot = components.compSnapshot,
|
||||||
catalog = compCatalog,
|
catalog = components.compCatalog,
|
||||||
catalogAt = compCatalogAt,
|
catalogAt = components.compCatalogAt,
|
||||||
protonId = compProton,
|
protonId = components.compProton,
|
||||||
comp = compComp,
|
comp = components.compComp,
|
||||||
checking = compChecking,
|
checking = components.compChecking,
|
||||||
busy = compBusy,
|
busy = components.compBusy,
|
||||||
downloads = compDownloads,
|
downloads = components.compDownloads,
|
||||||
requestInitialFocus = focusComponentsContent,
|
requestInitialFocus = focusComponentsContent,
|
||||||
onProton = { compProton = it },
|
onProton = { components.compProton = it },
|
||||||
onComp = { compComp = it },
|
onComp = { components.compComp = it },
|
||||||
onSwap = { file -> compProton?.let { pid -> componentAction("Swapping") { ComponentsManager.swap(this, pid, file) } } },
|
onSwap = { file -> components.compProton?.let { pid -> components.componentAction("Swapping") { ComponentsManager.swap(this, pid, file) } } },
|
||||||
onRestore = { version -> compProton?.let { pid -> componentAction("Restoring") { ComponentsManager.restore(this, pid, compComp, version) } } },
|
onRestore = { version -> components.compProton?.let { pid -> components.componentAction("Restoring") { ComponentsManager.restore(this, pid, components.compComp, version) } } },
|
||||||
onCancelQueued = { compProton?.let { pid -> componentAction("Cancelling") { ComponentsManager.cancelQueued(this, pid, compComp); "The waiting swap was cancelled." } } },
|
onCancelQueued = { components.compProton?.let { pid -> components.componentAction("Cancelling") { ComponentsManager.cancelQueued(this, pid, components.compComp); "The waiting swap was cancelled." } } },
|
||||||
onDeletePackage = { file -> componentAction("Deleting") { ComponentsManager.deletePackage(this, file) } },
|
onDeletePackage = { file -> components.componentAction("Deleting") { ComponentsManager.deletePackage(this, file) } },
|
||||||
onDeleteOriginal = { version -> compProton?.let { pid -> componentAction("Deleting") { ComponentsManager.deleteOriginal(this, pid, compComp, version) } } },
|
onDeleteOriginal = { version -> components.compProton?.let { pid -> components.componentAction("Deleting") { ComponentsManager.deleteOriginal(this, pid, components.compComp, version) } } },
|
||||||
onDownload = { downloadComponent(it) },
|
onDownload = { components.downloadComponent(it) },
|
||||||
onRefresh = { refreshComponentCatalog() },
|
onRefresh = { components.refreshComponentCatalog() },
|
||||||
onImport = { pickComponent.launch(InAppFilePicker.buildIntent(this, WCP_EXT, "Choose a component package (-linux .wcp)")) },
|
onImport = { pickComponent.launch(InAppFilePicker.buildIntent(this, WCP_EXT, "Choose a component package (-linux .wcp)")) },
|
||||||
onBack = { showComponents = false },
|
onBack = { showComponents = false },
|
||||||
)
|
)
|
||||||
@@ -792,56 +705,19 @@ class MainActivity : ComponentActivity() {
|
|||||||
@Composable
|
@Composable
|
||||||
private fun ProtonHost() {
|
private fun ProtonHost() {
|
||||||
ProtonPage(
|
ProtonPage(
|
||||||
rows = protonRows,
|
rows = protons.protonRows,
|
||||||
busyId = protonBusyId,
|
busyId = protons.protonBusyId,
|
||||||
stage = protonStage,
|
stage = protons.protonStage,
|
||||||
percent = protonPercent,
|
percent = protons.protonPercent,
|
||||||
runtimeReady = ready,
|
runtimeReady = ready,
|
||||||
sessionRunning = SessionState.running,
|
sessionRunning = SessionState.running,
|
||||||
onInstall = { id -> installProton(id) },
|
onInstall = { id -> protons.installProton(id) },
|
||||||
onCancel = { id -> ProtonExtras.tools.firstOrNull { it.id == id }?.let { ProtonExtras.unqueue(this, it) }; refreshProtons() },
|
onCancel = { id -> ProtonExtras.tools.firstOrNull { it.id == id }?.let { ProtonExtras.unqueue(this, it) }; protons.refreshProtons() },
|
||||||
onRemove = { id -> removeProton(id) },
|
onRemove = { id -> protons.removeProton(id) },
|
||||||
onBack = { showProtons = false },
|
onBack = { showProtons = false },
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun installProton(id: String) {
|
|
||||||
val tool = ProtonExtras.tools.firstOrNull { it.id == id } ?: return
|
|
||||||
if (protonBusyId != null || SessionState.running) return
|
|
||||||
ProtonExtras.unqueue(this, tool)
|
|
||||||
protonBusyId = id
|
|
||||||
protonStage = "Starting…"
|
|
||||||
protonPercent = -1
|
|
||||||
Thread({
|
|
||||||
val problem = ProtonExtras.install(this, tool) { label, value ->
|
|
||||||
ui.post { protonStage = label; protonPercent = value }
|
|
||||||
}
|
|
||||||
ui.post {
|
|
||||||
protonBusyId = null
|
|
||||||
protonStage = null
|
|
||||||
protonPercent = -1
|
|
||||||
refreshProtons()
|
|
||||||
if (problem != null) android.widget.Toast.makeText(this, problem, android.widget.Toast.LENGTH_LONG).show()
|
|
||||||
}
|
|
||||||
}, "install-proton-$id").start()
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun removeProton(id: String) {
|
|
||||||
val tool = ProtonExtras.tools.firstOrNull { it.id == id } ?: return
|
|
||||||
if (protonBusyId != null || SessionState.running) return
|
|
||||||
protonBusyId = id
|
|
||||||
protonStage = "Removing ${tool.name}…"
|
|
||||||
protonPercent = -1
|
|
||||||
Thread({
|
|
||||||
ProtonExtras.remove(this, tool)
|
|
||||||
ui.post {
|
|
||||||
protonBusyId = null
|
|
||||||
protonStage = null
|
|
||||||
refreshProtons()
|
|
||||||
}
|
|
||||||
}, "remove-proton-$id").start()
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun refreshPackages() {
|
private fun refreshPackages() {
|
||||||
packageRows = catalog?.map { PackageRow(it.id, it.kind, it.notes) }
|
packageRows = catalog?.map { PackageRow(it.id, it.kind, it.notes) }
|
||||||
desktopInstalled = DesktopCatalog.desktopInstalled(this)
|
desktopInstalled = DesktopCatalog.desktopInstalled(this)
|
||||||
@@ -890,9 +766,9 @@ class MainActivity : ComponentActivity() {
|
|||||||
ModeSettings(
|
ModeSettings(
|
||||||
mode = mode, resolutionCap = resolutionCap, customResolution = customResolution, shapeMode = shapeMode,
|
mode = mode, resolutionCap = resolutionCap, customResolution = customResolution, shapeMode = shapeMode,
|
||||||
hdr = hdrOn, hdrReason = hdrReason,
|
hdr = hdrOn, hdrReason = hdrReason,
|
||||||
linuxRows = linuxRows,
|
linuxRows = drivers.linuxRows,
|
||||||
linuxSelected = if (mode == SessionService.MODE_STEAM) linuxSteam else linuxDesktop,
|
linuxSelected = if (mode == SessionService.MODE_STEAM) drivers.linuxSteam else drivers.linuxDesktop,
|
||||||
androidRows = androidRows, androidSelected = androidSelected,
|
androidRows = drivers.androidRows, androidSelected = drivers.androidSelected,
|
||||||
touchMode = touchMode,
|
touchMode = touchMode,
|
||||||
suspendPolicy = suspendPolicy,
|
suspendPolicy = suspendPolicy,
|
||||||
oscMode = if (mode == SessionService.MODE_STEAM) oscMode else null,
|
oscMode = if (mode == SessionService.MODE_STEAM) oscMode else null,
|
||||||
@@ -910,27 +786,27 @@ class MainActivity : ComponentActivity() {
|
|||||||
addedGamesDirs = if (mode == SessionService.MODE_STEAM) addedGamesDirs else null,
|
addedGamesDirs = if (mode == SessionService.MODE_STEAM) addedGamesDirs else null,
|
||||||
addedGames = if (mode == SessionService.MODE_STEAM) addedGames else emptyList(),
|
addedGames = if (mode == SessionService.MODE_STEAM) addedGames else emptyList(),
|
||||||
addedGamesArt = addedGamesArt,
|
addedGamesArt = addedGamesArt,
|
||||||
linuxDownloads = linuxDownloads, androidDownloads = androidDownloads, releaseStatus = releaseStatus,
|
linuxDownloads = drivers.linuxDownloads, androidDownloads = drivers.androidDownloads, releaseStatus = drivers.releaseStatus,
|
||||||
releaseChecking = releaseChecking, canRestoreBundled = canRestoreBundled,
|
releaseChecking = drivers.releaseChecking, canRestoreBundled = drivers.canRestoreBundled,
|
||||||
deckyInstalled = if (mode == SessionService.MODE_STEAM) deckyInstalled else null,
|
deckyInstalled = if (mode == SessionService.MODE_STEAM) decky.deckyInstalled else null,
|
||||||
deckyLatestRelease = if (mode == SessionService.MODE_STEAM) deckyReleases.firstOrNull() else null,
|
deckyLatestRelease = if (mode == SessionService.MODE_STEAM) decky.deckyReleases.firstOrNull() else null,
|
||||||
deckyChecking = deckyChecking, deckyStage = deckyStage, deckyPercent = deckyPercent,
|
deckyChecking = decky.deckyChecking, deckyStage = decky.deckyStage, deckyPercent = decky.deckyPercent,
|
||||||
deckyEnabled = deckySupervisor, deckySessionRunning = SessionState.running,
|
deckyEnabled = decky.deckySupervisor, deckySessionRunning = SessionState.running,
|
||||||
),
|
),
|
||||||
ModeSettingsActions(
|
ModeSettingsActions(
|
||||||
onResolution = { cap -> SessionPrefs.setResolutionCap(this, mode, cap); resolutionCap = cap },
|
onResolution = { cap -> SessionPrefs.setResolutionCap(this, mode, cap); resolutionCap = cap },
|
||||||
onCustomResolution = { size -> SessionPrefs.setCustomResolution(this, mode, size); customResolution = size },
|
onCustomResolution = { size -> SessionPrefs.setCustomResolution(this, mode, size); customResolution = size },
|
||||||
onShape = { shape -> SessionPrefs.setShapeMode(this, shape); shapeMode = shape },
|
onShape = { shape -> SessionPrefs.setShapeMode(this, shape); shapeMode = shape },
|
||||||
onHdr = { on -> SessionPrefs.setHdr(this, mode, on); hdrOn = on },
|
onHdr = { on -> SessionPrefs.setHdr(this, mode, on); hdrOn = on },
|
||||||
onSelectLinux = { id -> SessionPrefs.setLinuxDriver(this, mode, id); refreshDrivers() },
|
onSelectLinux = { id -> SessionPrefs.setLinuxDriver(this, mode, id); drivers.refreshDrivers() },
|
||||||
onImportLinux = { pickLinuxDriver.launch(InAppFilePicker.buildIntent(this, ZIP_EXT, "Choose a Linux runtime driver (-Linux zip)")) },
|
onImportLinux = { pickLinuxDriver.launch(InAppFilePicker.buildIntent(this, ZIP_EXT, "Choose a Linux runtime driver (-Linux zip)")) },
|
||||||
onRemoveLinux = { id -> deleteDriver(id, linux = true) },
|
onRemoveLinux = { id -> drivers.deleteDriver(id, linux = true) },
|
||||||
onRefreshReleases = { checkLatestTurnip() },
|
onRefreshReleases = { drivers.checkLatestTurnip() },
|
||||||
onDownloadDriver = { name -> downloadReleaseDriver(name) },
|
onDownloadDriver = { name -> drivers.downloadReleaseDriver(name) },
|
||||||
onRestoreBundled = { TurnipDriver(this).restoreBundled(); refreshDrivers() },
|
onRestoreBundled = { TurnipDriver(this).restoreBundled(); drivers.refreshDrivers() },
|
||||||
onSelectAndroid = { id -> SessionPrefs.setAndroidDriver(this, id); refreshDrivers() },
|
onSelectAndroid = { id -> SessionPrefs.setAndroidDriver(this, id); drivers.refreshDrivers() },
|
||||||
onImportAndroid = { pickAndroidDriver.launch(InAppFilePicker.buildIntent(this, ZIP_EXT, "Choose a display driver (AdrenoTools zip)")) },
|
onImportAndroid = { pickAndroidDriver.launch(InAppFilePicker.buildIntent(this, ZIP_EXT, "Choose a display driver (AdrenoTools zip)")) },
|
||||||
onRemoveAndroid = { id -> deleteDriver(id, linux = false) },
|
onRemoveAndroid = { id -> drivers.deleteDriver(id, linux = false) },
|
||||||
onTouch = { t -> SessionPrefs.setTouchMode(this, t); touchMode = t },
|
onTouch = { t -> SessionPrefs.setTouchMode(this, t); touchMode = t },
|
||||||
onSuspendPolicy = { policy -> SessionPrefs.setSuspendPolicy(this, mode, policy); suspendPolicy = policy },
|
onSuspendPolicy = { policy -> SessionPrefs.setSuspendPolicy(this, mode, policy); suspendPolicy = policy },
|
||||||
onOsc = { o -> SessionPrefs.setOscMode(this, o); oscMode = o },
|
onOsc = { o -> SessionPrefs.setOscMode(this, o); oscMode = o },
|
||||||
@@ -969,13 +845,13 @@ class MainActivity : ComponentActivity() {
|
|||||||
pendingAddedGame = folder
|
pendingAddedGame = folder
|
||||||
pickAddedGameExe.launch(InAppFilePicker.buildIntent(this, listOf("exe"), "Choose the game's .exe", folder))
|
pickAddedGameExe.launch(InAppFilePicker.buildIntent(this, listOf("exe"), "Choose the game's .exe", folder))
|
||||||
},
|
},
|
||||||
onDeckyInstall = { release -> installDecky(release) },
|
onDeckyInstall = { release -> decky.installDecky(release) },
|
||||||
onDeckyCheck = { refreshDecky() },
|
onDeckyCheck = { decky.refreshDecky() },
|
||||||
onDeckyEnabled = { enabled -> DeckyManager.setSupervisorEnabled(this, enabled); deckySupervisor = enabled },
|
onDeckyEnabled = { enabled -> DeckyManager.setSupervisorEnabled(this, enabled); decky.deckySupervisor = enabled },
|
||||||
onDeckyUninstall = {
|
onDeckyUninstall = {
|
||||||
DeckyManager.uninstall(this, wipeData = false)
|
DeckyManager.uninstall(this, wipeData = false)
|
||||||
deckyInstalled = null
|
decky.deckyInstalled = null
|
||||||
deckySupervisor = false
|
decky.deckySupervisor = false
|
||||||
},
|
},
|
||||||
onDismiss = { settingsMode = null },
|
onDismiss = { settingsMode = null },
|
||||||
),
|
),
|
||||||
@@ -1034,7 +910,7 @@ class MainActivity : ComponentActivity() {
|
|||||||
showProtons = false
|
showProtons = false
|
||||||
showComponents = false
|
showComponents = false
|
||||||
showMapping = false
|
showMapping = false
|
||||||
refreshDrivers()
|
drivers.refreshDrivers()
|
||||||
resolutionCap = SessionPrefs.resolutionCap(this, mode)
|
resolutionCap = SessionPrefs.resolutionCap(this, mode)
|
||||||
customResolution = SessionPrefs.customResolution(this, mode)
|
customResolution = SessionPrefs.customResolution(this, mode)
|
||||||
fexPreset = SessionPrefs.fexPreset(this)
|
fexPreset = SessionPrefs.fexPreset(this)
|
||||||
@@ -1057,9 +933,9 @@ class MainActivity : ComponentActivity() {
|
|||||||
gameStorage = SessionPrefs.gameStorage(this)
|
gameStorage = SessionPrefs.gameStorage(this)
|
||||||
storageOptions = GameStorage.options(this).map { it.label to it.path }
|
storageOptions = GameStorage.options(this).map { it.label to it.path }
|
||||||
if (mode == SessionService.MODE_STEAM) {
|
if (mode == SessionService.MODE_STEAM) {
|
||||||
deckyInstalled = DeckyManager.installed(this)
|
decky.deckyInstalled = DeckyManager.installed(this)
|
||||||
deckySupervisor = DeckyManager.supervisorEnabled(this)
|
decky.deckySupervisor = DeckyManager.supervisorEnabled(this)
|
||||||
refreshDecky()
|
decky.refreshDecky()
|
||||||
}
|
}
|
||||||
settingsMode = mode
|
settingsMode = mode
|
||||||
}
|
}
|
||||||
@@ -1077,178 +953,6 @@ class MainActivity : ComponentActivity() {
|
|||||||
gameStorage = path
|
gameStorage = path
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun refreshDrivers() {
|
|
||||||
val lm = LinuxVulkanDriverManager(this)
|
|
||||||
fun origin(id: String) = if (TurnipReleases.isDownloaded(this, id)) DriverRow.DOWNLOADED else DriverRow.IMPORTED
|
|
||||||
linuxRows = LinuxVulkanDriver.optionValues(this).map { id ->
|
|
||||||
if (id.isEmpty()) DriverRow("", "Runtime default", "the Turnip built into the runtime", false)
|
|
||||||
else DriverRow(
|
|
||||||
id, lm.getDriverName(id),
|
|
||||||
listOfNotNull(
|
|
||||||
lm.getDriverVersion(id).takeIf { it.isNotEmpty() },
|
|
||||||
lm.getMinGlibc(id).takeIf { it.isNotEmpty() }?.let { "glibc $it+" },
|
|
||||||
).joinToString(" · "),
|
|
||||||
true, origin(id),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
linuxSteam = SessionPrefs.linuxDriver(this, SessionService.MODE_STEAM)
|
|
||||||
linuxDesktop = SessionPrefs.linuxDriver(this, SessionService.MODE_DESKTOP)
|
|
||||||
val td = TurnipDriver(this)
|
|
||||||
val auto = td.autoId()
|
|
||||||
androidRows = buildList {
|
|
||||||
add(DriverRow(
|
|
||||||
TurnipDriver.AUTO, "Auto - picked by GPU",
|
|
||||||
if (auto == "system") "system Vulkan: no bundled build for this GPU" else "${td.displayName(auto)} (bundled)",
|
|
||||||
false,
|
|
||||||
))
|
|
||||||
for (id in td.visibleBundled()) add(DriverRow(id, td.displayName(id), td.driverVersion(id), true, DriverRow.BUNDLED))
|
|
||||||
for (id in td.enumerateImported()) add(DriverRow(id, td.displayName(id), td.driverVersion(id), true, origin(id)))
|
|
||||||
}
|
|
||||||
canRestoreBundled = td.hiddenBundled().isNotEmpty()
|
|
||||||
androidSelected = SessionPrefs.androidDriver(this)
|
|
||||||
refreshReleaseRows()
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Import off the main thread - a driver zip is a few MB and the glibc check reads the whole
|
|
||||||
* library - then say what happened. A refusal's message is the user-facing reason.
|
|
||||||
*/
|
|
||||||
private fun importDriver(uri: Uri, linux: Boolean) {
|
|
||||||
val name = displayNameOf(uri)
|
|
||||||
Thread({
|
|
||||||
val problem = try {
|
|
||||||
if (linux) LinuxVulkanDriverManager(this).installDriver(uri, name)
|
|
||||||
else TurnipDriver(this).installFromZip(uri, name)
|
|
||||||
null
|
|
||||||
} catch (e: IllegalArgumentException) {
|
|
||||||
e.message
|
|
||||||
} catch (e: Exception) {
|
|
||||||
Log.w(TAG, "driver import", e)
|
|
||||||
"Import failed: ${e.message}"
|
|
||||||
}
|
|
||||||
ui.post {
|
|
||||||
android.widget.Toast.makeText(
|
|
||||||
this, problem ?: "Imported ${name ?: "driver"}",
|
|
||||||
if (problem != null) android.widget.Toast.LENGTH_LONG else android.widget.Toast.LENGTH_SHORT,
|
|
||||||
).show()
|
|
||||||
refreshDrivers()
|
|
||||||
}
|
|
||||||
}, "import-driver").start()
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Delete an imported or downloaded driver. A mode still set to it goes back to its default, so a
|
|
||||||
* session never starts on a driver that is gone; a release download is forgotten, so the menu
|
|
||||||
* offers it again.
|
|
||||||
*/
|
|
||||||
private fun deleteDriver(id: String, linux: Boolean) {
|
|
||||||
if (linux) {
|
|
||||||
LinuxVulkanDriverManager(this).removeDriver(id)
|
|
||||||
for (mode in listOf(SessionService.MODE_STEAM, SessionService.MODE_DESKTOP)) {
|
|
||||||
if (SessionPrefs.linuxDriver(this, mode) == id) SessionPrefs.setLinuxDriver(this, mode, "")
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
val td = TurnipDriver(this)
|
|
||||||
if (id in TurnipDriver.BUNDLED) td.hideBundled(id) else td.remove(id)
|
|
||||||
if (SessionPrefs.androidDriver(this) == id) SessionPrefs.setAndroidDriver(this, TurnipDriver.AUTO)
|
|
||||||
}
|
|
||||||
TurnipReleases.forget(this, id)
|
|
||||||
android.widget.Toast.makeText(this, "Deleted ${id}", android.widget.Toast.LENGTH_SHORT).show()
|
|
||||||
refreshDrivers()
|
|
||||||
}
|
|
||||||
|
|
||||||
/** The download entries and the refresh line, from what the last check found. */
|
|
||||||
private fun refreshReleaseRows() {
|
|
||||||
val check = TurnipReleases.cached(this)
|
|
||||||
val lm = LinuxVulkanDriverManager(this)
|
|
||||||
val td = TurnipDriver(this)
|
|
||||||
fun rows(linux: Boolean) = check?.assets.orEmpty()
|
|
||||||
.filter { it.linux == linux }
|
|
||||||
.filter { a -> TurnipReleases.installedId(this, a) { id -> if (linux) lm.isInstalled(id) else td.isInstalled(id) } == null }
|
|
||||||
.map { a ->
|
|
||||||
val mb = "%.1f MB".format(a.size / 1_048_576.0)
|
|
||||||
com.droiddeck.launcher.ui.DownloadRow(a.name, "${a.source} ${a.tag}", "${a.label} · $mb", releaseProgress[a.name])
|
|
||||||
}
|
|
||||||
linuxDownloads = rows(linux = true)
|
|
||||||
androidDownloads = rows(linux = false)
|
|
||||||
if (!releaseChecking) releaseStatus = when (check) {
|
|
||||||
null -> "Not checked yet - tap refresh to look for new drivers"
|
|
||||||
else -> "Latest: " + check.latest.joinToString(" · ") { "${it.first} ${it.second}" } +
|
|
||||||
(if (check.failed.isEmpty()) "" else " · ${check.failed.joinToString()} unreachable") +
|
|
||||||
" · checked ${ago(check.checkedAt)}"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun ago(t: Long): String {
|
|
||||||
val m = ((System.currentTimeMillis() - t) / 60_000).coerceAtLeast(0)
|
|
||||||
return when {
|
|
||||||
m < 1 -> "just now"
|
|
||||||
m < 60 -> "$m min ago"
|
|
||||||
m < 48 * 60 -> "${m / 60} h ago"
|
|
||||||
else -> "${m / (24 * 60)} days ago"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Only when the user taps refresh: nothing goes online on its own. */
|
|
||||||
private fun checkLatestTurnip() {
|
|
||||||
if (releaseChecking) return
|
|
||||||
releaseChecking = true
|
|
||||||
releaseStatus = "Checking Banners-Turnip and WinNative…"
|
|
||||||
Thread({
|
|
||||||
val problem = try { TurnipReleases.refresh(this); null } catch (e: Exception) {
|
|
||||||
Log.w(TAG, "latest Turnip check", e); e.message ?: "check failed"
|
|
||||||
}
|
|
||||||
ui.post {
|
|
||||||
releaseChecking = false
|
|
||||||
refreshReleaseRows()
|
|
||||||
if (problem != null) releaseStatus = "Couldn't check: $problem"
|
|
||||||
}
|
|
||||||
}, "turnip-release-check").start()
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Download one release driver and import it through the same importer a picked zip uses. */
|
|
||||||
private fun downloadReleaseDriver(assetName: String) {
|
|
||||||
val asset = TurnipReleases.cached(this)?.assets?.firstOrNull { it.name == assetName } ?: return
|
|
||||||
if (releaseProgress.containsKey(assetName)) return
|
|
||||||
releaseProgress[assetName] = 0
|
|
||||||
refreshReleaseRows()
|
|
||||||
Thread({
|
|
||||||
var file: java.io.File? = null
|
|
||||||
val problem = try {
|
|
||||||
file = TurnipReleases.download(this, asset) { pct ->
|
|
||||||
ui.post { releaseProgress[assetName] = pct; refreshReleaseRows() }
|
|
||||||
}
|
|
||||||
val uri = Uri.fromFile(file)
|
|
||||||
val id = if (asset.linux) LinuxVulkanDriverManager(this).installDriver(uri, asset.name)
|
|
||||||
else TurnipDriver(this).installFromZip(uri, asset.name)
|
|
||||||
TurnipReleases.recordDownload(this, asset, id)
|
|
||||||
null
|
|
||||||
} catch (e: IllegalArgumentException) {
|
|
||||||
e.message
|
|
||||||
} catch (e: Exception) {
|
|
||||||
Log.w(TAG, "release driver download", e)
|
|
||||||
"Download failed: ${e.message}"
|
|
||||||
} finally {
|
|
||||||
file?.let { com.droiddeck.launcher.core.FileUtils.delete(it) }
|
|
||||||
}
|
|
||||||
ui.post {
|
|
||||||
releaseProgress.remove(assetName)
|
|
||||||
android.widget.Toast.makeText(
|
|
||||||
this, problem ?: "Installed ${asset.name.removeSuffix(".zip")} - pick it in the menu",
|
|
||||||
android.widget.Toast.LENGTH_LONG,
|
|
||||||
).show()
|
|
||||||
refreshDrivers()
|
|
||||||
}
|
|
||||||
}, "download-turnip").start()
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun displayNameOf(uri: Uri): String? = if (uri.scheme == "file") uri.lastPathSegment else try {
|
|
||||||
contentResolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)
|
|
||||||
?.use { c -> if (c.moveToFirst()) c.getString(0) else null }
|
|
||||||
} catch (e: Exception) {
|
|
||||||
null
|
|
||||||
}
|
|
||||||
|
|
||||||
/** The two masks as the dialog shows them; an empty stored list shows as every core ticked. */
|
/** The two masks as the dialog shows them; an empty stored list shows as every core ticked. */
|
||||||
private fun refreshCores() {
|
private fun refreshCores() {
|
||||||
clientOverride = SessionPrefs.clientCpusOverride(this)
|
clientOverride = SessionPrefs.clientCpusOverride(this)
|
||||||
@@ -1264,11 +968,8 @@ class MainActivity : ComponentActivity() {
|
|||||||
refreshPhantomStatus()
|
refreshPhantomStatus()
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun refreshProtons() {
|
|
||||||
protonRows = ProtonExtras.tools.map { ProtonRow(it.id, it.name, ProtonExtras.installed(this, it), ProtonExtras.queued(this, it)) }
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun refresh() {
|
private fun refresh() {
|
||||||
|
if (!busy && LinuxRuntimeInstaller.isInstalling()) followInstall { LinuxRuntimeInstaller.attach(it) }
|
||||||
desktopInstalled = DesktopCatalog.desktopInstalled(this)
|
desktopInstalled = DesktopCatalog.desktopInstalled(this)
|
||||||
offlineAccount = OfflineMode.account(this)
|
offlineAccount = OfflineMode.account(this)
|
||||||
offline = OfflineMode.enabled(this)
|
offline = OfflineMode.enabled(this)
|
||||||
@@ -1285,7 +986,13 @@ class MainActivity : ComponentActivity() {
|
|||||||
// The libraries, off the main thread: manifests and a folder scan.
|
// The libraries, off the main thread: manifests and a folder scan.
|
||||||
Thread({
|
Thread({
|
||||||
val games = if (ready) Library.steamGames(this) + com.droiddeck.launcher.frontend.AddedGames.scan(this).map { g ->
|
val games = if (ready) Library.steamGames(this) + com.droiddeck.launcher.frontend.AddedGames.scan(this).map { g ->
|
||||||
com.droiddeck.launcher.frontend.AddedGameArt.resolve(this, g).let { art -> Library.SteamGame(g.appId.toInt(), g.name, art.portrait ?: art.header, "added", g.gameId, hero = art.hero ?: art.header) }
|
com.droiddeck.launcher.frontend.AddedGameArt.resolve(this, g).let { art ->
|
||||||
|
Library.SteamGame(
|
||||||
|
g.appId.toInt(), g.name, art.portrait ?: art.header, "added", g.gameId,
|
||||||
|
hero = art.hero ?: art.header, gameFiles = g.folder,
|
||||||
|
protonPrefix = Library.protonPrefix(this, g.appId),
|
||||||
|
)
|
||||||
|
}
|
||||||
} else emptyList()
|
} else emptyList()
|
||||||
val emus = Library.emulators(this) { id -> DesktopCatalog.installed(this, id) != null }
|
val emus = Library.emulators(this) { id -> DesktopCatalog.installed(this, id) != null }
|
||||||
ui.post { steamGames = games; emulatorList = emus }
|
ui.post { steamGames = games; emulatorList = emus }
|
||||||
@@ -1354,17 +1061,28 @@ class MainActivity : ComponentActivity() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private fun install(release: LinuxRuntimeInstaller.Release) {
|
private fun install(release: LinuxRuntimeInstaller.Release) {
|
||||||
|
// The service keeps the process alive if the user switches away; this screen joins the
|
||||||
|
// same install (or starts it, if it gets there first) to show the progress.
|
||||||
|
com.droiddeck.launcher.runtime.RuntimeInstallService.start(this, release)
|
||||||
|
followInstall { listener -> LinuxRuntimeInstaller.install(this, release, listener) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Shows an install's progress until it ends. [run] either starts one or joins the one already
|
||||||
|
* running (null: nothing was), which is how a launcher rebuilt mid-install picks it back up.
|
||||||
|
*/
|
||||||
|
private fun followInstall(run: (LinuxRuntimeInstaller.ProgressListener) -> Boolean?) {
|
||||||
busy = true
|
busy = true
|
||||||
failed = false
|
failed = false
|
||||||
stage = "Starting…"
|
stage = "Starting…"
|
||||||
percent = -1
|
percent = -1
|
||||||
Thread({
|
Thread({
|
||||||
val ok = LinuxRuntimeInstaller.install(this, release) { s, p ->
|
val ok = run(LinuxRuntimeInstaller.ProgressListener { s, p ->
|
||||||
ui.post { stage = s; percent = p }
|
ui.post { stage = s; percent = p }
|
||||||
}
|
})
|
||||||
ui.post {
|
ui.post {
|
||||||
busy = false
|
busy = false
|
||||||
failed = !ok
|
if (ok != null) failed = !ok
|
||||||
refresh()
|
refresh()
|
||||||
}
|
}
|
||||||
}, "install").start()
|
}, "install").start()
|
||||||
|
|||||||
@@ -0,0 +1,62 @@
|
|||||||
|
package com.droiddeck.launcher
|
||||||
|
|
||||||
|
import android.os.Handler
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.mutableIntStateOf
|
||||||
|
import androidx.compose.runtime.mutableStateOf
|
||||||
|
import androidx.compose.runtime.setValue
|
||||||
|
import com.droiddeck.launcher.session.ProtonExtras
|
||||||
|
import com.droiddeck.launcher.ui.ProtonRow
|
||||||
|
import com.droiddeck.launcher.session.SessionState
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The optional ARM64 Protons (GE-Proton, proton-cachyos): the rows the page lists and an install or
|
||||||
|
* removal in progress. The launcher screen keeps one and shows it.
|
||||||
|
*/
|
||||||
|
internal class ProtonMenu(private val activity: android.app.Activity, private val ui: android.os.Handler) {
|
||||||
|
var protonRows by mutableStateOf<List<ProtonRow>>(emptyList())
|
||||||
|
var protonBusyId by mutableStateOf<String?>(null)
|
||||||
|
var protonStage by mutableStateOf<String?>(null)
|
||||||
|
var protonPercent by mutableIntStateOf(-1)
|
||||||
|
|
||||||
|
fun installProton(id: String) {
|
||||||
|
val tool = ProtonExtras.tools.firstOrNull { it.id == id } ?: return
|
||||||
|
if (protonBusyId != null || SessionState.running) return
|
||||||
|
ProtonExtras.unqueue(activity, tool)
|
||||||
|
protonBusyId = id
|
||||||
|
protonStage = "Starting…"
|
||||||
|
protonPercent = -1
|
||||||
|
Thread({
|
||||||
|
val problem = ProtonExtras.install(activity, tool) { label, value ->
|
||||||
|
ui.post { protonStage = label; protonPercent = value }
|
||||||
|
}
|
||||||
|
ui.post {
|
||||||
|
protonBusyId = null
|
||||||
|
protonStage = null
|
||||||
|
protonPercent = -1
|
||||||
|
refreshProtons()
|
||||||
|
if (problem != null) android.widget.Toast.makeText(activity, problem, android.widget.Toast.LENGTH_LONG).show()
|
||||||
|
}
|
||||||
|
}, "install-proton-$id").start()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun removeProton(id: String) {
|
||||||
|
val tool = ProtonExtras.tools.firstOrNull { it.id == id } ?: return
|
||||||
|
if (protonBusyId != null || SessionState.running) return
|
||||||
|
protonBusyId = id
|
||||||
|
protonStage = "Removing ${tool.name}…"
|
||||||
|
protonPercent = -1
|
||||||
|
Thread({
|
||||||
|
ProtonExtras.remove(activity, tool)
|
||||||
|
ui.post {
|
||||||
|
protonBusyId = null
|
||||||
|
protonStage = null
|
||||||
|
refreshProtons()
|
||||||
|
}
|
||||||
|
}, "remove-proton-$id").start()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun refreshProtons() {
|
||||||
|
protonRows = ProtonExtras.tools.map { ProtonRow(it.id, it.name, ProtonExtras.installed(activity, it), ProtonExtras.queued(activity, it)) }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -97,6 +97,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
|||||||
private var touchMode by mutableStateOf(SessionPrefs.TOUCH_AUTO)
|
private var touchMode by mutableStateOf(SessionPrefs.TOUCH_AUTO)
|
||||||
private var cursorPos by mutableStateOf(androidx.compose.ui.geometry.Offset(-100f, -100f))
|
private var cursorPos by mutableStateOf(androidx.compose.ui.geometry.Offset(-100f, -100f))
|
||||||
private var cursorVisible by mutableStateOf(false)
|
private var cursorVisible by mutableStateOf(false)
|
||||||
|
/** The blue the front end flooded to on the way in; the loading screen opens on it (LaunchFlood). */
|
||||||
|
private var floodColor by mutableStateOf<Int?>(null)
|
||||||
private val cursorHide = Runnable { cursorVisible = false }
|
private val cursorHide = Runnable { cursorVisible = false }
|
||||||
/** When the pad or the on-screen controls were last used (uptimeMillis); see [showCursor]. */
|
/** When the pad or the on-screen controls were last used (uptimeMillis); see [showCursor]. */
|
||||||
private var lastPadInputMs = 0L
|
private var lastPadInputMs = 0L
|
||||||
@@ -232,7 +234,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
|||||||
root.pointerIcon = noCursor
|
root.pointerIcon = noCursor
|
||||||
surfaceView.pointerIcon = noCursor
|
surfaceView.pointerIcon = noCursor
|
||||||
|
|
||||||
loading = LoadingState(this)
|
loading = LoadingState(this, steam = loadingMode() == SessionService.MODE_STEAM)
|
||||||
if (!SessionState.running) {
|
if (!SessionState.running) {
|
||||||
val needRuntime = com.droiddeck.launcher.runtime.LinuxRuntimeInstaller.installedVersion(this) == null
|
val needRuntime = com.droiddeck.launcher.runtime.LinuxRuntimeInstaller.installedVersion(this) == null
|
||||||
val needDesktop = intent.getStringExtra(SessionService.EXTRA_MODE) == SessionService.MODE_DESKTOP &&
|
val needDesktop = intent.getStringExtra(SessionService.EXTRA_MODE) == SessionService.MODE_DESKTOP &&
|
||||||
@@ -252,130 +254,17 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
|||||||
}
|
}
|
||||||
readPrefs()
|
readPrefs()
|
||||||
|
|
||||||
// One Compose layer for every menu and overlay. Touches nothing in it consumes fall
|
intent.getIntExtra(com.droiddeck.launcher.ui.EXTRA_FLOOD, 0).takeIf { it != 0 && loading.visible }?.let {
|
||||||
// through to the pad and the game underneath.
|
floodColor = it
|
||||||
sessionOverlay = ComposeView(this).apply {
|
window.setBackgroundDrawable(android.graphics.drawable.ColorDrawable(it))
|
||||||
isFocusable = true
|
|
||||||
isFocusableInTouchMode = true
|
|
||||||
setContent {
|
|
||||||
DroidDeckTheme {
|
|
||||||
CursorOverlay(cursorPos, cursorVisible, resources.displayMetrics.density,
|
|
||||||
cursorImage, cursorHotX, cursorHotY, cursorImageScale)
|
|
||||||
if (hud.text.isNotEmpty()) HudText(hud.text)
|
|
||||||
if (loading.visible) LoadingOverlay(
|
|
||||||
loading.step, loading.percent, loading.elapsed, loading.hint, loading.ended,
|
|
||||||
title = loadingTitle(), steam = loadingMode() == SessionService.MODE_STEAM,
|
|
||||||
// As the drawer's Stop does: the service stops, and a start still installing is cancelled.
|
|
||||||
onCancel = { SessionService.stop(this@SessionActivity); finish() },
|
|
||||||
)
|
|
||||||
// Opening the drawer takes the controller away from the game: release its pad.
|
|
||||||
androidx.compose.runtime.LaunchedEffect(drawerOpen) {
|
|
||||||
if (drawerOpen) {
|
|
||||||
padBridge?.releaseAll()
|
|
||||||
androidx.compose.runtime.withFrameNanos { }
|
|
||||||
val requested = sessionOverlay.requestFocus()
|
|
||||||
Log.i(TAG, "drawer root focus requested=$requested focused=${sessionOverlay.hasFocus()}")
|
|
||||||
} else {
|
|
||||||
releaseDrawerDirection()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// 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) },
|
|
||||||
onAndroidKeyboard = { pcKeyboardOpen = false; keyboard?.toggle() },
|
|
||||||
onClose = { pcKeyboardOpen = false },
|
|
||||||
)
|
|
||||||
SessionDrawer(drawerOpen, drawerPage, drawerControllerActive, onPageChange = { drawerPage = it }, a = DrawerActions(
|
|
||||||
steam = SessionState.mode == SessionService.MODE_STEAM,
|
|
||||||
title = if (SessionState.mode == SessionService.MODE_RUN)
|
|
||||||
com.droiddeck.launcher.frontend.Library.nameForProgram(SessionState.program) ?: "Game" else null,
|
|
||||||
isHomeApp = isHomeApp,
|
|
||||||
androidApps = androidApps,
|
|
||||||
hudOn = hudOn,
|
|
||||||
fillScreen = if (SessionState.mode == SessionService.MODE_STEAM) fillScreen else null,
|
|
||||||
frameGenEngine = frameGenEngine, frameGenMultiplier = frameGenMultiplier,
|
|
||||||
lsfgReady = LsfgNative.isInstalled(this@SessionActivity),
|
|
||||||
oscMode = oscMode, suspendPolicy = suspendPolicy, touchMode = touchMode,
|
|
||||||
touchAuto = if (usingTouchpad()) "touchpad" else "direct",
|
|
||||||
shapeMode = shapeMode, fexPreset = fexPreset,
|
|
||||||
secondScreenMode = secondScreenMode,
|
|
||||||
secondScreenDisplays = secondScreenDisplays,
|
|
||||||
selectedSecondScreenDisplay = selectedSecondScreenDisplay,
|
|
||||||
onHud = { on -> SessionPrefs.setHudEnabled(this@SessionActivity, on); hudOn = on; hud.refresh() },
|
|
||||||
onFillScreen = { on -> SessionPrefs.setForceFullscreen(this@SessionActivity, on); fillScreen = on },
|
|
||||||
onFrameGenPick = { engine, multiplier ->
|
|
||||||
FrameGen.set(this@SessionActivity, engine, multiplier)
|
|
||||||
readPrefs()
|
|
||||||
applyFrameGen()
|
|
||||||
},
|
|
||||||
onKeyboard = { drawerOpen = false; pcKeyboardOpen = false; keyboard?.toggle() },
|
|
||||||
onHardwareKeyboard = { drawerOpen = false; pcKeyboardOpen = !pcKeyboardOpen },
|
|
||||||
onSteamMenu = if (SessionState.mode == SessionService.MODE_STEAM) ({ sendSteamGuide() }) else null,
|
|
||||||
onQam = if (SessionState.mode == SessionService.MODE_STEAM) ({ triggerSteamQam() }) else null,
|
|
||||||
// The desktop with Steam's desktop client in it, in this session's place: the
|
|
||||||
// session ends with status 0 and onSessionEnded starts the relaunch (Stop's
|
|
||||||
// finish() would skip it).
|
|
||||||
onSwitchToDesktop = if (SessionState.mode == SessionService.MODE_STEAM) ({
|
|
||||||
drawerOpen = false
|
|
||||||
SessionState.relaunch = Intent(this@SessionActivity, SessionActivity::class.java)
|
|
||||||
.putExtra(SessionService.EXTRA_MODE, SessionService.MODE_DESKTOP)
|
|
||||||
.putExtra(SessionService.EXTRA_STEAM_UI, "desktop")
|
|
||||||
SessionService.stop(this@SessionActivity)
|
|
||||||
}) else null,
|
|
||||||
backActionsInverted = backActionsInverted,
|
|
||||||
onBackActionsInverted = { inverted ->
|
|
||||||
SessionPrefs.setBackActionsInverted(this@SessionActivity, inverted)
|
|
||||||
backActionsInverted = inverted
|
|
||||||
},
|
|
||||||
onOsc = { v -> SessionPrefs.setOscMode(this@SessionActivity, v); readPrefs(); updateOnScreenControls() },
|
|
||||||
onSuspendPolicy = { policy ->
|
|
||||||
SessionPrefs.setSuspendPolicy(this@SessionActivity, SessionState.mode, policy)
|
|
||||||
suspendPolicy = policy
|
|
||||||
SessionService.suspendPolicyChanged(this@SessionActivity)
|
|
||||||
},
|
|
||||||
onTouch = { v -> SessionPrefs.setTouchMode(this@SessionActivity, v); readPrefs() },
|
|
||||||
onShape = { v -> SessionPrefs.setShapeMode(this@SessionActivity, v); readPrefs() },
|
|
||||||
onFexPreset = { v -> SessionPrefs.setFexPreset(this@SessionActivity, v); readPrefs() },
|
|
||||||
onSecondScreenMode = ::selectSecondScreenMode,
|
|
||||||
onSecondScreenDisplay = ::selectSecondScreenDisplay,
|
|
||||||
onLaunchAndroidApp = { app, displayId ->
|
|
||||||
drawerOpen = false
|
|
||||||
try {
|
|
||||||
HomeApp.launch(this@SessionActivity, app, displayId)
|
|
||||||
} catch (_: Exception) {
|
|
||||||
val target = if (displayId == null || displayId == Display.DEFAULT_DISPLAY) "the primary screen"
|
|
||||||
else secondScreenDisplays.firstOrNull { it.id == displayId }?.label ?: "display $displayId"
|
|
||||||
Toast.makeText(this@SessionActivity, "Could not open ${app.label} on $target", Toast.LENGTH_SHORT).show()
|
|
||||||
}
|
|
||||||
},
|
|
||||||
onBackground = { drawerOpen = false; moveTaskToBack(true) },
|
|
||||||
onShareLogs = { drawerOpen = false; shareCurrentSessionLogs() },
|
|
||||||
onStop = { drawerOpen = false; SessionService.stop(this@SessionActivity); finish() },
|
|
||||||
onClose = { drawerOpen = false },
|
|
||||||
components = drawerComponents,
|
|
||||||
onComponentsRefresh = { refreshDrawerComponents() },
|
|
||||||
onComponentSwap = { pid, comp, value -> swapDrawerComponent(pid, comp, value) },
|
|
||||||
))
|
|
||||||
if (SessionState.suspended) SessionPausedOverlay(
|
|
||||||
title = pausedTitle(),
|
|
||||||
onResume = { SessionService.resume(this@SessionActivity) },
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
sessionOverlay = createSessionOverlay()
|
||||||
root.addView(sessionOverlay)
|
root.addView(sessionOverlay)
|
||||||
setContentView(root)
|
setContentView(root)
|
||||||
handleHomeGuideIntent(intent)
|
handleHomeGuideIntent(intent)
|
||||||
|
|
||||||
updateOnScreenControls()
|
updateOnScreenControls()
|
||||||
WaylandCompositor.setFirstFrameListener {
|
WaylandCompositor.setFirstFrameListener(firstFrameListener)
|
||||||
SessionEvents.firstFrame()
|
|
||||||
runOnUiThread {
|
|
||||||
loading.visible = false
|
|
||||||
hud.start()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
SessionEvents.markReadyIfPossible()
|
SessionEvents.markReadyIfPossible()
|
||||||
SessionState.endListener = endListener
|
SessionState.endListener = endListener
|
||||||
// A single Back opens the session menu; two quick presses/swipes send the Steam QAM chord.
|
// A single Back opens the session menu; two quick presses/swipes send the Steam QAM chord.
|
||||||
@@ -384,6 +273,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
|||||||
override fun handleOnBackPressed() {
|
override fun handleOnBackPressed() {
|
||||||
// The PC keyboard closes first (B on a controller), then Back is the drawer again.
|
// The PC keyboard closes first (B on a controller), then Back is the drawer again.
|
||||||
when {
|
when {
|
||||||
|
::loading.isInitialized && loading.ended -> finish()
|
||||||
drawerOpen -> drawerOpen = false
|
drawerOpen -> drawerOpen = false
|
||||||
pcKeyboardOpen -> pcKeyboardOpen = false
|
pcKeyboardOpen -> pcKeyboardOpen = false
|
||||||
else -> routeBackAction()
|
else -> routeBackAction()
|
||||||
@@ -393,6 +283,130 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
|||||||
watchSession()
|
watchSession()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* One Compose layer for every menu and overlay. Touches nothing in it consumes fall through to
|
||||||
|
* the pad and the game underneath.
|
||||||
|
*/
|
||||||
|
private fun createSessionOverlay(): ComposeView = ComposeView(this).apply {
|
||||||
|
isFocusable = true
|
||||||
|
isFocusableInTouchMode = true
|
||||||
|
setContent {
|
||||||
|
DroidDeckTheme {
|
||||||
|
CursorOverlay(cursorPos, cursorVisible, resources.displayMetrics.density,
|
||||||
|
cursorImage, cursorHotX, cursorHotY, cursorImageScale)
|
||||||
|
if (hud.text.isNotEmpty()) HudText(hud.text)
|
||||||
|
if (loading.visible) LoadingOverlay(
|
||||||
|
loading.step, loading.percent, loading.elapsed, loading.hint, loading.ended,
|
||||||
|
title = loadingTitle(), steam = loadingMode() == SessionService.MODE_STEAM,
|
||||||
|
// As the drawer's Stop does: the service stops, and a start still installing is cancelled.
|
||||||
|
onCancel = { SessionService.stop(this@SessionActivity); finish() },
|
||||||
|
endedDetail = loading.endedDetail,
|
||||||
|
onRetry = { retrySession() },
|
||||||
|
onShareLogs = { shareCurrentSessionLogs() },
|
||||||
|
onClose = { finish() },
|
||||||
|
flood = floodColor?.let { androidx.compose.ui.graphics.Color(it) },
|
||||||
|
onFlooded = {
|
||||||
|
floodColor = null
|
||||||
|
window.setBackgroundDrawable(android.graphics.drawable.ColorDrawable(android.graphics.Color.BLACK))
|
||||||
|
},
|
||||||
|
)
|
||||||
|
// Opening the drawer takes the controller away from the game: release its pad.
|
||||||
|
androidx.compose.runtime.LaunchedEffect(drawerOpen) {
|
||||||
|
if (drawerOpen) {
|
||||||
|
padBridge?.releaseAll()
|
||||||
|
androidx.compose.runtime.withFrameNanos { }
|
||||||
|
val requested = sessionOverlay.requestFocus()
|
||||||
|
Log.i(TAG, "drawer root focus requested=$requested focused=${sessionOverlay.hasFocus()}")
|
||||||
|
} else {
|
||||||
|
releaseDrawerDirection()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// 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) },
|
||||||
|
onAndroidKeyboard = { pcKeyboardOpen = false; keyboard?.toggle() },
|
||||||
|
onClose = { pcKeyboardOpen = false },
|
||||||
|
)
|
||||||
|
SessionDrawer(drawerOpen, drawerPage, drawerControllerActive, onPageChange = { drawerPage = it }, a = DrawerActions(
|
||||||
|
steam = SessionState.mode == SessionService.MODE_STEAM,
|
||||||
|
title = if (SessionState.mode == SessionService.MODE_RUN)
|
||||||
|
com.droiddeck.launcher.frontend.Library.nameForProgram(SessionState.program) ?: "Game" else null,
|
||||||
|
isHomeApp = isHomeApp,
|
||||||
|
androidApps = androidApps,
|
||||||
|
hudOn = hudOn,
|
||||||
|
fillScreen = if (SessionState.mode == SessionService.MODE_STEAM) fillScreen else null,
|
||||||
|
frameGenEngine = frameGenEngine, frameGenMultiplier = frameGenMultiplier,
|
||||||
|
lsfgReady = LsfgNative.isInstalled(this@SessionActivity),
|
||||||
|
oscMode = oscMode, suspendPolicy = suspendPolicy, touchMode = touchMode,
|
||||||
|
touchAuto = if (usingTouchpad()) "touchpad" else "direct",
|
||||||
|
shapeMode = shapeMode, fexPreset = fexPreset,
|
||||||
|
secondScreenMode = secondScreenMode,
|
||||||
|
secondScreenDisplays = secondScreenDisplays,
|
||||||
|
selectedSecondScreenDisplay = selectedSecondScreenDisplay,
|
||||||
|
onHud = { on -> SessionPrefs.setHudEnabled(this@SessionActivity, on); hudOn = on; hud.refresh() },
|
||||||
|
onFillScreen = { on -> SessionPrefs.setForceFullscreen(this@SessionActivity, on); fillScreen = on },
|
||||||
|
onFrameGenPick = { engine, multiplier ->
|
||||||
|
FrameGen.set(this@SessionActivity, engine, multiplier)
|
||||||
|
readPrefs()
|
||||||
|
applyFrameGen()
|
||||||
|
},
|
||||||
|
onKeyboard = { drawerOpen = false; pcKeyboardOpen = false; keyboard?.toggle() },
|
||||||
|
onHardwareKeyboard = { drawerOpen = false; pcKeyboardOpen = !pcKeyboardOpen },
|
||||||
|
onSteamMenu = if (SessionState.mode == SessionService.MODE_STEAM) ({ sendSteamGuide() }) else null,
|
||||||
|
onQam = if (SessionState.mode == SessionService.MODE_STEAM) ({ triggerSteamQam() }) else null,
|
||||||
|
// The desktop with Steam's desktop client in it, in this session's place: the
|
||||||
|
// session ends with status 0 and onSessionEnded starts the relaunch (Stop's
|
||||||
|
// finish() would skip it).
|
||||||
|
onSwitchToDesktop = if (SessionState.mode == SessionService.MODE_STEAM) ({
|
||||||
|
drawerOpen = false
|
||||||
|
SessionState.relaunch = Intent(this@SessionActivity, SessionActivity::class.java)
|
||||||
|
.putExtra(SessionService.EXTRA_MODE, SessionService.MODE_DESKTOP)
|
||||||
|
.putExtra(SessionService.EXTRA_STEAM_UI, "desktop")
|
||||||
|
SessionService.stop(this@SessionActivity)
|
||||||
|
}) else null,
|
||||||
|
backActionsInverted = backActionsInverted,
|
||||||
|
onBackActionsInverted = { inverted ->
|
||||||
|
SessionPrefs.setBackActionsInverted(this@SessionActivity, inverted)
|
||||||
|
backActionsInverted = inverted
|
||||||
|
},
|
||||||
|
onOsc = { v -> SessionPrefs.setOscMode(this@SessionActivity, v); readPrefs(); updateOnScreenControls() },
|
||||||
|
onSuspendPolicy = { policy ->
|
||||||
|
SessionPrefs.setSuspendPolicy(this@SessionActivity, SessionState.mode, policy)
|
||||||
|
suspendPolicy = policy
|
||||||
|
SessionService.suspendPolicyChanged(this@SessionActivity)
|
||||||
|
},
|
||||||
|
onTouch = { v -> SessionPrefs.setTouchMode(this@SessionActivity, v); readPrefs() },
|
||||||
|
onShape = { v -> SessionPrefs.setShapeMode(this@SessionActivity, v); readPrefs() },
|
||||||
|
onFexPreset = { v -> SessionPrefs.setFexPreset(this@SessionActivity, v); readPrefs() },
|
||||||
|
onSecondScreenMode = ::selectSecondScreenMode,
|
||||||
|
onSecondScreenDisplay = ::selectSecondScreenDisplay,
|
||||||
|
onLaunchAndroidApp = { app, displayId ->
|
||||||
|
drawerOpen = false
|
||||||
|
try {
|
||||||
|
HomeApp.launch(this@SessionActivity, app, displayId)
|
||||||
|
} catch (_: Exception) {
|
||||||
|
val target = if (displayId == null || displayId == Display.DEFAULT_DISPLAY) "the primary screen"
|
||||||
|
else secondScreenDisplays.firstOrNull { it.id == displayId }?.label ?: "display $displayId"
|
||||||
|
Toast.makeText(this@SessionActivity, "Could not open ${app.label} on $target", Toast.LENGTH_SHORT).show()
|
||||||
|
}
|
||||||
|
},
|
||||||
|
onBackground = { drawerOpen = false; moveTaskToBack(true) },
|
||||||
|
onShareLogs = { drawerOpen = false; shareCurrentSessionLogs() },
|
||||||
|
onStop = { drawerOpen = false; SessionService.stop(this@SessionActivity); finish() },
|
||||||
|
onClose = { drawerOpen = false },
|
||||||
|
components = drawerComponents,
|
||||||
|
onComponentsRefresh = { refreshDrawerComponents() },
|
||||||
|
onComponentSwap = { pid, comp, value -> swapDrawerComponent(pid, comp, value) },
|
||||||
|
))
|
||||||
|
if (SessionState.suspended) SessionPausedOverlay(
|
||||||
|
title = pausedTitle(),
|
||||||
|
onResume = { SessionService.resume(this@SessionActivity) },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private fun refreshHomeApp() {
|
private fun refreshHomeApp() {
|
||||||
isHomeApp = HomeApp.isDefault(this)
|
isHomeApp = HomeApp.isDefault(this)
|
||||||
androidApps = if (isHomeApp) HomeApp.launchableApps(this) else emptyList()
|
androidApps = if (isHomeApp) HomeApp.launchableApps(this) else emptyList()
|
||||||
@@ -595,6 +609,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
|||||||
SessionEvents.fail(code, problem)
|
SessionEvents.fail(code, problem)
|
||||||
collectStartArtifacts("session start failed")
|
collectStartArtifacts("session start failed")
|
||||||
loading.showEnded(problem)
|
loading.showEnded(problem)
|
||||||
|
focusEndedScreen()
|
||||||
return@post
|
return@post
|
||||||
}
|
}
|
||||||
loading.percent = -1
|
loading.percent = -1
|
||||||
@@ -884,19 +899,30 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private fun showEnded(status: Int, hint: String?) {
|
private fun showEnded(status: Int, hint: String?) {
|
||||||
run {
|
if (status == 0) {
|
||||||
if (status != 0) {
|
finish()
|
||||||
loading.showEnded(
|
return
|
||||||
"The session ended ($status)\n${SessionState.logFile?.path ?: "-"}" +
|
|
||||||
(if (hint != null) "\n\n$hint" else "")
|
|
||||||
)
|
|
||||||
// A moment on screen, so a failure is readable rather than a flash of black;
|
|
||||||
// longer when there is advice to read.
|
|
||||||
Handler(Looper.getMainLooper()).postDelayed({ finish() }, if (hint != null) 9000 else 4000)
|
|
||||||
} else {
|
|
||||||
finish()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
// It stays until the user leaves: a failure read against a timer is a failure not read.
|
||||||
|
loading.showEnded(
|
||||||
|
hint ?: "Steam stopped unexpectedly. Share the logs with a bug report, or try again.",
|
||||||
|
"Exit status $status · ${SessionState.logFile?.path ?: "no log"}",
|
||||||
|
)
|
||||||
|
focusEndedScreen()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The ended screen's buttons take the pad: it is no longer driving a game. */
|
||||||
|
private fun focusEndedScreen() {
|
||||||
|
drawerOpen = false
|
||||||
|
padBridge?.releaseAll()
|
||||||
|
uiHandler.post { sessionOverlay.requestFocus() }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The same start again, in a fresh activity: the ended one keeps no session to reuse. */
|
||||||
|
private fun retrySession() {
|
||||||
|
val again = Intent(intent)
|
||||||
|
finish()
|
||||||
|
startActivity(again)
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -952,6 +978,14 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
|||||||
}
|
}
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
// The ended screen is a page of buttons: the pad drives them, and B leaves.
|
||||||
|
if (::loading.isInitialized && loading.ended) {
|
||||||
|
if (event.keyCode == KeyEvent.KEYCODE_BUTTON_B || event.keyCode == KeyEvent.KEYCODE_BACK) {
|
||||||
|
if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) finish()
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return super.dispatchKeyEvent(event)
|
||||||
|
}
|
||||||
if (drawerOpen) {
|
if (drawerOpen) {
|
||||||
if (fromController && (event.keyCode == KeyEvent.KEYCODE_BUTTON_L1 || event.keyCode == KeyEvent.KEYCODE_BUTTON_R1)) {
|
if (fromController && (event.keyCode == KeyEvent.KEYCODE_BUTTON_L1 || event.keyCode == KeyEvent.KEYCODE_BUTTON_R1)) {
|
||||||
if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) {
|
if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) {
|
||||||
@@ -1439,6 +1473,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
|||||||
|
|
||||||
override fun onResume() {
|
override fun onResume() {
|
||||||
super.onResume()
|
super.onResume()
|
||||||
|
com.droiddeck.launcher.ui.Motion.refresh(this)
|
||||||
refreshHomeApp()
|
refreshHomeApp()
|
||||||
if (intent?.action == SessionService.ACTION_RESUME) {
|
if (intent?.action == SessionService.ACTION_RESUME) {
|
||||||
intent.action = null
|
intent.action = null
|
||||||
@@ -1453,6 +1488,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
|||||||
}
|
}
|
||||||
|
|
||||||
override fun onPause() {
|
override fun onPause() {
|
||||||
|
// 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
|
||||||
|
pcKeyboardOpen = false
|
||||||
(getSystemService(INPUT_SERVICE) as? InputManager)?.unregisterInputDeviceListener(deviceListener)
|
(getSystemService(INPUT_SERVICE) as? InputManager)?.unregisterInputDeviceListener(deviceListener)
|
||||||
releaseDrawerDirection()
|
releaseDrawerDirection()
|
||||||
// A button held when the app goes away would stay held in the ring for the whole session.
|
// A button held when the app goes away would stay held in the ring for the whole session.
|
||||||
@@ -1492,6 +1531,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
|||||||
|
|
||||||
/** Ours, so a finishing activity never unhooks the one that replaced it. */
|
/** Ours, so a finishing activity never unhooks the one that replaced it. */
|
||||||
private val endListener: (Int) -> Unit = { status -> onSessionEnded(status) }
|
private val endListener: (Int) -> Unit = { status -> onSessionEnded(status) }
|
||||||
|
private val firstFrameListener = Runnable {
|
||||||
|
SessionEvents.firstFrame()
|
||||||
|
runOnUiThread {
|
||||||
|
loading.visible = false
|
||||||
|
hud.start()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
override fun onDestroy() {
|
override fun onDestroy() {
|
||||||
// Deliberately does NOT end the session: this activity can be destroyed while the user is
|
// Deliberately does NOT end the session: this activity can be destroyed while the user is
|
||||||
@@ -1504,7 +1550,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
|||||||
if (::hud.isInitialized) hud.stop()
|
if (::hud.isInitialized) hud.stop()
|
||||||
padBridge?.stop()
|
padBridge?.stop()
|
||||||
if (SessionState.endListener === endListener) SessionState.endListener = null
|
if (SessionState.endListener === endListener) SessionState.endListener = null
|
||||||
WaylandCompositor.setFirstFrameListener(null)
|
WaylandCompositor.clearFirstFrameListener(firstFrameListener)
|
||||||
super.onDestroy()
|
super.onDestroy()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,25 @@
|
|||||||
|
package com.droiddeck.launcher.core;
|
||||||
|
|
||||||
|
import java.io.File;
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Where an archive entry may land. An entry name ("../x", "/etc/x") or a symlink already written
|
||||||
|
* by an earlier entry can point outside the directory being filled; the canonical path follows
|
||||||
|
* both, so anything that does not resolve inside it is refused.
|
||||||
|
*/
|
||||||
|
public final class ArchivePaths {
|
||||||
|
private ArchivePaths() {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The file for {@code name} under {@code destination}, or null when it would resolve outside
|
||||||
|
* it. The destination itself counts as inside (a "./" entry).
|
||||||
|
*/
|
||||||
|
public static File inside(File destination, String name) throws IOException {
|
||||||
|
String base = destination.getCanonicalPath();
|
||||||
|
File file = new File(destination, name);
|
||||||
|
String path = file.getCanonicalPath();
|
||||||
|
if (path.equals(base) || path.startsWith(base + File.separator)) return file;
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
package com.droiddeck.launcher.core
|
||||||
|
|
||||||
|
import java.io.File
|
||||||
|
import java.security.MessageDigest
|
||||||
|
|
||||||
|
/** File checksums as lowercase hex, and GitHub's release-asset digests, in one place. */
|
||||||
|
object Hashes {
|
||||||
|
private val GITHUB_SHA256 = Regex("(?i)sha256:[0-9a-f]{64}")
|
||||||
|
|
||||||
|
@JvmStatic
|
||||||
|
fun sha256(file: File): String = hex(file, "SHA-256")
|
||||||
|
|
||||||
|
@JvmStatic
|
||||||
|
fun sha512(file: File): String = hex(file, "SHA-512")
|
||||||
|
|
||||||
|
/** True when [digest] is GitHub's asset digest form, "sha256:" and 64 hex digits. */
|
||||||
|
@JvmStatic
|
||||||
|
fun isGithubSha256(digest: String?): Boolean = digest != null && digest.matches(GITHUB_SHA256)
|
||||||
|
|
||||||
|
/** The hex of a GitHub asset digest ("sha256:<hex>"), or null when [digest] is not one. */
|
||||||
|
@JvmStatic
|
||||||
|
fun githubSha256(digest: String?): String? = digest?.takeIf { isGithubSha256(it) }?.substringAfter(':')
|
||||||
|
|
||||||
|
private fun hex(file: File, algorithm: String): String {
|
||||||
|
val digest = MessageDigest.getInstance(algorithm)
|
||||||
|
file.inputStream().buffered(1 shl 16).use { input ->
|
||||||
|
val buffer = ByteArray(1 shl 20)
|
||||||
|
while (true) {
|
||||||
|
val n = input.read(buffer)
|
||||||
|
if (n < 0) break
|
||||||
|
digest.update(buffer, 0, n)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return digest.digest().joinToString("") { "%02x".format(it.toInt() and 0xff) }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -23,18 +23,40 @@ object PhantomProcessLimit {
|
|||||||
|
|
||||||
fun read(resolver: ContentResolver, sdk: Int = Build.VERSION.SDK_INT): PhantomProcessStatus {
|
fun read(resolver: ContentResolver, sdk: Int = Build.VERSION.SDK_INT): PhantomProcessStatus {
|
||||||
if (sdk < Build.VERSION_CODES.S) return PhantomProcessStatus.NOT_APPLICABLE
|
if (sdk < Build.VERSION_CODES.S) return PhantomProcessStatus.NOT_APPLICABLE
|
||||||
val value = try {
|
val global = try {
|
||||||
Settings.Global.getString(resolver, SETTING)
|
Settings.Global.getString(resolver, SETTING)
|
||||||
} catch (_: Exception) {
|
} catch (_: Exception) {
|
||||||
return PhantomProcessStatus.UNREADABLE
|
return PhantomProcessStatus.UNREADABLE
|
||||||
}
|
}
|
||||||
return when (value?.trim()?.lowercase()) {
|
return status(global, systemProperty(OVERRIDE_PROPERTY))
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The value Android itself acts on, in FeatureFlagUtils.isEnabled's order: the global setting
|
||||||
|
* when it is set, otherwise the feature-flag override property. Developer options' "Disable
|
||||||
|
* child process restrictions" writes only the property, so a device switched off there has no
|
||||||
|
* global setting at all and must not be reported as unset.
|
||||||
|
*/
|
||||||
|
fun status(global: String?, override: String?): PhantomProcessStatus {
|
||||||
|
val value = global?.trim()?.lowercase()?.takeIf { it.isNotEmpty() }
|
||||||
|
?: override?.trim()?.lowercase()?.takeIf { it.isNotEmpty() }
|
||||||
|
return when (value) {
|
||||||
"false", "0" -> PhantomProcessStatus.DISABLED
|
"false", "0" -> PhantomProcessStatus.DISABLED
|
||||||
null, "" -> PhantomProcessStatus.UNSET
|
null -> PhantomProcessStatus.UNSET
|
||||||
else -> PhantomProcessStatus.ENABLED
|
else -> PhantomProcessStatus.ENABLED
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private const val OVERRIDE_PROPERTY = "persist.sys.fflag.override.$SETTING"
|
||||||
|
|
||||||
|
private fun systemProperty(name: String): String? = try {
|
||||||
|
Class.forName("android.os.SystemProperties")
|
||||||
|
.getMethod("get", String::class.java)
|
||||||
|
.invoke(null, name) as? String
|
||||||
|
} catch (_: Exception) {
|
||||||
|
null
|
||||||
|
}
|
||||||
|
|
||||||
fun blocksSteam(status: PhantomProcessStatus): Boolean =
|
fun blocksSteam(status: PhantomProcessStatus): Boolean =
|
||||||
status != PhantomProcessStatus.NOT_APPLICABLE && status != PhantomProcessStatus.DISABLED
|
status != PhantomProcessStatus.NOT_APPLICABLE && status != PhantomProcessStatus.DISABLED
|
||||||
|
|
||||||
|
|||||||
@@ -37,11 +37,10 @@ public final class TarZst {
|
|||||||
destination.mkdirs();
|
destination.mkdirs();
|
||||||
try (InputStream in = new ZstdCompressorInputStream(new BufferedInputStream(source, 1 << 16));
|
try (InputStream in = new ZstdCompressorInputStream(new BufferedInputStream(source, 1 << 16));
|
||||||
TarArchiveInputStream tar = new TarArchiveInputStream(in)) {
|
TarArchiveInputStream tar = new TarArchiveInputStream(in)) {
|
||||||
String base = destination.getCanonicalPath() + File.separator;
|
|
||||||
TarArchiveEntry entry;
|
TarArchiveEntry entry;
|
||||||
while ((entry = tar.getNextTarEntry()) != null) {
|
while ((entry = tar.getNextTarEntry()) != null) {
|
||||||
File file = new File(destination, entry.getName());
|
File file = ArchivePaths.inside(destination, entry.getName());
|
||||||
if (!file.getCanonicalPath().startsWith(base)) continue;
|
if (file == null) continue;
|
||||||
if (entry.isDirectory()) {
|
if (entry.isDirectory()) {
|
||||||
//noinspection ResultOfMethodCallIgnored
|
//noinspection ResultOfMethodCallIgnored
|
||||||
file.mkdirs();
|
file.mkdirs();
|
||||||
|
|||||||
@@ -0,0 +1,93 @@
|
|||||||
|
package com.droiddeck.launcher.files
|
||||||
|
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.setValue
|
||||||
|
import java.io.File
|
||||||
|
|
||||||
|
// Reading and setting a file's read-only and hidden attributes (the DOS attribute xattr).
|
||||||
|
|
||||||
|
// ── DOS file attributes (Read-only / Hidden) ──
|
||||||
|
// The in-container file manager (wfm.exe) exposes these in its Properties dialog; this mirrors the
|
||||||
|
// same two toggles for files browsed from the app side. No root - we only touch permission bits the
|
||||||
|
// app owns (container files) and the Wine DOS-attribute xattr.
|
||||||
|
|
||||||
|
// FILE_ATTRIBUTE_HIDDEN, as Wine encodes it in the user.DOSATTRIB extended attribute.
|
||||||
|
private const val FILE_ATTRIBUTE_HIDDEN = 0x2
|
||||||
|
|
||||||
|
private const val DOSATTRIB_XATTR = "user.DOSATTRIB"
|
||||||
|
|
||||||
|
// Snapshot of a file's two toggleable attributes. hiddenSupported is false when the underlying
|
||||||
|
// filesystem can't store the DOSATTRIB xattr (the FUSE /storage volumes) - the Hidden toggle is then
|
||||||
|
// disabled while Read-only keeps working.
|
||||||
|
internal data class FileAttrState(
|
||||||
|
val readOnly: Boolean,
|
||||||
|
val hidden: Boolean,
|
||||||
|
val hiddenSupported: Boolean,
|
||||||
|
)
|
||||||
|
|
||||||
|
// Wine (and Samba) store user.DOSATTRIB as an ASCII hex string ("0x22"), sometimes with trailing
|
||||||
|
// Samba fields after a separator. We only need the leading DOS-attribute hex, so read from the "0x"
|
||||||
|
// prefix and stop at the first non-hex character.
|
||||||
|
private fun parseDosAttrib(raw: ByteArray): Int {
|
||||||
|
val s = String(raw, Charsets.US_ASCII).trim()
|
||||||
|
val hex = if (s.startsWith("0x") || s.startsWith("0X")) s.substring(2) else s
|
||||||
|
val digits = hex.takeWhile { it in '0'..'9' || it in 'a'..'f' || it in 'A'..'F' }
|
||||||
|
return digits.toIntOrNull(16) ?: 0
|
||||||
|
}
|
||||||
|
|
||||||
|
// Read the current read-only + Wine-hidden state. Never throws: an xattr-unsupported filesystem
|
||||||
|
// comes back hiddenSupported=false (Hidden toggle disabled), Read-only always resolves.
|
||||||
|
internal fun readFileAttrs(file: File): FileAttrState {
|
||||||
|
val path = file.absolutePath
|
||||||
|
// Read-only reflects the OWNER write bit - that's what Wine maps to FILE_ATTRIBUTE_READONLY.
|
||||||
|
val readOnly = runCatching {
|
||||||
|
(android.system.Os.stat(path).st_mode and android.system.OsConstants.S_IWUSR) == 0
|
||||||
|
}.getOrDefault(!file.canWrite())
|
||||||
|
|
||||||
|
var hidden = false
|
||||||
|
var supported = true
|
||||||
|
try {
|
||||||
|
hidden = (parseDosAttrib(android.system.Os.getxattr(path, DOSATTRIB_XATTR)) and FILE_ATTRIBUTE_HIDDEN) != 0
|
||||||
|
} catch (e: android.system.ErrnoException) {
|
||||||
|
// ENODATA: xattr namespace works, the attribute just isn't set yet -> still toggleable.
|
||||||
|
// ENOTSUP/EOPNOTSUPP/anything else: the fs can't store it -> disable the Hidden toggle.
|
||||||
|
supported = e.errno == android.system.OsConstants.ENODATA
|
||||||
|
} catch (e: Exception) {
|
||||||
|
supported = false
|
||||||
|
}
|
||||||
|
return FileAttrState(readOnly, hidden, supported)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Toggle read-only by flipping the write bits, preserving every other permission bit. Setting
|
||||||
|
// read-only clears owner/group/other write (so Wine sees FILE_ATTRIBUTE_READONLY regardless of which
|
||||||
|
// write bit it checks); clearing it restores owner write. Falls back to File.setWritable if chmod is
|
||||||
|
// somehow refused. Returns true on success.
|
||||||
|
internal fun setReadOnly(file: File, readOnly: Boolean): Boolean = runCatching {
|
||||||
|
val path = file.absolutePath
|
||||||
|
val mode = android.system.Os.stat(path).st_mode
|
||||||
|
val writeBits = android.system.OsConstants.S_IWUSR or
|
||||||
|
android.system.OsConstants.S_IWGRP or android.system.OsConstants.S_IWOTH
|
||||||
|
val newMode = if (readOnly) mode and writeBits.inv()
|
||||||
|
else mode or android.system.OsConstants.S_IWUSR
|
||||||
|
android.system.Os.chmod(path, newMode)
|
||||||
|
true
|
||||||
|
}.getOrElse { file.setWritable(!readOnly, true) }
|
||||||
|
|
||||||
|
// Flip Wine's DOS hidden bit in user.DOSATTRIB, preserving the other DOS-attribute bits
|
||||||
|
// (archive/system/read-only) already encoded there, and synthesizing a minimal value when absent.
|
||||||
|
// Writes Wine's own "0x%x" format, which Wine reads back natively. Returns false when the fs can't
|
||||||
|
// store the xattr, so the caller can disable just the Hidden toggle.
|
||||||
|
internal fun setHidden(file: File, hidden: Boolean): Boolean = try {
|
||||||
|
val path = file.absolutePath
|
||||||
|
var attr = try {
|
||||||
|
parseDosAttrib(android.system.Os.getxattr(path, DOSATTRIB_XATTR))
|
||||||
|
} catch (e: android.system.ErrnoException) {
|
||||||
|
if (e.errno == android.system.OsConstants.ENODATA) 0 else throw e
|
||||||
|
}
|
||||||
|
attr = if (hidden) attr or FILE_ATTRIBUTE_HIDDEN else attr and FILE_ATTRIBUTE_HIDDEN.inv()
|
||||||
|
val value = "0x%x".format(attr).toByteArray(Charsets.US_ASCII)
|
||||||
|
android.system.Os.setxattr(path, DOSATTRIB_XATTR, value, 0)
|
||||||
|
true
|
||||||
|
} catch (e: Exception) {
|
||||||
|
false
|
||||||
|
}
|
||||||
@@ -11,6 +11,7 @@ import androidx.compose.material3.MaterialTheme
|
|||||||
import androidx.compose.material3.Surface
|
import androidx.compose.material3.Surface
|
||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
import com.droiddeck.launcher.ui.DroidDeckTheme
|
import com.droiddeck.launcher.ui.DroidDeckTheme
|
||||||
|
import java.io.File
|
||||||
|
|
||||||
/** The File Manager as a screen of its own, from the Files tile on the main screen. */
|
/** The File Manager as a screen of its own, from the Files tile on the main screen. */
|
||||||
class FileManagerActivity : ComponentActivity() {
|
class FileManagerActivity : ComponentActivity() {
|
||||||
@@ -19,10 +20,11 @@ class FileManagerActivity : ComponentActivity() {
|
|||||||
if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
|
if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
|
||||||
requestPermissions(arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), 1)
|
requestPermissions(arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), 1)
|
||||||
}
|
}
|
||||||
|
val initialDir = intent.getStringExtra(EXTRA_START_DIR)?.let(::File)
|
||||||
setContent {
|
setContent {
|
||||||
DroidDeckTheme {
|
DroidDeckTheme {
|
||||||
Surface(modifier = Modifier.fillMaxSize().systemBarsPadding(), color = MaterialTheme.colorScheme.background) {
|
Surface(modifier = Modifier.fillMaxSize().systemBarsPadding(), color = MaterialTheme.colorScheme.background) {
|
||||||
FileManagerScreen()
|
FileManagerScreen(initialDir = initialDir)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -32,4 +34,8 @@ class FileManagerActivity : ComponentActivity() {
|
|||||||
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
|
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
|
||||||
if (requestCode == 1 && grantResults.firstOrNull() == PackageManager.PERMISSION_GRANTED) recreate()
|
if (requestCode == 1 && grantResults.firstOrNull() == PackageManager.PERMISSION_GRANTED) recreate()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
const val EXTRA_START_DIR = "com.droiddeck.launcher.files.START_DIR"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,599 @@
|
|||||||
|
package com.droiddeck.launcher.files
|
||||||
|
|
||||||
|
import androidx.compose.foundation.BorderStroke
|
||||||
|
import androidx.compose.foundation.Image
|
||||||
|
import androidx.compose.foundation.background
|
||||||
|
import androidx.compose.foundation.border
|
||||||
|
import androidx.compose.foundation.ExperimentalFoundationApi
|
||||||
|
import androidx.compose.foundation.clickable
|
||||||
|
import androidx.compose.foundation.combinedClickable
|
||||||
|
import androidx.compose.foundation.layout.Box
|
||||||
|
import androidx.compose.foundation.layout.Column
|
||||||
|
import androidx.compose.foundation.layout.Row
|
||||||
|
import androidx.compose.foundation.layout.Spacer
|
||||||
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
|
import androidx.compose.foundation.layout.height
|
||||||
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.foundation.layout.size
|
||||||
|
import androidx.compose.foundation.layout.width
|
||||||
|
import androidx.compose.foundation.lazy.LazyColumn
|
||||||
|
import androidx.compose.foundation.lazy.items
|
||||||
|
import androidx.compose.foundation.lazy.grid.items
|
||||||
|
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||||
|
import androidx.compose.material.icons.Icons
|
||||||
|
import androidx.compose.material.icons.filled.Add
|
||||||
|
import androidx.compose.material.icons.filled.Checklist
|
||||||
|
import androidx.compose.material.icons.filled.Delete
|
||||||
|
import androidx.compose.material.icons.filled.FileCopy
|
||||||
|
import androidx.compose.material.icons.filled.Folder
|
||||||
|
import androidx.compose.material.icons.filled.Info
|
||||||
|
import androidx.compose.material.icons.filled.InsertDriveFile
|
||||||
|
import androidx.compose.material.icons.filled.MoreVert
|
||||||
|
import androidx.compose.material.icons.filled.ContentCut
|
||||||
|
import androidx.compose.material.icons.filled.Edit
|
||||||
|
import androidx.compose.material.icons.filled.Star
|
||||||
|
import androidx.compose.material.icons.filled.StarBorder
|
||||||
|
import androidx.compose.material.icons.filled.PushPin
|
||||||
|
import androidx.compose.material.icons.filled.Storage
|
||||||
|
import androidx.compose.material.icons.filled.Image
|
||||||
|
import androidx.compose.material3.Card
|
||||||
|
import androidx.compose.material3.CardDefaults
|
||||||
|
import androidx.compose.material3.DropdownMenu
|
||||||
|
import androidx.compose.material3.DropdownMenuItem
|
||||||
|
import androidx.compose.material3.Icon
|
||||||
|
import androidx.compose.material3.IconButton
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.material3.TextButton
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.LaunchedEffect
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.mutableStateOf
|
||||||
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.runtime.setValue
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.draw.clip
|
||||||
|
import androidx.compose.ui.graphics.Color
|
||||||
|
import androidx.compose.ui.graphics.ImageBitmap
|
||||||
|
import androidx.compose.ui.graphics.asImageBitmap
|
||||||
|
import androidx.compose.ui.layout.ContentScale
|
||||||
|
import androidx.compose.ui.graphics.vector.rememberVectorPainter
|
||||||
|
import androidx.compose.ui.platform.LocalContext
|
||||||
|
import androidx.compose.ui.res.painterResource
|
||||||
|
import coil.compose.AsyncImage
|
||||||
|
import androidx.compose.ui.text.font.FontFamily
|
||||||
|
import androidx.compose.ui.text.font.FontWeight
|
||||||
|
import androidx.compose.ui.text.style.TextOverflow
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import androidx.compose.ui.unit.sp
|
||||||
|
import com.droiddeck.launcher.R
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
|
import java.io.File
|
||||||
|
import java.text.SimpleDateFormat
|
||||||
|
import java.util.Date
|
||||||
|
import java.util.Locale
|
||||||
|
|
||||||
|
// The File Manager's rows, tiles, favourites and context menu.
|
||||||
|
|
||||||
|
// Semantic identity colours for the favourite-card drive badge. Intentionally NOT theme
|
||||||
|
// accent colours - they identify the storage source at a glance. Returns (background, foreground).
|
||||||
|
private fun badgeColors(loc: FavLocation): Pair<Color, Color> {
|
||||||
|
val white = Color(0xFFFFFFFF)
|
||||||
|
return when {
|
||||||
|
loc.storage == FavStorage.INTERNAL -> Color(0xFF2E5FB0) to white // blue
|
||||||
|
loc.storage == FavStorage.SD -> Color(0xFF2E7D32) to white // green
|
||||||
|
else -> Color(0xFF555555) to white // grey
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The context-menu item list shared by the list rows (FileItemRow) and the grid tiles
|
||||||
|
// (FileGridTile), so both open the identical menu. Gating (isDir/canRun/isInno/looksLikeArchive) is
|
||||||
|
// recomputed from [file] here - one source of truth for what each item shows. Every item dismisses
|
||||||
|
// the menu first, then runs its action.
|
||||||
|
@Composable
|
||||||
|
private fun FileContextMenuItems(
|
||||||
|
file: File,
|
||||||
|
isFavorite: Boolean,
|
||||||
|
onSelect: () -> Unit,
|
||||||
|
onRename: () -> Unit,
|
||||||
|
onCopy: () -> Unit,
|
||||||
|
onCut: () -> Unit,
|
||||||
|
onDelete: () -> Unit,
|
||||||
|
onToggleFavorite: () -> Unit,
|
||||||
|
onProperties: () -> Unit,
|
||||||
|
onDismissMenu: () -> Unit,
|
||||||
|
) {
|
||||||
|
val isDir = file.isDirectory
|
||||||
|
DropdownMenuItem(
|
||||||
|
text = { Text("Select") },
|
||||||
|
leadingIcon = { Icon(Icons.Filled.Checklist, null, tint = MaterialTheme.colorScheme.primary) },
|
||||||
|
onClick = { onDismissMenu(); onSelect() },
|
||||||
|
)
|
||||||
|
MenuItemDivider()
|
||||||
|
// Properties: basic info + Read-only / Hidden toggles, for ANY file or folder (handy for config
|
||||||
|
// files like .txt/.cfg/.ini). Kept near the top since it's a common reason to open this menu.
|
||||||
|
DropdownMenuItem(
|
||||||
|
text = { Text("Properties") },
|
||||||
|
leadingIcon = { Icon(Icons.Filled.Info, null, tint = MaterialTheme.colorScheme.primary) },
|
||||||
|
onClick = { onDismissMenu(); onProperties() },
|
||||||
|
)
|
||||||
|
MenuItemDivider()
|
||||||
|
// Favorites are directories - only folders get the pin toggle.
|
||||||
|
if (isDir) {
|
||||||
|
DropdownMenuItem(
|
||||||
|
text = { Text(if (isFavorite) "Remove from Favorites" else "Add to Favorites") },
|
||||||
|
leadingIcon = {
|
||||||
|
Icon(
|
||||||
|
if (isFavorite) Icons.Filled.Star else Icons.Filled.StarBorder,
|
||||||
|
null,
|
||||||
|
tint = MaterialTheme.colorScheme.primary,
|
||||||
|
)
|
||||||
|
},
|
||||||
|
onClick = { onToggleFavorite() },
|
||||||
|
)
|
||||||
|
MenuItemDivider()
|
||||||
|
}
|
||||||
|
DropdownMenuItem(
|
||||||
|
text = { Text("Rename") },
|
||||||
|
leadingIcon = { Icon(Icons.Filled.Edit, null, tint = MaterialTheme.colorScheme.primary) },
|
||||||
|
onClick = { onDismissMenu(); onRename() },
|
||||||
|
)
|
||||||
|
MenuItemDivider()
|
||||||
|
DropdownMenuItem(
|
||||||
|
text = { Text("Copy") },
|
||||||
|
leadingIcon = { Icon(Icons.Filled.FileCopy, null, tint = MaterialTheme.colorScheme.primary) },
|
||||||
|
onClick = { onDismissMenu(); onCopy() },
|
||||||
|
)
|
||||||
|
MenuItemDivider()
|
||||||
|
DropdownMenuItem(
|
||||||
|
text = { Text("Cut") },
|
||||||
|
leadingIcon = { Icon(Icons.Filled.ContentCut, null, tint = MaterialTheme.colorScheme.primary) },
|
||||||
|
onClick = { onDismissMenu(); onCut() },
|
||||||
|
)
|
||||||
|
MenuItemDivider()
|
||||||
|
DropdownMenuItem(
|
||||||
|
text = { Text("Delete") },
|
||||||
|
leadingIcon = { Icon(Icons.Filled.Delete, null, tint = MaterialTheme.colorScheme.primary) },
|
||||||
|
onClick = { onDismissMenu(); onDelete() },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
@OptIn(ExperimentalFoundationApi::class)
|
||||||
|
internal fun FileItemRow(
|
||||||
|
file: File,
|
||||||
|
showActions: Boolean = true,
|
||||||
|
compact: Boolean = false,
|
||||||
|
selectionMode: Boolean = false,
|
||||||
|
selected: Boolean = false,
|
||||||
|
onLongPress: () -> Unit = {},
|
||||||
|
onToggleSelect: () -> Unit = {},
|
||||||
|
onTap: () -> Unit,
|
||||||
|
onMenu: () -> Unit,
|
||||||
|
menuExpanded: Boolean,
|
||||||
|
onDismissMenu: () -> Unit,
|
||||||
|
onSelect: () -> Unit = {},
|
||||||
|
onCopy: () -> Unit,
|
||||||
|
onCut: () -> Unit,
|
||||||
|
onDelete: () -> Unit,
|
||||||
|
onRename: () -> Unit,
|
||||||
|
isFavorite: Boolean = false,
|
||||||
|
onToggleFavorite: () -> Unit = {},
|
||||||
|
onProperties: () -> Unit = {},
|
||||||
|
) {
|
||||||
|
val dateFormat = remember { SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault()) }
|
||||||
|
val isDir = file.isDirectory
|
||||||
|
val isExe = !isDir && file.name.lowercase().let { it.endsWith(".exe") || it.endsWith(".bat") || it.endsWith(".msi") || it.endsWith(".sh") }
|
||||||
|
// Image files show a real thumbnail instead of the generic file icon (handy when picking a
|
||||||
|
// wallpaper/icon). Coil sizes the decode to the 36dp slot and caches it, so scrolling stays smooth.
|
||||||
|
val isImage = !isDir && file.extension.lowercase() in IMAGE_THUMB_EXTS
|
||||||
|
|
||||||
|
// For real PE executables, try to pull out the embedded application icon (async, off the main thread).
|
||||||
|
var exeIcon by remember(file.absolutePath) { mutableStateOf<ImageBitmap?>(null) }
|
||||||
|
if (!isDir && file.name.lowercase().endsWith(".exe")) {
|
||||||
|
LaunchedEffect(file.absolutePath) {
|
||||||
|
val bmp = withContext(Dispatchers.IO) { PeIconExtractor.extract(file) }
|
||||||
|
if (bmp != null) exeIcon = bmp.asImageBitmap()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Card(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.padding(horizontal = 12.dp, vertical = 3.dp)
|
||||||
|
.combinedClickable(
|
||||||
|
// In selection mode a tap toggles instead of opening, so you can rattle through a
|
||||||
|
// folder without long-pressing every single row.
|
||||||
|
onClick = { if (selectionMode) onToggleSelect() else onTap() },
|
||||||
|
onLongClick = onLongPress,
|
||||||
|
),
|
||||||
|
shape = RoundedCornerShape(10.dp),
|
||||||
|
colors = CardDefaults.cardColors(
|
||||||
|
containerColor = if (selected) MaterialTheme.colorScheme.primary.copy(alpha = 0.18f)
|
||||||
|
else MaterialTheme.colorScheme.surfaceContainer,
|
||||||
|
),
|
||||||
|
border = BorderStroke(
|
||||||
|
1.dp,
|
||||||
|
if (selected) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.outline,
|
||||||
|
),
|
||||||
|
) {
|
||||||
|
Row(
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
modifier = Modifier.padding(horizontal = 12.dp, vertical = if (compact) 3.dp else 8.dp),
|
||||||
|
) {
|
||||||
|
if (selectionMode) {
|
||||||
|
androidx.compose.material3.Checkbox(checked = selected, onCheckedChange = { onToggleSelect() })
|
||||||
|
Spacer(Modifier.width(4.dp))
|
||||||
|
}
|
||||||
|
when {
|
||||||
|
// Show the executable's own embedded icon when we managed to extract one.
|
||||||
|
exeIcon != null -> Image(
|
||||||
|
bitmap = exeIcon!!,
|
||||||
|
contentDescription = null,
|
||||||
|
modifier = Modifier.size(if (compact) 24.dp else 36.dp),
|
||||||
|
)
|
||||||
|
isExe -> Icon(
|
||||||
|
painter = painterResource(R.drawable.icon_menu_container),
|
||||||
|
contentDescription = null,
|
||||||
|
tint = MaterialTheme.colorScheme.onSurface,
|
||||||
|
modifier = Modifier.size(if (compact) 24.dp else 36.dp),
|
||||||
|
)
|
||||||
|
isDir -> Icon(
|
||||||
|
imageVector = Icons.Filled.Folder,
|
||||||
|
contentDescription = null,
|
||||||
|
tint = MaterialTheme.colorScheme.primary,
|
||||||
|
modifier = Modifier.size(if (compact) 24.dp else 36.dp),
|
||||||
|
)
|
||||||
|
// Real image preview. Falls back to the generic file icon while loading or on decode failure.
|
||||||
|
isImage -> AsyncImage(
|
||||||
|
model = file,
|
||||||
|
contentDescription = null,
|
||||||
|
contentScale = ContentScale.Crop,
|
||||||
|
placeholder = rememberVectorPainter(Icons.Filled.InsertDriveFile),
|
||||||
|
error = rememberVectorPainter(Icons.Filled.InsertDriveFile),
|
||||||
|
modifier = Modifier
|
||||||
|
.size(36.dp)
|
||||||
|
.clip(RoundedCornerShape(6.dp)),
|
||||||
|
)
|
||||||
|
else -> Icon(
|
||||||
|
imageVector = Icons.Filled.InsertDriveFile,
|
||||||
|
contentDescription = null,
|
||||||
|
tint = MaterialTheme.colorScheme.onSurface,
|
||||||
|
modifier = Modifier.size(if (compact) 24.dp else 36.dp),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
Spacer(Modifier.width(10.dp))
|
||||||
|
Column(modifier = Modifier.weight(1f)) {
|
||||||
|
Text(
|
||||||
|
text = file.name,
|
||||||
|
color = MaterialTheme.colorScheme.onBackground,
|
||||||
|
fontSize = 14.sp,
|
||||||
|
fontWeight = FontWeight.Medium,
|
||||||
|
maxLines = 1,
|
||||||
|
overflow = TextOverflow.Ellipsis,
|
||||||
|
)
|
||||||
|
Text(
|
||||||
|
text = buildString {
|
||||||
|
if (!isDir) append(FileOps.formatBytes(file.length())).append(" \u2022 ")
|
||||||
|
append(dateFormat.format(Date(file.lastModified())))
|
||||||
|
},
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
fontSize = 12.sp,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
if (showActions) Box {
|
||||||
|
IconButton(onClick = onMenu) {
|
||||||
|
Icon(Icons.Filled.MoreVert, "Actions", tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(20.dp))
|
||||||
|
}
|
||||||
|
DropdownMenu(
|
||||||
|
expanded = menuExpanded,
|
||||||
|
onDismissRequest = onDismissMenu,
|
||||||
|
modifier = Modifier.outlinedMenuCard(),
|
||||||
|
) {
|
||||||
|
FileContextMenuItems(
|
||||||
|
file = file,
|
||||||
|
isFavorite = isFavorite,
|
||||||
|
onSelect = onSelect,
|
||||||
|
onRename = onRename,
|
||||||
|
onCopy = onCopy,
|
||||||
|
onCut = onCut,
|
||||||
|
onDelete = onDelete,
|
||||||
|
onToggleFavorite = onToggleFavorite,
|
||||||
|
onProperties = onProperties,
|
||||||
|
onDismissMenu = onDismissMenu,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Dedicated Favorites list that replaces the file list while the star toggle is on.
|
||||||
|
// Reads the store keyed on [favTick] so it recomposes after any pin/unpin.
|
||||||
|
@Composable
|
||||||
|
internal fun FavoritesList(
|
||||||
|
currentDir: File,
|
||||||
|
favTick: Int,
|
||||||
|
onPinCurrent: () -> Unit,
|
||||||
|
onJump: (File) -> Unit,
|
||||||
|
onUnpin: (File) -> Unit,
|
||||||
|
modifier: Modifier = Modifier,
|
||||||
|
) {
|
||||||
|
val context = LocalContext.current
|
||||||
|
val favorites = remember(favTick) {
|
||||||
|
FavoritesStore.list(context).map(::File).filter { it.exists() }
|
||||||
|
}
|
||||||
|
val currentAlreadyPinned = remember(favTick, currentDir.absolutePath) {
|
||||||
|
FavoritesStore.isFavorite(context, currentDir.absolutePath)
|
||||||
|
}
|
||||||
|
|
||||||
|
LazyColumn(modifier = modifier) {
|
||||||
|
item {
|
||||||
|
Row(
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.padding(horizontal = 16.dp, vertical = 8.dp),
|
||||||
|
) {
|
||||||
|
Text(
|
||||||
|
text = "Favorites",
|
||||||
|
color = MaterialTheme.colorScheme.onBackground,
|
||||||
|
fontSize = 15.sp,
|
||||||
|
fontWeight = FontWeight.SemiBold,
|
||||||
|
modifier = Modifier.weight(1f),
|
||||||
|
)
|
||||||
|
TextButton(
|
||||||
|
onClick = onPinCurrent,
|
||||||
|
enabled = !currentAlreadyPinned,
|
||||||
|
) {
|
||||||
|
Icon(Icons.Filled.PushPin, null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(16.dp))
|
||||||
|
Spacer(Modifier.width(6.dp))
|
||||||
|
Text(
|
||||||
|
text = "Pin current folder",
|
||||||
|
color = MaterialTheme.colorScheme.primary,
|
||||||
|
fontSize = 13.sp,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (favorites.isEmpty()) {
|
||||||
|
item {
|
||||||
|
Box(
|
||||||
|
modifier = Modifier.fillParentMaxSize(),
|
||||||
|
contentAlignment = Alignment.Center,
|
||||||
|
) {
|
||||||
|
Text(
|
||||||
|
text = "No favorites yet - pin a folder with its ⋮ menu to jump back here fast.",
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
fontSize = 13.sp,
|
||||||
|
modifier = Modifier.padding(horizontal = 32.dp),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
items(favorites, key = { it.absolutePath }) { file ->
|
||||||
|
val loc = remember(file.absolutePath) { describeLocation(file) }
|
||||||
|
FavoriteCard(
|
||||||
|
file = file,
|
||||||
|
loc = loc,
|
||||||
|
onJump = { onJump(file) },
|
||||||
|
onUnpin = { onUnpin(file) },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// A single favourite - matches the FileItemRow card style (surfaceContainer + outline +
|
||||||
|
// RoundedCornerShape(10.dp)). Shows the folder name, a coloured drive badge + origin text,
|
||||||
|
// and the full display path; tapping jumps into it, the filled star unpins.
|
||||||
|
@Composable
|
||||||
|
private fun FavoriteCard(
|
||||||
|
file: File,
|
||||||
|
loc: FavLocation,
|
||||||
|
onJump: () -> Unit,
|
||||||
|
onUnpin: () -> Unit,
|
||||||
|
) {
|
||||||
|
val (badgeBg, badgeFg) = badgeColors(loc)
|
||||||
|
Card(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.padding(horizontal = 12.dp, vertical = 3.dp)
|
||||||
|
.clickable(onClick = onJump),
|
||||||
|
shape = RoundedCornerShape(10.dp),
|
||||||
|
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceContainer),
|
||||||
|
border = BorderStroke(1.dp, MaterialTheme.colorScheme.outline),
|
||||||
|
) {
|
||||||
|
Row(
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
modifier = Modifier.padding(horizontal = 12.dp, vertical = 8.dp),
|
||||||
|
) {
|
||||||
|
Icon(
|
||||||
|
imageVector = Icons.Filled.Folder,
|
||||||
|
contentDescription = null,
|
||||||
|
tint = MaterialTheme.colorScheme.primary,
|
||||||
|
modifier = Modifier.size(36.dp),
|
||||||
|
)
|
||||||
|
Spacer(Modifier.width(10.dp))
|
||||||
|
Column(modifier = Modifier.weight(1f)) {
|
||||||
|
Text(
|
||||||
|
text = file.name,
|
||||||
|
color = MaterialTheme.colorScheme.onBackground,
|
||||||
|
fontSize = 14.sp,
|
||||||
|
fontWeight = FontWeight.SemiBold,
|
||||||
|
maxLines = 1,
|
||||||
|
overflow = TextOverflow.Ellipsis,
|
||||||
|
)
|
||||||
|
Spacer(Modifier.height(2.dp))
|
||||||
|
// Origin line: coloured drive badge + source description.
|
||||||
|
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||||
|
Text(
|
||||||
|
text = loc.driveLabel,
|
||||||
|
color = badgeFg,
|
||||||
|
fontSize = 11.sp,
|
||||||
|
fontWeight = FontWeight.Bold,
|
||||||
|
modifier = Modifier
|
||||||
|
.clip(RoundedCornerShape(4.dp))
|
||||||
|
.background(badgeBg)
|
||||||
|
.padding(horizontal = 6.dp, vertical = 2.dp),
|
||||||
|
)
|
||||||
|
Spacer(Modifier.width(6.dp))
|
||||||
|
Text(
|
||||||
|
text = when (loc.storage) {
|
||||||
|
FavStorage.INTERNAL -> "Internal storage"
|
||||||
|
FavStorage.SD -> "SD card"
|
||||||
|
FavStorage.OTHER -> "Storage"
|
||||||
|
},
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
fontSize = 12.sp,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
Spacer(Modifier.height(2.dp))
|
||||||
|
Text(
|
||||||
|
text = loc.displayPath,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
fontSize = 12.sp,
|
||||||
|
fontFamily = FontFamily.Monospace,
|
||||||
|
maxLines = 1,
|
||||||
|
overflow = TextOverflow.Ellipsis,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
IconButton(onClick = onUnpin) {
|
||||||
|
Icon(
|
||||||
|
Icons.Filled.Star,
|
||||||
|
contentDescription = "Remove from favorites",
|
||||||
|
tint = MaterialTheme.colorScheme.primary,
|
||||||
|
modifier = Modifier.size(22.dp),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* One entry in the File Manager's grid view: a big thumbnail with the name under it.
|
||||||
|
*
|
||||||
|
* Deliberately drops size and date - at this width they truncate to noise. The grid is for
|
||||||
|
* recognising things by sight (screenshots, covers, game folders); the list stays the view for
|
||||||
|
* reading details.
|
||||||
|
*/
|
||||||
|
@OptIn(ExperimentalFoundationApi::class)
|
||||||
|
@Composable
|
||||||
|
internal fun FileGridTile(
|
||||||
|
file: File,
|
||||||
|
selectionMode: Boolean,
|
||||||
|
selected: Boolean,
|
||||||
|
onLongPress: () -> Unit,
|
||||||
|
onToggleSelect: () -> Unit,
|
||||||
|
onTap: () -> Unit,
|
||||||
|
onMenu: () -> Unit,
|
||||||
|
menuExpanded: Boolean = false,
|
||||||
|
onDismissMenu: () -> Unit = {},
|
||||||
|
isFavorite: Boolean = false,
|
||||||
|
onSelect: () -> Unit = {},
|
||||||
|
onRename: () -> Unit = {},
|
||||||
|
onCopy: () -> Unit = {},
|
||||||
|
onCut: () -> Unit = {},
|
||||||
|
onDelete: () -> Unit = {},
|
||||||
|
onToggleFavorite: () -> Unit = {},
|
||||||
|
onProperties: () -> Unit = {},
|
||||||
|
) {
|
||||||
|
val isDir = file.isDirectory
|
||||||
|
val isImage = !isDir && file.extension.lowercase() in IMAGE_THUMB_EXTS
|
||||||
|
var exeIcon by remember(file.absolutePath) { mutableStateOf<ImageBitmap?>(null) }
|
||||||
|
if (!isDir && file.name.lowercase().endsWith(".exe")) {
|
||||||
|
LaunchedEffect(file.absolutePath) {
|
||||||
|
val bmp = withContext(Dispatchers.IO) { PeIconExtractor.extract(file) }
|
||||||
|
if (bmp != null) exeIcon = bmp.asImageBitmap()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// The tile has no ⋮ button - long-press opens this menu, anchored to the Box around the Card.
|
||||||
|
Box {
|
||||||
|
Card(
|
||||||
|
modifier = Modifier
|
||||||
|
.padding(4.dp)
|
||||||
|
.combinedClickable(
|
||||||
|
onClick = { if (selectionMode) onToggleSelect() else onTap() },
|
||||||
|
onLongClick = onLongPress,
|
||||||
|
),
|
||||||
|
shape = RoundedCornerShape(10.dp),
|
||||||
|
colors = CardDefaults.cardColors(
|
||||||
|
containerColor = if (selected) MaterialTheme.colorScheme.primary.copy(alpha = 0.18f)
|
||||||
|
else MaterialTheme.colorScheme.surfaceContainer,
|
||||||
|
),
|
||||||
|
border = BorderStroke(
|
||||||
|
1.dp,
|
||||||
|
if (selected) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.outline,
|
||||||
|
),
|
||||||
|
) {
|
||||||
|
Column(
|
||||||
|
horizontalAlignment = Alignment.CenterHorizontally,
|
||||||
|
modifier = Modifier.fillMaxWidth().padding(8.dp),
|
||||||
|
) {
|
||||||
|
Box(modifier = Modifier.size(56.dp), contentAlignment = Alignment.Center) {
|
||||||
|
when {
|
||||||
|
exeIcon != null -> Image(bitmap = exeIcon!!, contentDescription = null, modifier = Modifier.size(48.dp))
|
||||||
|
isDir -> Icon(
|
||||||
|
Icons.Filled.Folder, null,
|
||||||
|
tint = MaterialTheme.colorScheme.primary,
|
||||||
|
modifier = Modifier.size(48.dp),
|
||||||
|
)
|
||||||
|
isImage -> AsyncImage(
|
||||||
|
model = file,
|
||||||
|
contentDescription = null,
|
||||||
|
contentScale = ContentScale.Crop,
|
||||||
|
placeholder = rememberVectorPainter(Icons.Filled.InsertDriveFile),
|
||||||
|
error = rememberVectorPainter(Icons.Filled.InsertDriveFile),
|
||||||
|
modifier = Modifier.size(56.dp).clip(RoundedCornerShape(6.dp)),
|
||||||
|
)
|
||||||
|
else -> Icon(
|
||||||
|
Icons.Filled.InsertDriveFile, null,
|
||||||
|
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
modifier = Modifier.size(44.dp),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
if (selectionMode) {
|
||||||
|
androidx.compose.material3.Checkbox(
|
||||||
|
checked = selected,
|
||||||
|
onCheckedChange = { onToggleSelect() },
|
||||||
|
modifier = Modifier.align(Alignment.TopStart),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Spacer(Modifier.height(4.dp))
|
||||||
|
// Always reserve two lines (issue #475): a one-line name used to make its card shorter than
|
||||||
|
// its neighbours, so grid rows had ragged heights. Fixed min/max keeps every tile the same size.
|
||||||
|
Text(
|
||||||
|
file.name,
|
||||||
|
color = MaterialTheme.colorScheme.onSurface,
|
||||||
|
fontSize = 12.sp,
|
||||||
|
minLines = 2,
|
||||||
|
maxLines = 2,
|
||||||
|
textAlign = androidx.compose.ui.text.style.TextAlign.Center,
|
||||||
|
overflow = TextOverflow.Ellipsis,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
DropdownMenu(
|
||||||
|
expanded = menuExpanded,
|
||||||
|
onDismissRequest = onDismissMenu,
|
||||||
|
modifier = Modifier.outlinedMenuCard(),
|
||||||
|
) {
|
||||||
|
FileContextMenuItems(
|
||||||
|
file = file,
|
||||||
|
isFavorite = isFavorite,
|
||||||
|
onSelect = onSelect,
|
||||||
|
onRename = onRename,
|
||||||
|
onCopy = onCopy,
|
||||||
|
onCut = onCut,
|
||||||
|
onDelete = onDelete,
|
||||||
|
onToggleFavorite = onToggleFavorite,
|
||||||
|
onProperties = onProperties,
|
||||||
|
onDismissMenu = onDismissMenu,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,101 @@
|
|||||||
|
package com.droiddeck.launcher.files
|
||||||
|
|
||||||
|
import androidx.compose.foundation.Image
|
||||||
|
import androidx.compose.foundation.layout.size
|
||||||
|
import androidx.compose.material.icons.filled.Folder
|
||||||
|
import androidx.compose.material.icons.filled.Storage
|
||||||
|
import androidx.compose.material.icons.filled.Image
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.setValue
|
||||||
|
import androidx.compose.ui.text.style.TextOverflow
|
||||||
|
import java.io.File
|
||||||
|
|
||||||
|
// The File Manager's non-UI helpers: sorting, paths, conflict choices and favourite locations.
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Bannerlator's File Manager (ui/screens/FileManagerScreen.kt), carried over whole: the same
|
||||||
|
* browsing, grid and list, sorting, search, multi-select, copy/cut/paste with conflicts and
|
||||||
|
* progress, rename, delete, new folder, properties, favourites and the locations rail, and the
|
||||||
|
* same pick modes. What this app has no use for is not here: running a file in a Wine container,
|
||||||
|
* adding it to a container's shortcuts, the Drive C: / Drive Z: locations and the archive
|
||||||
|
* unpacker that installs into a prefix. Everything else is line for line the same so a fix in
|
||||||
|
* either app carries to the other.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* What to do when a pasted item already exists at the destination.
|
||||||
|
*
|
||||||
|
* OVERWRITE and MERGE resolve to the same call - `copyWithProgress` recurses into an existing
|
||||||
|
* directory and truncates existing files - but they mean different things to the user, so both are
|
||||||
|
* offered and the wording is chosen per item type (files overwrite, folders merge).
|
||||||
|
*/
|
||||||
|
enum class ConflictChoice { OVERWRITE, MERGE, KEEP_BOTH, SKIP }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Shortens a path from the LEFT, keeping whole segments.
|
||||||
|
*
|
||||||
|
* Compose's TextOverflow can only ellipsise the tail, which for a path throws away the part that
|
||||||
|
* matters - `/storage/emulated/0/Games/Racing/Dir…` tells you nothing about where you are.
|
||||||
|
*/
|
||||||
|
internal fun elidePathStart(path: String, max: Int): String {
|
||||||
|
if (path.length <= max) return path
|
||||||
|
val parts = path.split('/').filter { it.isNotEmpty() }
|
||||||
|
val out = StringBuilder()
|
||||||
|
for (part in parts.asReversed()) {
|
||||||
|
if (out.length + part.length + 1 > max - 2) break
|
||||||
|
out.insert(0, "/$part")
|
||||||
|
}
|
||||||
|
return if (out.isEmpty()) "…" + path.takeLast(max - 1) else "…$out"
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Folder-first ordering stays fixed across both sort directions. */
|
||||||
|
internal fun comparatorFor(sortBy: String, desc: Boolean): Comparator<File> {
|
||||||
|
val inner: Comparator<File> = when (sortBy) {
|
||||||
|
"date" -> compareBy { it.lastModified() }
|
||||||
|
// Directory length() is meaningless, so folders sort by name within the size ordering
|
||||||
|
// instead of pretending to have one.
|
||||||
|
"size" -> compareBy { if (it.isDirectory) -1L else it.length() }
|
||||||
|
else -> compareBy { it.name.lowercase() }
|
||||||
|
}
|
||||||
|
val directed = if (desc) inner.reversed() else inner
|
||||||
|
return compareBy<File> { if (it.isDirectory) 0 else 1 }.then(directed)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Image extensions that get a real thumbnail (via Coil) instead of the generic file icon.
|
||||||
|
internal val IMAGE_THUMB_EXTS = setOf("jpg", "jpeg", "png", "webp", "bmp", "gif")
|
||||||
|
|
||||||
|
// True when [child] is [ancestor] itself or lives anywhere inside it.
|
||||||
|
internal fun isWithin(child: File, ancestor: File): Boolean {
|
||||||
|
val c = runCatching { child.canonicalPath }.getOrDefault(child.absolutePath)
|
||||||
|
val a = runCatching { ancestor.canonicalPath }.getOrDefault(ancestor.absolutePath)
|
||||||
|
return c == a || c.startsWith(a + File.separator)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Favorites: origin resolution ──
|
||||||
|
|
||||||
|
enum class FavStorage { INTERNAL, SD, OTHER }
|
||||||
|
|
||||||
|
data class FavLocation(
|
||||||
|
val storage: FavStorage,
|
||||||
|
val driveLabel: String, // "Internal", "SD card", or "Storage"
|
||||||
|
val displayPath: String // the unix absolute path
|
||||||
|
)
|
||||||
|
|
||||||
|
// Resolve where [file] lives (storage source + a friendly label) by prefix-matching its path.
|
||||||
|
fun describeLocation(file: File): FavLocation {
|
||||||
|
val abs = file.absolutePath
|
||||||
|
|
||||||
|
val internal = "/storage/emulated/0"
|
||||||
|
if (abs == internal || abs.startsWith("$internal/")) {
|
||||||
|
return FavLocation(FavStorage.INTERNAL, "Internal", abs)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (abs.startsWith("/storage/")) {
|
||||||
|
val name = abs.removePrefix("/storage/").substringBefore('/')
|
||||||
|
if (name.isNotEmpty() && name != "emulated" && name != "self") {
|
||||||
|
return FavLocation(FavStorage.SD, "SD card", abs)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return FavLocation(FavStorage.OTHER, "Storage", abs)
|
||||||
|
}
|
||||||
@@ -7,12 +7,7 @@ import androidx.compose.foundation.Image
|
|||||||
import android.content.res.Configuration
|
import android.content.res.Configuration
|
||||||
import androidx.compose.foundation.background
|
import androidx.compose.foundation.background
|
||||||
import androidx.compose.foundation.border
|
import androidx.compose.foundation.border
|
||||||
import androidx.compose.foundation.ExperimentalFoundationApi
|
|
||||||
import androidx.compose.foundation.clickable
|
import androidx.compose.foundation.clickable
|
||||||
import androidx.compose.foundation.combinedClickable
|
|
||||||
import androidx.compose.foundation.rememberScrollState
|
|
||||||
import androidx.compose.foundation.verticalScroll
|
|
||||||
import androidx.compose.foundation.layout.Arrangement
|
|
||||||
import androidx.compose.foundation.layout.Box
|
import androidx.compose.foundation.layout.Box
|
||||||
import androidx.compose.foundation.layout.Column
|
import androidx.compose.foundation.layout.Column
|
||||||
import androidx.compose.foundation.layout.PaddingValues
|
import androidx.compose.foundation.layout.PaddingValues
|
||||||
@@ -21,7 +16,6 @@ import androidx.compose.foundation.layout.Spacer
|
|||||||
import androidx.compose.foundation.layout.fillMaxSize
|
import androidx.compose.foundation.layout.fillMaxSize
|
||||||
import androidx.compose.foundation.layout.fillMaxWidth
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
import androidx.compose.foundation.layout.height
|
import androidx.compose.foundation.layout.height
|
||||||
import androidx.compose.foundation.layout.heightIn
|
|
||||||
import androidx.compose.foundation.layout.padding
|
import androidx.compose.foundation.layout.padding
|
||||||
import androidx.compose.foundation.layout.size
|
import androidx.compose.foundation.layout.size
|
||||||
import androidx.compose.foundation.layout.width
|
import androidx.compose.foundation.layout.width
|
||||||
@@ -33,41 +27,25 @@ import androidx.compose.foundation.lazy.grid.items
|
|||||||
import androidx.compose.foundation.lazy.rememberLazyListState
|
import androidx.compose.foundation.lazy.rememberLazyListState
|
||||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||||
import androidx.compose.material.icons.Icons
|
import androidx.compose.material.icons.Icons
|
||||||
import androidx.compose.material.icons.filled.Add
|
|
||||||
import androidx.compose.material.icons.filled.ArrowBack
|
import androidx.compose.material.icons.filled.ArrowBack
|
||||||
import androidx.compose.material.icons.filled.Bolt
|
|
||||||
import androidx.compose.material.icons.filled.Checklist
|
|
||||||
import androidx.compose.material.icons.filled.ContentPaste
|
import androidx.compose.material.icons.filled.ContentPaste
|
||||||
import androidx.compose.material.icons.filled.CreateNewFolder
|
import androidx.compose.material.icons.filled.CreateNewFolder
|
||||||
import androidx.compose.material.icons.filled.Delete
|
import androidx.compose.material.icons.filled.Delete
|
||||||
import androidx.compose.material.icons.filled.FileCopy
|
|
||||||
import androidx.compose.material.icons.filled.Folder
|
import androidx.compose.material.icons.filled.Folder
|
||||||
import androidx.compose.material.icons.filled.GridView
|
import androidx.compose.material.icons.filled.GridView
|
||||||
import androidx.compose.material.icons.filled.Info
|
|
||||||
import androidx.compose.material.icons.filled.InsertDriveFile
|
|
||||||
import androidx.compose.material.icons.filled.MoreVert
|
|
||||||
import androidx.compose.material.icons.filled.ContentCut
|
|
||||||
import androidx.compose.material.icons.filled.Edit
|
|
||||||
import androidx.compose.material.icons.filled.PlayArrow
|
|
||||||
import androidx.compose.material.icons.filled.SdStorage
|
import androidx.compose.material.icons.filled.SdStorage
|
||||||
import androidx.compose.material.icons.filled.Search
|
import androidx.compose.material.icons.filled.Search
|
||||||
import androidx.compose.material.icons.filled.Sort
|
import androidx.compose.material.icons.filled.Sort
|
||||||
import androidx.compose.material.icons.filled.Star
|
import androidx.compose.material.icons.filled.Star
|
||||||
import androidx.compose.material.icons.filled.Unarchive
|
|
||||||
import androidx.compose.material.icons.filled.ViewList
|
import androidx.compose.material.icons.filled.ViewList
|
||||||
import androidx.compose.material.icons.filled.StarBorder
|
import androidx.compose.material.icons.filled.StarBorder
|
||||||
import androidx.compose.material.icons.filled.PushPin
|
|
||||||
import androidx.compose.material.icons.filled.Storage
|
import androidx.compose.material.icons.filled.Storage
|
||||||
import androidx.compose.material.icons.filled.Smartphone
|
import androidx.compose.material.icons.filled.Smartphone
|
||||||
import androidx.compose.material.icons.filled.Download
|
import androidx.compose.material.icons.filled.Download
|
||||||
import androidx.compose.material.icons.filled.Description
|
import androidx.compose.material.icons.filled.Description
|
||||||
import androidx.compose.material.icons.filled.Image
|
import androidx.compose.material.icons.filled.Image
|
||||||
import androidx.compose.material.icons.filled.SportsEsports
|
import androidx.compose.material.icons.filled.SportsEsports
|
||||||
import androidx.compose.material3.AlertDialog
|
|
||||||
import androidx.compose.material3.Button
|
import androidx.compose.material3.Button
|
||||||
import androidx.compose.material3.ButtonDefaults
|
|
||||||
import androidx.compose.material3.Card
|
|
||||||
import androidx.compose.material3.CardDefaults
|
|
||||||
import androidx.compose.material3.DropdownMenu
|
import androidx.compose.material3.DropdownMenu
|
||||||
import androidx.compose.material3.DropdownMenuItem
|
import androidx.compose.material3.DropdownMenuItem
|
||||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||||
@@ -95,217 +73,22 @@ import androidx.compose.runtime.setValue
|
|||||||
import androidx.compose.ui.Alignment
|
import androidx.compose.ui.Alignment
|
||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
import androidx.compose.ui.draw.clip
|
import androidx.compose.ui.draw.clip
|
||||||
import androidx.compose.ui.graphics.Color
|
|
||||||
import androidx.compose.ui.graphics.ImageBitmap
|
|
||||||
import androidx.compose.ui.graphics.asImageBitmap
|
|
||||||
import androidx.compose.ui.input.nestedscroll.nestedScroll
|
import androidx.compose.ui.input.nestedscroll.nestedScroll
|
||||||
import androidx.compose.ui.layout.ContentScale
|
|
||||||
import androidx.compose.ui.graphics.vector.rememberVectorPainter
|
|
||||||
import androidx.compose.ui.platform.LocalConfiguration
|
import androidx.compose.ui.platform.LocalConfiguration
|
||||||
import androidx.compose.ui.platform.LocalContext
|
import androidx.compose.ui.platform.LocalContext
|
||||||
import androidx.compose.ui.platform.LocalLifecycleOwner
|
import androidx.compose.ui.platform.LocalLifecycleOwner
|
||||||
import androidx.compose.ui.res.painterResource
|
|
||||||
import androidx.lifecycle.Lifecycle
|
import androidx.lifecycle.Lifecycle
|
||||||
import androidx.lifecycle.LifecycleEventObserver
|
import androidx.lifecycle.LifecycleEventObserver
|
||||||
import coil.compose.AsyncImage
|
|
||||||
import androidx.compose.ui.text.font.FontFamily
|
|
||||||
import androidx.compose.ui.text.font.FontWeight
|
import androidx.compose.ui.text.font.FontWeight
|
||||||
import androidx.compose.ui.text.style.TextOverflow
|
import androidx.compose.ui.text.style.TextOverflow
|
||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
import androidx.compose.ui.unit.sp
|
import androidx.compose.ui.unit.sp
|
||||||
import com.droiddeck.launcher.R
|
|
||||||
import com.droiddeck.launcher.session.SessionPrefs
|
import com.droiddeck.launcher.session.SessionPrefs
|
||||||
import kotlinx.coroutines.Dispatchers
|
import kotlinx.coroutines.Dispatchers
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
import kotlinx.coroutines.withContext
|
import kotlinx.coroutines.withContext
|
||||||
import java.io.File
|
import java.io.File
|
||||||
import java.text.SimpleDateFormat
|
|
||||||
import java.util.Date
|
import java.util.Date
|
||||||
import java.util.Locale
|
|
||||||
|
|
||||||
/*
|
|
||||||
* Bannerlator's File Manager (ui/screens/FileManagerScreen.kt), carried over whole: the same
|
|
||||||
* browsing, grid and list, sorting, search, multi-select, copy/cut/paste with conflicts and
|
|
||||||
* progress, rename, delete, new folder, properties, favourites and the locations rail, and the
|
|
||||||
* same pick modes. What this app has no use for is not here: running a file in a Wine container,
|
|
||||||
* adding it to a container's shortcuts, the Drive C: / Drive Z: locations and the archive
|
|
||||||
* unpacker that installs into a prefix. Everything else is line for line the same so a fix in
|
|
||||||
* either app carries to the other.
|
|
||||||
*/
|
|
||||||
|
|
||||||
/**
|
|
||||||
* What to do when a pasted item already exists at the destination.
|
|
||||||
*
|
|
||||||
* OVERWRITE and MERGE resolve to the same call - `copyWithProgress` recurses into an existing
|
|
||||||
* directory and truncates existing files - but they mean different things to the user, so both are
|
|
||||||
* offered and the wording is chosen per item type (files overwrite, folders merge).
|
|
||||||
*/
|
|
||||||
enum class ConflictChoice { OVERWRITE, MERGE, KEEP_BOTH, SKIP }
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Shortens a path from the LEFT, keeping whole segments.
|
|
||||||
*
|
|
||||||
* Compose's TextOverflow can only ellipsise the tail, which for a path throws away the part that
|
|
||||||
* matters - `/storage/emulated/0/Games/Racing/Dir…` tells you nothing about where you are.
|
|
||||||
*/
|
|
||||||
private fun elidePathStart(path: String, max: Int): String {
|
|
||||||
if (path.length <= max) return path
|
|
||||||
val parts = path.split('/').filter { it.isNotEmpty() }
|
|
||||||
val out = StringBuilder()
|
|
||||||
for (part in parts.asReversed()) {
|
|
||||||
if (out.length + part.length + 1 > max - 2) break
|
|
||||||
out.insert(0, "/$part")
|
|
||||||
}
|
|
||||||
return if (out.isEmpty()) "…" + path.takeLast(max - 1) else "…$out"
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Folder-first ordering stays fixed across both sort directions. */
|
|
||||||
private fun comparatorFor(sortBy: String, desc: Boolean): Comparator<File> {
|
|
||||||
val inner: Comparator<File> = when (sortBy) {
|
|
||||||
"date" -> compareBy { it.lastModified() }
|
|
||||||
// Directory length() is meaningless, so folders sort by name within the size ordering
|
|
||||||
// instead of pretending to have one.
|
|
||||||
"size" -> compareBy { if (it.isDirectory) -1L else it.length() }
|
|
||||||
else -> compareBy { it.name.lowercase() }
|
|
||||||
}
|
|
||||||
val directed = if (desc) inner.reversed() else inner
|
|
||||||
return compareBy<File> { if (it.isDirectory) 0 else 1 }.then(directed)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Image extensions that get a real thumbnail (via Coil) instead of the generic file icon.
|
|
||||||
private val IMAGE_THUMB_EXTS = setOf("jpg", "jpeg", "png", "webp", "bmp", "gif")
|
|
||||||
|
|
||||||
// True when [child] is [ancestor] itself or lives anywhere inside it.
|
|
||||||
private fun isWithin(child: File, ancestor: File): Boolean {
|
|
||||||
val c = runCatching { child.canonicalPath }.getOrDefault(child.absolutePath)
|
|
||||||
val a = runCatching { ancestor.canonicalPath }.getOrDefault(ancestor.absolutePath)
|
|
||||||
return c == a || c.startsWith(a + File.separator)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── DOS file attributes (Read-only / Hidden) ──
|
|
||||||
// The in-container file manager (wfm.exe) exposes these in its Properties dialog; this mirrors the
|
|
||||||
// same two toggles for files browsed from the app side. No root - we only touch permission bits the
|
|
||||||
// app owns (container files) and the Wine DOS-attribute xattr.
|
|
||||||
|
|
||||||
// FILE_ATTRIBUTE_HIDDEN, as Wine encodes it in the user.DOSATTRIB extended attribute.
|
|
||||||
private const val FILE_ATTRIBUTE_HIDDEN = 0x2
|
|
||||||
private const val DOSATTRIB_XATTR = "user.DOSATTRIB"
|
|
||||||
|
|
||||||
// Snapshot of a file's two toggleable attributes. hiddenSupported is false when the underlying
|
|
||||||
// filesystem can't store the DOSATTRIB xattr (the FUSE /storage volumes) - the Hidden toggle is then
|
|
||||||
// disabled while Read-only keeps working.
|
|
||||||
private data class FileAttrState(
|
|
||||||
val readOnly: Boolean,
|
|
||||||
val hidden: Boolean,
|
|
||||||
val hiddenSupported: Boolean,
|
|
||||||
)
|
|
||||||
|
|
||||||
// Wine (and Samba) store user.DOSATTRIB as an ASCII hex string ("0x22"), sometimes with trailing
|
|
||||||
// Samba fields after a separator. We only need the leading DOS-attribute hex, so read from the "0x"
|
|
||||||
// prefix and stop at the first non-hex character.
|
|
||||||
private fun parseDosAttrib(raw: ByteArray): Int {
|
|
||||||
val s = String(raw, Charsets.US_ASCII).trim()
|
|
||||||
val hex = if (s.startsWith("0x") || s.startsWith("0X")) s.substring(2) else s
|
|
||||||
val digits = hex.takeWhile { it in '0'..'9' || it in 'a'..'f' || it in 'A'..'F' }
|
|
||||||
return digits.toIntOrNull(16) ?: 0
|
|
||||||
}
|
|
||||||
|
|
||||||
// Read the current read-only + Wine-hidden state. Never throws: an xattr-unsupported filesystem
|
|
||||||
// comes back hiddenSupported=false (Hidden toggle disabled), Read-only always resolves.
|
|
||||||
private fun readFileAttrs(file: File): FileAttrState {
|
|
||||||
val path = file.absolutePath
|
|
||||||
// Read-only reflects the OWNER write bit - that's what Wine maps to FILE_ATTRIBUTE_READONLY.
|
|
||||||
val readOnly = runCatching {
|
|
||||||
(android.system.Os.stat(path).st_mode and android.system.OsConstants.S_IWUSR) == 0
|
|
||||||
}.getOrDefault(!file.canWrite())
|
|
||||||
|
|
||||||
var hidden = false
|
|
||||||
var supported = true
|
|
||||||
try {
|
|
||||||
hidden = (parseDosAttrib(android.system.Os.getxattr(path, DOSATTRIB_XATTR)) and FILE_ATTRIBUTE_HIDDEN) != 0
|
|
||||||
} catch (e: android.system.ErrnoException) {
|
|
||||||
// ENODATA: xattr namespace works, the attribute just isn't set yet -> still toggleable.
|
|
||||||
// ENOTSUP/EOPNOTSUPP/anything else: the fs can't store it -> disable the Hidden toggle.
|
|
||||||
supported = e.errno == android.system.OsConstants.ENODATA
|
|
||||||
} catch (e: Exception) {
|
|
||||||
supported = false
|
|
||||||
}
|
|
||||||
return FileAttrState(readOnly, hidden, supported)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Toggle read-only by flipping the write bits, preserving every other permission bit. Setting
|
|
||||||
// read-only clears owner/group/other write (so Wine sees FILE_ATTRIBUTE_READONLY regardless of which
|
|
||||||
// write bit it checks); clearing it restores owner write. Falls back to File.setWritable if chmod is
|
|
||||||
// somehow refused. Returns true on success.
|
|
||||||
private fun setReadOnly(file: File, readOnly: Boolean): Boolean = runCatching {
|
|
||||||
val path = file.absolutePath
|
|
||||||
val mode = android.system.Os.stat(path).st_mode
|
|
||||||
val writeBits = android.system.OsConstants.S_IWUSR or
|
|
||||||
android.system.OsConstants.S_IWGRP or android.system.OsConstants.S_IWOTH
|
|
||||||
val newMode = if (readOnly) mode and writeBits.inv()
|
|
||||||
else mode or android.system.OsConstants.S_IWUSR
|
|
||||||
android.system.Os.chmod(path, newMode)
|
|
||||||
true
|
|
||||||
}.getOrElse { file.setWritable(!readOnly, true) }
|
|
||||||
|
|
||||||
// Flip Wine's DOS hidden bit in user.DOSATTRIB, preserving the other DOS-attribute bits
|
|
||||||
// (archive/system/read-only) already encoded there, and synthesizing a minimal value when absent.
|
|
||||||
// Writes Wine's own "0x%x" format, which Wine reads back natively. Returns false when the fs can't
|
|
||||||
// store the xattr, so the caller can disable just the Hidden toggle.
|
|
||||||
private fun setHidden(file: File, hidden: Boolean): Boolean = try {
|
|
||||||
val path = file.absolutePath
|
|
||||||
var attr = try {
|
|
||||||
parseDosAttrib(android.system.Os.getxattr(path, DOSATTRIB_XATTR))
|
|
||||||
} catch (e: android.system.ErrnoException) {
|
|
||||||
if (e.errno == android.system.OsConstants.ENODATA) 0 else throw e
|
|
||||||
}
|
|
||||||
attr = if (hidden) attr or FILE_ATTRIBUTE_HIDDEN else attr and FILE_ATTRIBUTE_HIDDEN.inv()
|
|
||||||
val value = "0x%x".format(attr).toByteArray(Charsets.US_ASCII)
|
|
||||||
android.system.Os.setxattr(path, DOSATTRIB_XATTR, value, 0)
|
|
||||||
true
|
|
||||||
} catch (e: Exception) {
|
|
||||||
false
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── Favorites: origin resolution ──
|
|
||||||
|
|
||||||
enum class FavStorage { INTERNAL, SD, OTHER }
|
|
||||||
|
|
||||||
data class FavLocation(
|
|
||||||
val storage: FavStorage,
|
|
||||||
val driveLabel: String, // "Internal", "SD card", or "Storage"
|
|
||||||
val displayPath: String // the unix absolute path
|
|
||||||
)
|
|
||||||
|
|
||||||
// Resolve where [file] lives (storage source + a friendly label) by prefix-matching its path.
|
|
||||||
fun describeLocation(file: File): FavLocation {
|
|
||||||
val abs = file.absolutePath
|
|
||||||
|
|
||||||
val internal = "/storage/emulated/0"
|
|
||||||
if (abs == internal || abs.startsWith("$internal/")) {
|
|
||||||
return FavLocation(FavStorage.INTERNAL, "Internal", abs)
|
|
||||||
}
|
|
||||||
|
|
||||||
if (abs.startsWith("/storage/")) {
|
|
||||||
val name = abs.removePrefix("/storage/").substringBefore('/')
|
|
||||||
if (name.isNotEmpty() && name != "emulated" && name != "self") {
|
|
||||||
return FavLocation(FavStorage.SD, "SD card", abs)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return FavLocation(FavStorage.OTHER, "Storage", abs)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Semantic identity colours for the favourite-card drive badge. Intentionally NOT theme
|
|
||||||
// accent colours - they identify the storage source at a glance. Returns (background, foreground).
|
|
||||||
private fun badgeColors(loc: FavLocation): Pair<Color, Color> {
|
|
||||||
val white = Color(0xFFFFFFFF)
|
|
||||||
return when {
|
|
||||||
loc.storage == FavStorage.INTERNAL -> Color(0xFF2E5FB0) to white // blue
|
|
||||||
loc.storage == FavStorage.SD -> Color(0xFF2E7D32) to white // green
|
|
||||||
else -> Color(0xFF555555) to white // grey
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@OptIn(ExperimentalMaterial3Api::class)
|
@OptIn(ExperimentalMaterial3Api::class)
|
||||||
@Composable
|
@Composable
|
||||||
@@ -1414,675 +1197,3 @@ fun FileManagerScreen(
|
|||||||
} // end rail + content Row
|
} // end rail + content Row
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// The context-menu item list shared by the list rows (FileItemRow) and the grid tiles
|
|
||||||
// (FileGridTile), so both open the identical menu. Gating (isDir/canRun/isInno/looksLikeArchive) is
|
|
||||||
// recomputed from [file] here - one source of truth for what each item shows. Every item dismisses
|
|
||||||
// the menu first, then runs its action.
|
|
||||||
@Composable
|
|
||||||
private fun FileContextMenuItems(
|
|
||||||
file: File,
|
|
||||||
isFavorite: Boolean,
|
|
||||||
onSelect: () -> Unit,
|
|
||||||
onRename: () -> Unit,
|
|
||||||
onCopy: () -> Unit,
|
|
||||||
onCut: () -> Unit,
|
|
||||||
onDelete: () -> Unit,
|
|
||||||
onToggleFavorite: () -> Unit,
|
|
||||||
onProperties: () -> Unit,
|
|
||||||
onDismissMenu: () -> Unit,
|
|
||||||
) {
|
|
||||||
val isDir = file.isDirectory
|
|
||||||
DropdownMenuItem(
|
|
||||||
text = { Text("Select") },
|
|
||||||
leadingIcon = { Icon(Icons.Filled.Checklist, null, tint = MaterialTheme.colorScheme.primary) },
|
|
||||||
onClick = { onDismissMenu(); onSelect() },
|
|
||||||
)
|
|
||||||
MenuItemDivider()
|
|
||||||
// Properties: basic info + Read-only / Hidden toggles, for ANY file or folder (handy for config
|
|
||||||
// files like .txt/.cfg/.ini). Kept near the top since it's a common reason to open this menu.
|
|
||||||
DropdownMenuItem(
|
|
||||||
text = { Text("Properties") },
|
|
||||||
leadingIcon = { Icon(Icons.Filled.Info, null, tint = MaterialTheme.colorScheme.primary) },
|
|
||||||
onClick = { onDismissMenu(); onProperties() },
|
|
||||||
)
|
|
||||||
MenuItemDivider()
|
|
||||||
// Favorites are directories - only folders get the pin toggle.
|
|
||||||
if (isDir) {
|
|
||||||
DropdownMenuItem(
|
|
||||||
text = { Text(if (isFavorite) "Remove from Favorites" else "Add to Favorites") },
|
|
||||||
leadingIcon = {
|
|
||||||
Icon(
|
|
||||||
if (isFavorite) Icons.Filled.Star else Icons.Filled.StarBorder,
|
|
||||||
null,
|
|
||||||
tint = MaterialTheme.colorScheme.primary,
|
|
||||||
)
|
|
||||||
},
|
|
||||||
onClick = { onToggleFavorite() },
|
|
||||||
)
|
|
||||||
MenuItemDivider()
|
|
||||||
}
|
|
||||||
DropdownMenuItem(
|
|
||||||
text = { Text("Rename") },
|
|
||||||
leadingIcon = { Icon(Icons.Filled.Edit, null, tint = MaterialTheme.colorScheme.primary) },
|
|
||||||
onClick = { onDismissMenu(); onRename() },
|
|
||||||
)
|
|
||||||
MenuItemDivider()
|
|
||||||
DropdownMenuItem(
|
|
||||||
text = { Text("Copy") },
|
|
||||||
leadingIcon = { Icon(Icons.Filled.FileCopy, null, tint = MaterialTheme.colorScheme.primary) },
|
|
||||||
onClick = { onDismissMenu(); onCopy() },
|
|
||||||
)
|
|
||||||
MenuItemDivider()
|
|
||||||
DropdownMenuItem(
|
|
||||||
text = { Text("Cut") },
|
|
||||||
leadingIcon = { Icon(Icons.Filled.ContentCut, null, tint = MaterialTheme.colorScheme.primary) },
|
|
||||||
onClick = { onDismissMenu(); onCut() },
|
|
||||||
)
|
|
||||||
MenuItemDivider()
|
|
||||||
DropdownMenuItem(
|
|
||||||
text = { Text("Delete") },
|
|
||||||
leadingIcon = { Icon(Icons.Filled.Delete, null, tint = MaterialTheme.colorScheme.primary) },
|
|
||||||
onClick = { onDismissMenu(); onDelete() },
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Composable
|
|
||||||
@OptIn(ExperimentalFoundationApi::class)
|
|
||||||
private fun FileItemRow(
|
|
||||||
file: File,
|
|
||||||
showActions: Boolean = true,
|
|
||||||
compact: Boolean = false,
|
|
||||||
selectionMode: Boolean = false,
|
|
||||||
selected: Boolean = false,
|
|
||||||
onLongPress: () -> Unit = {},
|
|
||||||
onToggleSelect: () -> Unit = {},
|
|
||||||
onTap: () -> Unit,
|
|
||||||
onMenu: () -> Unit,
|
|
||||||
menuExpanded: Boolean,
|
|
||||||
onDismissMenu: () -> Unit,
|
|
||||||
onSelect: () -> Unit = {},
|
|
||||||
onCopy: () -> Unit,
|
|
||||||
onCut: () -> Unit,
|
|
||||||
onDelete: () -> Unit,
|
|
||||||
onRename: () -> Unit,
|
|
||||||
isFavorite: Boolean = false,
|
|
||||||
onToggleFavorite: () -> Unit = {},
|
|
||||||
onProperties: () -> Unit = {},
|
|
||||||
) {
|
|
||||||
val dateFormat = remember { SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault()) }
|
|
||||||
val isDir = file.isDirectory
|
|
||||||
val isExe = !isDir && file.name.lowercase().let { it.endsWith(".exe") || it.endsWith(".bat") || it.endsWith(".msi") || it.endsWith(".sh") }
|
|
||||||
// Image files show a real thumbnail instead of the generic file icon (handy when picking a
|
|
||||||
// wallpaper/icon). Coil sizes the decode to the 36dp slot and caches it, so scrolling stays smooth.
|
|
||||||
val isImage = !isDir && file.extension.lowercase() in IMAGE_THUMB_EXTS
|
|
||||||
|
|
||||||
// For real PE executables, try to pull out the embedded application icon (async, off the main thread).
|
|
||||||
var exeIcon by remember(file.absolutePath) { mutableStateOf<ImageBitmap?>(null) }
|
|
||||||
if (!isDir && file.name.lowercase().endsWith(".exe")) {
|
|
||||||
LaunchedEffect(file.absolutePath) {
|
|
||||||
val bmp = withContext(Dispatchers.IO) { PeIconExtractor.extract(file) }
|
|
||||||
if (bmp != null) exeIcon = bmp.asImageBitmap()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Card(
|
|
||||||
modifier = Modifier
|
|
||||||
.fillMaxWidth()
|
|
||||||
.padding(horizontal = 12.dp, vertical = 3.dp)
|
|
||||||
.combinedClickable(
|
|
||||||
// In selection mode a tap toggles instead of opening, so you can rattle through a
|
|
||||||
// folder without long-pressing every single row.
|
|
||||||
onClick = { if (selectionMode) onToggleSelect() else onTap() },
|
|
||||||
onLongClick = onLongPress,
|
|
||||||
),
|
|
||||||
shape = RoundedCornerShape(10.dp),
|
|
||||||
colors = CardDefaults.cardColors(
|
|
||||||
containerColor = if (selected) MaterialTheme.colorScheme.primary.copy(alpha = 0.18f)
|
|
||||||
else MaterialTheme.colorScheme.surfaceContainer,
|
|
||||||
),
|
|
||||||
border = BorderStroke(
|
|
||||||
1.dp,
|
|
||||||
if (selected) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.outline,
|
|
||||||
),
|
|
||||||
) {
|
|
||||||
Row(
|
|
||||||
verticalAlignment = Alignment.CenterVertically,
|
|
||||||
modifier = Modifier.padding(horizontal = 12.dp, vertical = if (compact) 3.dp else 8.dp),
|
|
||||||
) {
|
|
||||||
if (selectionMode) {
|
|
||||||
androidx.compose.material3.Checkbox(checked = selected, onCheckedChange = { onToggleSelect() })
|
|
||||||
Spacer(Modifier.width(4.dp))
|
|
||||||
}
|
|
||||||
when {
|
|
||||||
// Show the executable's own embedded icon when we managed to extract one.
|
|
||||||
exeIcon != null -> Image(
|
|
||||||
bitmap = exeIcon!!,
|
|
||||||
contentDescription = null,
|
|
||||||
modifier = Modifier.size(if (compact) 24.dp else 36.dp),
|
|
||||||
)
|
|
||||||
isExe -> Icon(
|
|
||||||
painter = painterResource(R.drawable.icon_menu_container),
|
|
||||||
contentDescription = null,
|
|
||||||
tint = MaterialTheme.colorScheme.onSurface,
|
|
||||||
modifier = Modifier.size(if (compact) 24.dp else 36.dp),
|
|
||||||
)
|
|
||||||
isDir -> Icon(
|
|
||||||
imageVector = Icons.Filled.Folder,
|
|
||||||
contentDescription = null,
|
|
||||||
tint = MaterialTheme.colorScheme.primary,
|
|
||||||
modifier = Modifier.size(if (compact) 24.dp else 36.dp),
|
|
||||||
)
|
|
||||||
// Real image preview. Falls back to the generic file icon while loading or on decode failure.
|
|
||||||
isImage -> AsyncImage(
|
|
||||||
model = file,
|
|
||||||
contentDescription = null,
|
|
||||||
contentScale = ContentScale.Crop,
|
|
||||||
placeholder = rememberVectorPainter(Icons.Filled.InsertDriveFile),
|
|
||||||
error = rememberVectorPainter(Icons.Filled.InsertDriveFile),
|
|
||||||
modifier = Modifier
|
|
||||||
.size(36.dp)
|
|
||||||
.clip(RoundedCornerShape(6.dp)),
|
|
||||||
)
|
|
||||||
else -> Icon(
|
|
||||||
imageVector = Icons.Filled.InsertDriveFile,
|
|
||||||
contentDescription = null,
|
|
||||||
tint = MaterialTheme.colorScheme.onSurface,
|
|
||||||
modifier = Modifier.size(if (compact) 24.dp else 36.dp),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
Spacer(Modifier.width(10.dp))
|
|
||||||
Column(modifier = Modifier.weight(1f)) {
|
|
||||||
Text(
|
|
||||||
text = file.name,
|
|
||||||
color = MaterialTheme.colorScheme.onBackground,
|
|
||||||
fontSize = 14.sp,
|
|
||||||
fontWeight = FontWeight.Medium,
|
|
||||||
maxLines = 1,
|
|
||||||
overflow = TextOverflow.Ellipsis,
|
|
||||||
)
|
|
||||||
Text(
|
|
||||||
text = buildString {
|
|
||||||
if (!isDir) append(FileOps.formatBytes(file.length())).append(" \u2022 ")
|
|
||||||
append(dateFormat.format(Date(file.lastModified())))
|
|
||||||
},
|
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
|
||||||
fontSize = 12.sp,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
if (showActions) Box {
|
|
||||||
IconButton(onClick = onMenu) {
|
|
||||||
Icon(Icons.Filled.MoreVert, "Actions", tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(20.dp))
|
|
||||||
}
|
|
||||||
DropdownMenu(
|
|
||||||
expanded = menuExpanded,
|
|
||||||
onDismissRequest = onDismissMenu,
|
|
||||||
modifier = Modifier.outlinedMenuCard(),
|
|
||||||
) {
|
|
||||||
FileContextMenuItems(
|
|
||||||
file = file,
|
|
||||||
isFavorite = isFavorite,
|
|
||||||
onSelect = onSelect,
|
|
||||||
onRename = onRename,
|
|
||||||
onCopy = onCopy,
|
|
||||||
onCut = onCut,
|
|
||||||
onDelete = onDelete,
|
|
||||||
onToggleFavorite = onToggleFavorite,
|
|
||||||
onProperties = onProperties,
|
|
||||||
onDismissMenu = onDismissMenu,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Dedicated Favorites list that replaces the file list while the star toggle is on.
|
|
||||||
// Reads the store keyed on [favTick] so it recomposes after any pin/unpin.
|
|
||||||
@Composable
|
|
||||||
private fun FavoritesList(
|
|
||||||
currentDir: File,
|
|
||||||
favTick: Int,
|
|
||||||
onPinCurrent: () -> Unit,
|
|
||||||
onJump: (File) -> Unit,
|
|
||||||
onUnpin: (File) -> Unit,
|
|
||||||
modifier: Modifier = Modifier,
|
|
||||||
) {
|
|
||||||
val context = LocalContext.current
|
|
||||||
val favorites = remember(favTick) {
|
|
||||||
FavoritesStore.list(context).map(::File).filter { it.exists() }
|
|
||||||
}
|
|
||||||
val currentAlreadyPinned = remember(favTick, currentDir.absolutePath) {
|
|
||||||
FavoritesStore.isFavorite(context, currentDir.absolutePath)
|
|
||||||
}
|
|
||||||
|
|
||||||
LazyColumn(modifier = modifier) {
|
|
||||||
item {
|
|
||||||
Row(
|
|
||||||
verticalAlignment = Alignment.CenterVertically,
|
|
||||||
modifier = Modifier
|
|
||||||
.fillMaxWidth()
|
|
||||||
.padding(horizontal = 16.dp, vertical = 8.dp),
|
|
||||||
) {
|
|
||||||
Text(
|
|
||||||
text = "Favorites",
|
|
||||||
color = MaterialTheme.colorScheme.onBackground,
|
|
||||||
fontSize = 15.sp,
|
|
||||||
fontWeight = FontWeight.SemiBold,
|
|
||||||
modifier = Modifier.weight(1f),
|
|
||||||
)
|
|
||||||
TextButton(
|
|
||||||
onClick = onPinCurrent,
|
|
||||||
enabled = !currentAlreadyPinned,
|
|
||||||
) {
|
|
||||||
Icon(Icons.Filled.PushPin, null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(16.dp))
|
|
||||||
Spacer(Modifier.width(6.dp))
|
|
||||||
Text(
|
|
||||||
text = "Pin current folder",
|
|
||||||
color = MaterialTheme.colorScheme.primary,
|
|
||||||
fontSize = 13.sp,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (favorites.isEmpty()) {
|
|
||||||
item {
|
|
||||||
Box(
|
|
||||||
modifier = Modifier.fillParentMaxSize(),
|
|
||||||
contentAlignment = Alignment.Center,
|
|
||||||
) {
|
|
||||||
Text(
|
|
||||||
text = "No favorites yet - pin a folder with its ⋮ menu to jump back here fast.",
|
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
|
||||||
fontSize = 13.sp,
|
|
||||||
modifier = Modifier.padding(horizontal = 32.dp),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
items(favorites, key = { it.absolutePath }) { file ->
|
|
||||||
val loc = remember(file.absolutePath) { describeLocation(file) }
|
|
||||||
FavoriteCard(
|
|
||||||
file = file,
|
|
||||||
loc = loc,
|
|
||||||
onJump = { onJump(file) },
|
|
||||||
onUnpin = { onUnpin(file) },
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// A single favourite - matches the FileItemRow card style (surfaceContainer + outline +
|
|
||||||
// RoundedCornerShape(10.dp)). Shows the folder name, a coloured drive badge + origin text,
|
|
||||||
// and the full display path; tapping jumps into it, the filled star unpins.
|
|
||||||
@Composable
|
|
||||||
private fun FavoriteCard(
|
|
||||||
file: File,
|
|
||||||
loc: FavLocation,
|
|
||||||
onJump: () -> Unit,
|
|
||||||
onUnpin: () -> Unit,
|
|
||||||
) {
|
|
||||||
val (badgeBg, badgeFg) = badgeColors(loc)
|
|
||||||
Card(
|
|
||||||
modifier = Modifier
|
|
||||||
.fillMaxWidth()
|
|
||||||
.padding(horizontal = 12.dp, vertical = 3.dp)
|
|
||||||
.clickable(onClick = onJump),
|
|
||||||
shape = RoundedCornerShape(10.dp),
|
|
||||||
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceContainer),
|
|
||||||
border = BorderStroke(1.dp, MaterialTheme.colorScheme.outline),
|
|
||||||
) {
|
|
||||||
Row(
|
|
||||||
verticalAlignment = Alignment.CenterVertically,
|
|
||||||
modifier = Modifier.padding(horizontal = 12.dp, vertical = 8.dp),
|
|
||||||
) {
|
|
||||||
Icon(
|
|
||||||
imageVector = Icons.Filled.Folder,
|
|
||||||
contentDescription = null,
|
|
||||||
tint = MaterialTheme.colorScheme.primary,
|
|
||||||
modifier = Modifier.size(36.dp),
|
|
||||||
)
|
|
||||||
Spacer(Modifier.width(10.dp))
|
|
||||||
Column(modifier = Modifier.weight(1f)) {
|
|
||||||
Text(
|
|
||||||
text = file.name,
|
|
||||||
color = MaterialTheme.colorScheme.onBackground,
|
|
||||||
fontSize = 14.sp,
|
|
||||||
fontWeight = FontWeight.SemiBold,
|
|
||||||
maxLines = 1,
|
|
||||||
overflow = TextOverflow.Ellipsis,
|
|
||||||
)
|
|
||||||
Spacer(Modifier.height(2.dp))
|
|
||||||
// Origin line: coloured drive badge + source description.
|
|
||||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
|
||||||
Text(
|
|
||||||
text = loc.driveLabel,
|
|
||||||
color = badgeFg,
|
|
||||||
fontSize = 11.sp,
|
|
||||||
fontWeight = FontWeight.Bold,
|
|
||||||
modifier = Modifier
|
|
||||||
.clip(RoundedCornerShape(4.dp))
|
|
||||||
.background(badgeBg)
|
|
||||||
.padding(horizontal = 6.dp, vertical = 2.dp),
|
|
||||||
)
|
|
||||||
Spacer(Modifier.width(6.dp))
|
|
||||||
Text(
|
|
||||||
text = when (loc.storage) {
|
|
||||||
FavStorage.INTERNAL -> "Internal storage"
|
|
||||||
FavStorage.SD -> "SD card"
|
|
||||||
FavStorage.OTHER -> "Storage"
|
|
||||||
},
|
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
|
||||||
fontSize = 12.sp,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
Spacer(Modifier.height(2.dp))
|
|
||||||
Text(
|
|
||||||
text = loc.displayPath,
|
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
|
||||||
fontSize = 12.sp,
|
|
||||||
fontFamily = FontFamily.Monospace,
|
|
||||||
maxLines = 1,
|
|
||||||
overflow = TextOverflow.Ellipsis,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
IconButton(onClick = onUnpin) {
|
|
||||||
Icon(
|
|
||||||
Icons.Filled.Star,
|
|
||||||
contentDescription = "Remove from favorites",
|
|
||||||
tint = MaterialTheme.colorScheme.primary,
|
|
||||||
modifier = Modifier.size(22.dp),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* One entry in the File Manager's grid view: a big thumbnail with the name under it.
|
|
||||||
*
|
|
||||||
* Deliberately drops size and date - at this width they truncate to noise. The grid is for
|
|
||||||
* recognising things by sight (screenshots, covers, game folders); the list stays the view for
|
|
||||||
* reading details.
|
|
||||||
*/
|
|
||||||
@OptIn(ExperimentalFoundationApi::class)
|
|
||||||
@Composable
|
|
||||||
private fun FileGridTile(
|
|
||||||
file: File,
|
|
||||||
selectionMode: Boolean,
|
|
||||||
selected: Boolean,
|
|
||||||
onLongPress: () -> Unit,
|
|
||||||
onToggleSelect: () -> Unit,
|
|
||||||
onTap: () -> Unit,
|
|
||||||
onMenu: () -> Unit,
|
|
||||||
menuExpanded: Boolean = false,
|
|
||||||
onDismissMenu: () -> Unit = {},
|
|
||||||
isFavorite: Boolean = false,
|
|
||||||
onSelect: () -> Unit = {},
|
|
||||||
onRename: () -> Unit = {},
|
|
||||||
onCopy: () -> Unit = {},
|
|
||||||
onCut: () -> Unit = {},
|
|
||||||
onDelete: () -> Unit = {},
|
|
||||||
onToggleFavorite: () -> Unit = {},
|
|
||||||
onProperties: () -> Unit = {},
|
|
||||||
) {
|
|
||||||
val isDir = file.isDirectory
|
|
||||||
val isImage = !isDir && file.extension.lowercase() in IMAGE_THUMB_EXTS
|
|
||||||
var exeIcon by remember(file.absolutePath) { mutableStateOf<ImageBitmap?>(null) }
|
|
||||||
if (!isDir && file.name.lowercase().endsWith(".exe")) {
|
|
||||||
LaunchedEffect(file.absolutePath) {
|
|
||||||
val bmp = withContext(Dispatchers.IO) { PeIconExtractor.extract(file) }
|
|
||||||
if (bmp != null) exeIcon = bmp.asImageBitmap()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// The tile has no ⋮ button - long-press opens this menu, anchored to the Box around the Card.
|
|
||||||
Box {
|
|
||||||
Card(
|
|
||||||
modifier = Modifier
|
|
||||||
.padding(4.dp)
|
|
||||||
.combinedClickable(
|
|
||||||
onClick = { if (selectionMode) onToggleSelect() else onTap() },
|
|
||||||
onLongClick = onLongPress,
|
|
||||||
),
|
|
||||||
shape = RoundedCornerShape(10.dp),
|
|
||||||
colors = CardDefaults.cardColors(
|
|
||||||
containerColor = if (selected) MaterialTheme.colorScheme.primary.copy(alpha = 0.18f)
|
|
||||||
else MaterialTheme.colorScheme.surfaceContainer,
|
|
||||||
),
|
|
||||||
border = BorderStroke(
|
|
||||||
1.dp,
|
|
||||||
if (selected) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.outline,
|
|
||||||
),
|
|
||||||
) {
|
|
||||||
Column(
|
|
||||||
horizontalAlignment = Alignment.CenterHorizontally,
|
|
||||||
modifier = Modifier.fillMaxWidth().padding(8.dp),
|
|
||||||
) {
|
|
||||||
Box(modifier = Modifier.size(56.dp), contentAlignment = Alignment.Center) {
|
|
||||||
when {
|
|
||||||
exeIcon != null -> Image(bitmap = exeIcon!!, contentDescription = null, modifier = Modifier.size(48.dp))
|
|
||||||
isDir -> Icon(
|
|
||||||
Icons.Filled.Folder, null,
|
|
||||||
tint = MaterialTheme.colorScheme.primary,
|
|
||||||
modifier = Modifier.size(48.dp),
|
|
||||||
)
|
|
||||||
isImage -> AsyncImage(
|
|
||||||
model = file,
|
|
||||||
contentDescription = null,
|
|
||||||
contentScale = ContentScale.Crop,
|
|
||||||
placeholder = rememberVectorPainter(Icons.Filled.InsertDriveFile),
|
|
||||||
error = rememberVectorPainter(Icons.Filled.InsertDriveFile),
|
|
||||||
modifier = Modifier.size(56.dp).clip(RoundedCornerShape(6.dp)),
|
|
||||||
)
|
|
||||||
else -> Icon(
|
|
||||||
Icons.Filled.InsertDriveFile, null,
|
|
||||||
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
|
||||||
modifier = Modifier.size(44.dp),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
if (selectionMode) {
|
|
||||||
androidx.compose.material3.Checkbox(
|
|
||||||
checked = selected,
|
|
||||||
onCheckedChange = { onToggleSelect() },
|
|
||||||
modifier = Modifier.align(Alignment.TopStart),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Spacer(Modifier.height(4.dp))
|
|
||||||
// Always reserve two lines (issue #475): a one-line name used to make its card shorter than
|
|
||||||
// its neighbours, so grid rows had ragged heights. Fixed min/max keeps every tile the same size.
|
|
||||||
Text(
|
|
||||||
file.name,
|
|
||||||
color = MaterialTheme.colorScheme.onSurface,
|
|
||||||
fontSize = 12.sp,
|
|
||||||
minLines = 2,
|
|
||||||
maxLines = 2,
|
|
||||||
textAlign = androidx.compose.ui.text.style.TextAlign.Center,
|
|
||||||
overflow = TextOverflow.Ellipsis,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
DropdownMenu(
|
|
||||||
expanded = menuExpanded,
|
|
||||||
onDismissRequest = onDismissMenu,
|
|
||||||
modifier = Modifier.outlinedMenuCard(),
|
|
||||||
) {
|
|
||||||
FileContextMenuItems(
|
|
||||||
file = file,
|
|
||||||
isFavorite = isFavorite,
|
|
||||||
onSelect = onSelect,
|
|
||||||
onRename = onRename,
|
|
||||||
onCopy = onCopy,
|
|
||||||
onCut = onCut,
|
|
||||||
onDelete = onDelete,
|
|
||||||
onToggleFavorite = onToggleFavorite,
|
|
||||||
onProperties = onProperties,
|
|
||||||
onDismissMenu = onDismissMenu,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Properties sheet for a single file or folder: basic info plus the two Windows/Wine file attributes
|
|
||||||
* the in-container file manager (wfm.exe) also exposes - Read-only and Hidden. Each toggle applies
|
|
||||||
* immediately (off the main thread) and refreshes the listing via [onChanged].
|
|
||||||
*
|
|
||||||
* State is keyed on the file so it always reflects the entry it was opened for. On a filesystem that
|
|
||||||
* can't store Wine's DOSATTRIB xattr (the FUSE /storage volumes) only the Hidden toggle is disabled;
|
|
||||||
* Read-only keeps working everywhere.
|
|
||||||
*/
|
|
||||||
@Composable
|
|
||||||
private fun FilePropertiesDialog(
|
|
||||||
file: File,
|
|
||||||
onDismiss: () -> Unit,
|
|
||||||
onChanged: () -> Unit,
|
|
||||||
) {
|
|
||||||
val context = LocalContext.current
|
|
||||||
val scope = rememberCoroutineScope()
|
|
||||||
val dateFormat = remember { SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault()) }
|
|
||||||
var attrs by remember(file.absolutePath) { mutableStateOf<FileAttrState?>(null) }
|
|
||||||
// Guards against a second toggle landing while the first is still being applied off-thread.
|
|
||||||
var busy by remember(file.absolutePath) { mutableStateOf(false) }
|
|
||||||
LaunchedEffect(file.absolutePath) {
|
|
||||||
attrs = withContext(Dispatchers.IO) { readFileAttrs(file) }
|
|
||||||
}
|
|
||||||
|
|
||||||
OutlinedAlertDialog(
|
|
||||||
onDismissRequest = onDismiss,
|
|
||||||
title = { Text("Properties") },
|
|
||||||
text = {
|
|
||||||
Column(modifier = Modifier.verticalScroll(rememberScrollState())) {
|
|
||||||
// ── Basic info ──
|
|
||||||
Text(
|
|
||||||
text = file.name,
|
|
||||||
color = MaterialTheme.colorScheme.onBackground,
|
|
||||||
fontSize = 14.sp,
|
|
||||||
fontWeight = FontWeight.SemiBold,
|
|
||||||
maxLines = 2,
|
|
||||||
overflow = TextOverflow.Ellipsis,
|
|
||||||
)
|
|
||||||
Spacer(Modifier.height(6.dp))
|
|
||||||
PropertyLine("Location", file.parent ?: "-")
|
|
||||||
PropertyLine(
|
|
||||||
"Type",
|
|
||||||
if (file.isDirectory) "Folder"
|
|
||||||
else file.extension.uppercase().let { if (it.isBlank()) "File" else "$it file" },
|
|
||||||
)
|
|
||||||
if (!file.isDirectory) PropertyLine("Size", FileOps.formatBytes(file.length()))
|
|
||||||
PropertyLine("Modified", dateFormat.format(Date(file.lastModified())))
|
|
||||||
|
|
||||||
Spacer(Modifier.height(10.dp))
|
|
||||||
HorizontalDivider(color = MaterialTheme.colorScheme.outline)
|
|
||||||
Spacer(Modifier.height(6.dp))
|
|
||||||
|
|
||||||
val state = attrs
|
|
||||||
// ── Read-only ── checked when the owner can't write (Wine's FILE_ATTRIBUTE_READONLY).
|
|
||||||
AttributeToggleRow(
|
|
||||||
label = "Read-only",
|
|
||||||
description = "Stops games (and Wine) from overwriting or deleting this file.",
|
|
||||||
checked = state?.readOnly == true,
|
|
||||||
enabled = state != null && !busy,
|
|
||||||
onToggle = { want ->
|
|
||||||
busy = true
|
|
||||||
scope.launch {
|
|
||||||
val ok = withContext(Dispatchers.IO) { setReadOnly(file, want) }
|
|
||||||
busy = false
|
|
||||||
if (ok) {
|
|
||||||
attrs = attrs?.copy(readOnly = want)
|
|
||||||
onChanged()
|
|
||||||
} else {
|
|
||||||
Toast.makeText(context, "Couldn't change Read-only", Toast.LENGTH_SHORT).show()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
)
|
|
||||||
Spacer(Modifier.height(2.dp))
|
|
||||||
// ── Hidden ── Wine's DOS hidden bit in the user.DOSATTRIB xattr.
|
|
||||||
val hiddenSupported = state?.hiddenSupported == true
|
|
||||||
AttributeToggleRow(
|
|
||||||
label = "Hidden",
|
|
||||||
description = if (state != null && !hiddenSupported)
|
|
||||||
"This storage can't store the hidden flag."
|
|
||||||
else "Marks the file hidden in Windows (Wine's hidden attribute).",
|
|
||||||
checked = state?.hidden == true,
|
|
||||||
enabled = state != null && hiddenSupported && !busy,
|
|
||||||
onToggle = { want ->
|
|
||||||
busy = true
|
|
||||||
scope.launch {
|
|
||||||
val ok = withContext(Dispatchers.IO) { setHidden(file, want) }
|
|
||||||
busy = false
|
|
||||||
if (ok) {
|
|
||||||
attrs = attrs?.copy(hidden = want)
|
|
||||||
onChanged()
|
|
||||||
} else {
|
|
||||||
// The write failed after all - disable the toggle rather than lie.
|
|
||||||
attrs = attrs?.copy(hiddenSupported = false)
|
|
||||||
Toast.makeText(context, "Couldn't change Hidden on this storage", Toast.LENGTH_SHORT).show()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
)
|
|
||||||
}
|
|
||||||
},
|
|
||||||
confirmButton = { TextButton(onClick = onDismiss) { Text("Done") } },
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
// One "label: value" line in the Properties info block.
|
|
||||||
@Composable
|
|
||||||
private fun PropertyLine(label: String, value: String) {
|
|
||||||
Row(modifier = Modifier.fillMaxWidth().padding(vertical = 2.dp)) {
|
|
||||||
Text(
|
|
||||||
text = label,
|
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
|
||||||
fontSize = 12.sp,
|
|
||||||
modifier = Modifier.width(76.dp),
|
|
||||||
)
|
|
||||||
Text(
|
|
||||||
text = value,
|
|
||||||
color = MaterialTheme.colorScheme.onSurface,
|
|
||||||
fontSize = 12.sp,
|
|
||||||
maxLines = 2,
|
|
||||||
overflow = TextOverflow.Ellipsis,
|
|
||||||
modifier = Modifier.weight(1f),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// A labelled attribute switch with a one-line description, used by the Properties sheet.
|
|
||||||
@Composable
|
|
||||||
private fun AttributeToggleRow(
|
|
||||||
label: String,
|
|
||||||
description: String,
|
|
||||||
checked: Boolean,
|
|
||||||
enabled: Boolean,
|
|
||||||
onToggle: (Boolean) -> Unit,
|
|
||||||
) {
|
|
||||||
Row(
|
|
||||||
verticalAlignment = Alignment.CenterVertically,
|
|
||||||
modifier = Modifier.fillMaxWidth().padding(vertical = 4.dp),
|
|
||||||
) {
|
|
||||||
Column(modifier = Modifier.weight(1f)) {
|
|
||||||
Text(
|
|
||||||
text = label,
|
|
||||||
color = MaterialTheme.colorScheme.onBackground,
|
|
||||||
fontSize = 14.sp,
|
|
||||||
fontWeight = FontWeight.Medium,
|
|
||||||
)
|
|
||||||
Text(
|
|
||||||
text = description,
|
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
|
||||||
fontSize = 12.sp,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
Spacer(Modifier.width(8.dp))
|
|
||||||
androidx.compose.material3.Switch(
|
|
||||||
checked = checked,
|
|
||||||
enabled = enabled,
|
|
||||||
onCheckedChange = onToggle,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,202 @@
|
|||||||
|
package com.droiddeck.launcher.files
|
||||||
|
|
||||||
|
import android.widget.Toast
|
||||||
|
import androidx.compose.foundation.rememberScrollState
|
||||||
|
import androidx.compose.foundation.verticalScroll
|
||||||
|
import androidx.compose.foundation.layout.Column
|
||||||
|
import androidx.compose.foundation.layout.Row
|
||||||
|
import androidx.compose.foundation.layout.Spacer
|
||||||
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
|
import androidx.compose.foundation.layout.height
|
||||||
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.foundation.layout.width
|
||||||
|
import androidx.compose.material.icons.filled.Folder
|
||||||
|
import androidx.compose.material3.HorizontalDivider
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.material3.TextButton
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.LaunchedEffect
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.mutableStateOf
|
||||||
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.runtime.rememberCoroutineScope
|
||||||
|
import androidx.compose.runtime.setValue
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.platform.LocalContext
|
||||||
|
import androidx.compose.ui.text.font.FontWeight
|
||||||
|
import androidx.compose.ui.text.style.TextOverflow
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import androidx.compose.ui.unit.sp
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
|
import java.io.File
|
||||||
|
import java.text.SimpleDateFormat
|
||||||
|
import java.util.Date
|
||||||
|
import java.util.Locale
|
||||||
|
|
||||||
|
// The File Manager's properties dialog.
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Properties sheet for a single file or folder: basic info plus the two Windows/Wine file attributes
|
||||||
|
* the in-container file manager (wfm.exe) also exposes - Read-only and Hidden. Each toggle applies
|
||||||
|
* immediately (off the main thread) and refreshes the listing via [onChanged].
|
||||||
|
*
|
||||||
|
* State is keyed on the file so it always reflects the entry it was opened for. On a filesystem that
|
||||||
|
* can't store Wine's DOSATTRIB xattr (the FUSE /storage volumes) only the Hidden toggle is disabled;
|
||||||
|
* Read-only keeps working everywhere.
|
||||||
|
*/
|
||||||
|
@Composable
|
||||||
|
internal fun FilePropertiesDialog(
|
||||||
|
file: File,
|
||||||
|
onDismiss: () -> Unit,
|
||||||
|
onChanged: () -> Unit,
|
||||||
|
) {
|
||||||
|
val context = LocalContext.current
|
||||||
|
val scope = rememberCoroutineScope()
|
||||||
|
val dateFormat = remember { SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault()) }
|
||||||
|
var attrs by remember(file.absolutePath) { mutableStateOf<FileAttrState?>(null) }
|
||||||
|
// Guards against a second toggle landing while the first is still being applied off-thread.
|
||||||
|
var busy by remember(file.absolutePath) { mutableStateOf(false) }
|
||||||
|
LaunchedEffect(file.absolutePath) {
|
||||||
|
attrs = withContext(Dispatchers.IO) { readFileAttrs(file) }
|
||||||
|
}
|
||||||
|
|
||||||
|
OutlinedAlertDialog(
|
||||||
|
onDismissRequest = onDismiss,
|
||||||
|
title = { Text("Properties") },
|
||||||
|
text = {
|
||||||
|
Column(modifier = Modifier.verticalScroll(rememberScrollState())) {
|
||||||
|
// ── Basic info ──
|
||||||
|
Text(
|
||||||
|
text = file.name,
|
||||||
|
color = MaterialTheme.colorScheme.onBackground,
|
||||||
|
fontSize = 14.sp,
|
||||||
|
fontWeight = FontWeight.SemiBold,
|
||||||
|
maxLines = 2,
|
||||||
|
overflow = TextOverflow.Ellipsis,
|
||||||
|
)
|
||||||
|
Spacer(Modifier.height(6.dp))
|
||||||
|
PropertyLine("Location", file.parent ?: "-")
|
||||||
|
PropertyLine(
|
||||||
|
"Type",
|
||||||
|
if (file.isDirectory) "Folder"
|
||||||
|
else file.extension.uppercase().let { if (it.isBlank()) "File" else "$it file" },
|
||||||
|
)
|
||||||
|
if (!file.isDirectory) PropertyLine("Size", FileOps.formatBytes(file.length()))
|
||||||
|
PropertyLine("Modified", dateFormat.format(Date(file.lastModified())))
|
||||||
|
|
||||||
|
Spacer(Modifier.height(10.dp))
|
||||||
|
HorizontalDivider(color = MaterialTheme.colorScheme.outline)
|
||||||
|
Spacer(Modifier.height(6.dp))
|
||||||
|
|
||||||
|
val state = attrs
|
||||||
|
// ── Read-only ── checked when the owner can't write (Wine's FILE_ATTRIBUTE_READONLY).
|
||||||
|
AttributeToggleRow(
|
||||||
|
label = "Read-only",
|
||||||
|
description = "Stops games (and Wine) from overwriting or deleting this file.",
|
||||||
|
checked = state?.readOnly == true,
|
||||||
|
enabled = state != null && !busy,
|
||||||
|
onToggle = { want ->
|
||||||
|
busy = true
|
||||||
|
scope.launch {
|
||||||
|
val ok = withContext(Dispatchers.IO) { setReadOnly(file, want) }
|
||||||
|
busy = false
|
||||||
|
if (ok) {
|
||||||
|
attrs = attrs?.copy(readOnly = want)
|
||||||
|
onChanged()
|
||||||
|
} else {
|
||||||
|
Toast.makeText(context, "Couldn't change Read-only", Toast.LENGTH_SHORT).show()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
)
|
||||||
|
Spacer(Modifier.height(2.dp))
|
||||||
|
// ── Hidden ── Wine's DOS hidden bit in the user.DOSATTRIB xattr.
|
||||||
|
val hiddenSupported = state?.hiddenSupported == true
|
||||||
|
AttributeToggleRow(
|
||||||
|
label = "Hidden",
|
||||||
|
description = if (state != null && !hiddenSupported)
|
||||||
|
"This storage can't store the hidden flag."
|
||||||
|
else "Marks the file hidden in Windows (Wine's hidden attribute).",
|
||||||
|
checked = state?.hidden == true,
|
||||||
|
enabled = state != null && hiddenSupported && !busy,
|
||||||
|
onToggle = { want ->
|
||||||
|
busy = true
|
||||||
|
scope.launch {
|
||||||
|
val ok = withContext(Dispatchers.IO) { setHidden(file, want) }
|
||||||
|
busy = false
|
||||||
|
if (ok) {
|
||||||
|
attrs = attrs?.copy(hidden = want)
|
||||||
|
onChanged()
|
||||||
|
} else {
|
||||||
|
// The write failed after all - disable the toggle rather than lie.
|
||||||
|
attrs = attrs?.copy(hiddenSupported = false)
|
||||||
|
Toast.makeText(context, "Couldn't change Hidden on this storage", Toast.LENGTH_SHORT).show()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
confirmButton = { TextButton(onClick = onDismiss) { Text("Done") } },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// One "label: value" line in the Properties info block.
|
||||||
|
@Composable
|
||||||
|
private fun PropertyLine(label: String, value: String) {
|
||||||
|
Row(modifier = Modifier.fillMaxWidth().padding(vertical = 2.dp)) {
|
||||||
|
Text(
|
||||||
|
text = label,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
fontSize = 12.sp,
|
||||||
|
modifier = Modifier.width(76.dp),
|
||||||
|
)
|
||||||
|
Text(
|
||||||
|
text = value,
|
||||||
|
color = MaterialTheme.colorScheme.onSurface,
|
||||||
|
fontSize = 12.sp,
|
||||||
|
maxLines = 2,
|
||||||
|
overflow = TextOverflow.Ellipsis,
|
||||||
|
modifier = Modifier.weight(1f),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// A labelled attribute switch with a one-line description, used by the Properties sheet.
|
||||||
|
@Composable
|
||||||
|
private fun AttributeToggleRow(
|
||||||
|
label: String,
|
||||||
|
description: String,
|
||||||
|
checked: Boolean,
|
||||||
|
enabled: Boolean,
|
||||||
|
onToggle: (Boolean) -> Unit,
|
||||||
|
) {
|
||||||
|
Row(
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
modifier = Modifier.fillMaxWidth().padding(vertical = 4.dp),
|
||||||
|
) {
|
||||||
|
Column(modifier = Modifier.weight(1f)) {
|
||||||
|
Text(
|
||||||
|
text = label,
|
||||||
|
color = MaterialTheme.colorScheme.onBackground,
|
||||||
|
fontSize = 14.sp,
|
||||||
|
fontWeight = FontWeight.Medium,
|
||||||
|
)
|
||||||
|
Text(
|
||||||
|
text = description,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
fontSize = 12.sp,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
Spacer(Modifier.width(8.dp))
|
||||||
|
androidx.compose.material3.Switch(
|
||||||
|
checked = checked,
|
||||||
|
enabled = enabled,
|
||||||
|
onCheckedChange = onToggle,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -21,6 +21,7 @@ object Library {
|
|||||||
class SteamGame(
|
class SteamGame(
|
||||||
val appId: Int, val name: String, val art: File?, val library: String, val gameId: Long = appId.toLong(),
|
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 hero: File? = null, val lastPlayed: Long = 0L,
|
||||||
|
val gameFiles: File? = null, val protonPrefix: File? = null,
|
||||||
)
|
)
|
||||||
class Rom(val name: String, val hostPath: File, val guestPath: String, val emulatorId: String, val art: File? = null)
|
class Rom(val name: String, val hostPath: File, val guestPath: String, val emulatorId: String, val art: File? = null)
|
||||||
class Emulator(val id: String, val name: String, val system: String, val program: String, val installed: Boolean, val games: List<Rom>) {
|
class Emulator(val id: String, val name: String, val system: String, val program: String, val installed: Boolean, val games: List<Rom>) {
|
||||||
@@ -66,14 +67,31 @@ object Library {
|
|||||||
private val NAME = Regex("^\\s*\"name\"\\s*\"([^\"]*)\"", RegexOption.MULTILINE)
|
private val NAME = Regex("^\\s*\"name\"\\s*\"([^\"]*)\"", RegexOption.MULTILINE)
|
||||||
private val STATE = Regex("^\\s*\"StateFlags\"\\s*\"(\\d+)\"", RegexOption.MULTILINE)
|
private val STATE = Regex("^\\s*\"StateFlags\"\\s*\"(\\d+)\"", RegexOption.MULTILINE)
|
||||||
private val LAST_PLAYED = Regex("^\\s*\"LastPlayed\"\\s*\"(\\d+)\"", RegexOption.MULTILINE)
|
private val LAST_PLAYED = Regex("^\\s*\"LastPlayed\"\\s*\"(\\d+)\"", RegexOption.MULTILINE)
|
||||||
|
private val INSTALL_DIR = Regex("^\\s*\"installdir\"\\s*\"([^\"]*)\"", RegexOption.MULTILINE)
|
||||||
|
|
||||||
|
/** Steam's library roots visible to this launcher: its private default plus the selected library. */
|
||||||
|
private fun steamLibraries(context: Context): List<Pair<File, String>> {
|
||||||
|
val root = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam")
|
||||||
|
return listOfNotNull(
|
||||||
|
root to "internal",
|
||||||
|
GameStorage.effective(context)?.let { File(it.path) to it.label },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Proton keeps each game's prefix below compatdata/<appid>/pfx in a Steam library. */
|
||||||
|
fun protonPrefix(context: Context, appId: Long, preferredLibrary: File? = null): File? {
|
||||||
|
val ids = listOf(appId.toString(), java.lang.Integer.toString(appId.toInt())).distinct()
|
||||||
|
val roots = (listOfNotNull(preferredLibrary) + steamLibraries(context).map { it.first })
|
||||||
|
.distinctBy { runCatching { it.canonicalPath }.getOrDefault(it.absolutePath) }
|
||||||
|
return roots.asSequence()
|
||||||
|
.flatMap { root -> ids.asSequence().map { id -> File(root, "steamapps/compatdata/$id/pfx") } }
|
||||||
|
.firstOrNull { it.isDirectory }
|
||||||
|
}
|
||||||
|
|
||||||
fun steamGames(context: Context): List<SteamGame> {
|
fun steamGames(context: Context): List<SteamGame> {
|
||||||
val root = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam")
|
val root = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam")
|
||||||
val cache = File(root, "appcache/librarycache")
|
val cache = File(root, "appcache/librarycache")
|
||||||
val libraries = listOfNotNull(
|
val libraries = steamLibraries(context)
|
||||||
root to "internal",
|
|
||||||
GameStorage.effective(context)?.let { File(it.path) to it.label },
|
|
||||||
)
|
|
||||||
val out = LinkedHashMap<Int, SteamGame>()
|
val out = LinkedHashMap<Int, SteamGame>()
|
||||||
for ((library, label) in libraries) {
|
for ((library, label) in libraries) {
|
||||||
val steamapps = File(library, "steamapps")
|
val steamapps = File(library, "steamapps")
|
||||||
@@ -89,7 +107,17 @@ object Library {
|
|||||||
val art = steamCacheImage(cache, appId, STEAM_CAPSULES)
|
val art = steamCacheImage(cache, appId, STEAM_CAPSULES)
|
||||||
val hero = steamCacheImage(cache, appId, STEAM_HEROES)
|
val hero = steamCacheImage(cache, appId, STEAM_HEROES)
|
||||||
val lastPlayed = LAST_PLAYED.find(text)?.groupValues?.get(1)?.toLongOrNull() ?: 0L
|
val lastPlayed = LAST_PLAYED.find(text)?.groupValues?.get(1)?.toLongOrNull() ?: 0L
|
||||||
out[appId] = SteamGame(appId, name, art, label, hero = hero, lastPlayed = lastPlayed)
|
// App manifests are Valve KeyValues (VDF) files. installdir is one folder
|
||||||
|
// below steamapps/common; only expose it when the directory exists and the
|
||||||
|
// manifest value cannot escape that directory.
|
||||||
|
val installDir = INSTALL_DIR.find(text)?.groupValues?.get(1)?.trim()
|
||||||
|
?.takeIf { it.isNotEmpty() && it != "." && it != ".." && '/' !in it && '\\' !in it }
|
||||||
|
val gameFiles = installDir?.let { File(steamapps, "common/$it").takeIf(File::isDirectory) }
|
||||||
|
out[appId] = SteamGame(
|
||||||
|
appId, name, art, label, hero = hero, lastPlayed = lastPlayed,
|
||||||
|
gameFiles = gameFiles,
|
||||||
|
protonPrefix = protonPrefix(context, appId.toLong(), library),
|
||||||
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return out.values.toList()
|
return out.values.toList()
|
||||||
@@ -289,7 +317,9 @@ object Library {
|
|||||||
"-C", "Dolphin.General.HotkeysRequireFocus=False", "-C", "Dolphin.Input.BackgroundInput=True",
|
"-C", "Dolphin.General.HotkeysRequireFocus=False", "-C", "Dolphin.Input.BackgroundInput=True",
|
||||||
"-e", guestPath,
|
"-e", guestPath,
|
||||||
)
|
)
|
||||||
"cemu" -> listOf("-g", guestPath)
|
// Full screen (LaunchSettings.cpp -f); the settings seed keeps the Getting Started
|
||||||
|
// dialog away (bannerlator-pad-defaults).
|
||||||
|
"cemu" -> listOf("-f", "-g", guestPath)
|
||||||
// Full screen (CLI.cpp --fullscreen); the guide button leaves it for melonDS's menus and
|
// Full screen (CLI.cpp --fullscreen); the guide button leaves it for melonDS's menus and
|
||||||
// comes back (HK_FullscreenToggle, bannerlator-pad-defaults).
|
// comes back (HK_FullscreenToggle, bannerlator-pad-defaults).
|
||||||
"melonds" -> listOf("-f", guestPath)
|
"melonds" -> listOf("-f", guestPath)
|
||||||
|
|||||||
@@ -40,9 +40,11 @@ object FrameGen {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** "Off", "Win-FG 2×", "LSFG 3×" - for the main screen. */
|
/** "Off", "Win-FG 2×", "LSFG 3×" - for the main screen. */
|
||||||
fun label(context: Context): String = when (engine(context)) {
|
fun label(context: Context): String = label(engine(context), multiplier(context))
|
||||||
ENGINE_WINFG -> "Win-FG ${multiplier(context)}×"
|
|
||||||
ENGINE_LSFG -> "LSFG ${multiplier(context)}×"
|
fun label(engine: String, multiplier: Int): String = when (engine) {
|
||||||
|
ENGINE_WINFG -> "Win-FG $multiplier×"
|
||||||
|
ENGINE_LSFG -> "LSFG $multiplier×"
|
||||||
else -> "Off"
|
else -> "Off"
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -82,47 +84,5 @@ object FrameGen {
|
|||||||
return problem
|
return problem
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Off, or an engine at 2x/3x/4x; saved on pick, then [onChanged]. The LSFG rows are greyed
|
|
||||||
* and unpickable until Lossless Scaling is installed in the Steam client - the engine cannot
|
|
||||||
* run without its DLL, so offering it would only produce a setting that silently does nothing.
|
|
||||||
*/
|
|
||||||
fun showPicker(activity: android.app.Activity, onChanged: () -> Unit) {
|
|
||||||
val lsfgReady = LsfgNative.isInstalled(activity)
|
|
||||||
val lsfgNote = if (lsfgReady) "" else " - install Lossless Scaling in Steam"
|
|
||||||
val choices = listOf("Off",
|
|
||||||
"Win-FG 2×", "Win-FG 3×", "Win-FG 4×",
|
|
||||||
"LSFG 2×$lsfgNote", "LSFG 3×$lsfgNote", "LSFG 4×$lsfgNote")
|
|
||||||
val current = when (engine(activity)) {
|
|
||||||
ENGINE_WINFG -> multiplier(activity) - 1
|
|
||||||
ENGINE_LSFG -> if (lsfgReady) multiplier(activity) + 2 else 0
|
|
||||||
else -> 0
|
|
||||||
}
|
|
||||||
val adapter = object : android.widget.ArrayAdapter<String>(
|
|
||||||
activity, android.R.layout.simple_list_item_single_choice, choices) {
|
|
||||||
override fun isEnabled(position: Int) = lsfgReady || position < 4
|
|
||||||
override fun areAllItemsEnabled() = lsfgReady
|
|
||||||
override fun getView(position: Int, convertView: android.view.View?, parent: android.view.ViewGroup): android.view.View {
|
|
||||||
val view = super.getView(position, convertView, parent)
|
|
||||||
view.isEnabled = isEnabled(position)
|
|
||||||
view.alpha = if (isEnabled(position)) 1f else 0.38f
|
|
||||||
return view
|
|
||||||
}
|
|
||||||
}
|
|
||||||
android.app.AlertDialog.Builder(activity)
|
|
||||||
.setTitle(com.droiddeck.launcher.R.string.frame_gen_title)
|
|
||||||
.setSingleChoiceItems(adapter, current) { dialog, which ->
|
|
||||||
when (which) {
|
|
||||||
0 -> set(activity, ENGINE_OFF, 2)
|
|
||||||
in 1..3 -> set(activity, ENGINE_WINFG, which + 1)
|
|
||||||
else -> set(activity, ENGINE_LSFG, which - 2)
|
|
||||||
}
|
|
||||||
dialog.dismiss()
|
|
||||||
onChanged()
|
|
||||||
}
|
|
||||||
.setNeutralButton(android.R.string.ok, null)
|
|
||||||
.show()
|
|
||||||
}
|
|
||||||
|
|
||||||
private const val TAG = "FrameGen"
|
private const val TAG = "FrameGen"
|
||||||
}
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
package com.droiddeck.launcher.gpu
|
package com.droiddeck.launcher.gpu
|
||||||
|
|
||||||
|
import com.droiddeck.launcher.core.Hashes
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
import com.droiddeck.launcher.core.FileUtils
|
import com.droiddeck.launcher.core.FileUtils
|
||||||
import org.json.JSONArray
|
import org.json.JSONArray
|
||||||
@@ -27,7 +28,9 @@ object TurnipReleases {
|
|||||||
private const val KEY_DOWNLOADS = "downloads"
|
private const val KEY_DOWNLOADS = "downloads"
|
||||||
|
|
||||||
/** [label] names the variant for the menu: the GPUs it is for, and a build flavour. */
|
/** [label] names the variant for the menu: the GPUs it is for, and a build flavour. */
|
||||||
class Asset(val source: String, val tag: String, val name: String, val url: String, val size: Long, val linux: Boolean, val label: String)
|
/** [sha256] is the release asset's digest from GitHub; empty for a list cached before it was kept. */
|
||||||
|
class Asset(val source: String, val tag: String, val name: String, val url: String, val size: Long, val linux: Boolean, val label: String,
|
||||||
|
val sha256: String = "")
|
||||||
/** [latest] = each source's newest release tag, for the refresh line. */
|
/** [latest] = each source's newest release tag, for the refresh line. */
|
||||||
class Check(val assets: List<Asset>, val latest: List<Pair<String, String>>, val failed: List<String>, val checkedAt: Long)
|
class Check(val assets: List<Asset>, val latest: List<Pair<String, String>>, val failed: List<String>, val checkedAt: Long)
|
||||||
|
|
||||||
@@ -89,11 +92,13 @@ object TurnipReleases {
|
|||||||
val a = list.getJSONObject(j)
|
val a = list.getJSONObject(j)
|
||||||
val name = a.getString("name")
|
val name = a.getString("name")
|
||||||
val (linux, label) = src.classify(name, tag) ?: continue
|
val (linux, label) = src.classify(name, tag) ?: continue
|
||||||
|
// Only assets GitHub has a sha256 for are offered: the download is checked against it.
|
||||||
|
val sha = Hashes.githubSha256(a.optString("digest")) ?: continue
|
||||||
// Newest first: the first release carrying a variant is the one offered.
|
// Newest first: the first release carrying a variant is the one offered.
|
||||||
if (!seen.add("$linux|$label")) continue
|
if (!seen.add("$linux|$label")) continue
|
||||||
assets.put(JSONObject().put("source", src.label).put("tag", tag).put("name", name)
|
assets.put(JSONObject().put("source", src.label).put("tag", tag).put("name", name)
|
||||||
.put("url", a.getString("browser_download_url")).put("size", a.optLong("size"))
|
.put("url", a.getString("browser_download_url")).put("size", a.optLong("size"))
|
||||||
.put("linux", linux).put("label", label))
|
.put("linux", linux).put("label", label).put("sha256", sha))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (newest != null) latest.put(JSONObject().put("source", src.label).put("tag", newest))
|
if (newest != null) latest.put(JSONObject().put("source", src.label).put("tag", newest))
|
||||||
@@ -131,7 +136,7 @@ object TurnipReleases {
|
|||||||
for (i in 0 until list.length()) {
|
for (i in 0 until list.length()) {
|
||||||
val a = list.getJSONObject(i)
|
val a = list.getJSONObject(i)
|
||||||
out.add(Asset(a.getString("source"), a.getString("tag"), a.getString("name"), a.getString("url"),
|
out.add(Asset(a.getString("source"), a.getString("tag"), a.getString("name"), a.getString("url"),
|
||||||
a.optLong("size"), a.getBoolean("linux"), a.getString("label")))
|
a.optLong("size"), a.getBoolean("linux"), a.getString("label"), a.optString("sha256", "")))
|
||||||
}
|
}
|
||||||
val latest = ArrayList<Pair<String, String>>()
|
val latest = ArrayList<Pair<String, String>>()
|
||||||
val l = json.optJSONArray("latest") ?: JSONArray()
|
val l = json.optJSONArray("latest") ?: JSONArray()
|
||||||
@@ -167,6 +172,7 @@ object TurnipReleases {
|
|||||||
|
|
||||||
/** Download an asset into the cache; the caller imports it and deletes the file. */
|
/** Download an asset into the cache; the caller imports it and deletes the file. */
|
||||||
fun download(context: Context, asset: Asset, progress: (Int) -> Unit): File {
|
fun download(context: Context, asset: Asset, progress: (Int) -> Unit): File {
|
||||||
|
if (asset.sha256.isEmpty()) throw IOException("This driver list predates checksums - refresh it and try again")
|
||||||
val target = File(context.cacheDir, asset.name)
|
val target = File(context.cacheDir, asset.name)
|
||||||
val c = URL(asset.url).openConnection() as HttpURLConnection
|
val c = URL(asset.url).openConnection() as HttpURLConnection
|
||||||
c.connectTimeout = 15_000
|
c.connectTimeout = 15_000
|
||||||
@@ -191,6 +197,9 @@ object TurnipReleases {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if (!asset.sha256.equals(Hashes.sha256(target), ignoreCase = true)) {
|
||||||
|
throw IOException("Checksum mismatch - the download was discarded")
|
||||||
|
}
|
||||||
return target
|
return target
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
FileUtils.delete(target)
|
FileUtils.delete(target)
|
||||||
|
|||||||
@@ -1,12 +1,11 @@
|
|||||||
package com.droiddeck.launcher.runtime
|
package com.droiddeck.launcher.runtime
|
||||||
|
|
||||||
|
import com.droiddeck.launcher.core.Hashes
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
import android.util.Log
|
import android.util.Log
|
||||||
import com.droiddeck.launcher.core.Downloader
|
import com.droiddeck.launcher.core.Downloader
|
||||||
import com.droiddeck.launcher.session.SessionState
|
import com.droiddeck.launcher.session.SessionState
|
||||||
import java.io.File
|
import java.io.File
|
||||||
import java.io.FileInputStream
|
|
||||||
import java.security.MessageDigest
|
|
||||||
import org.json.JSONArray
|
import org.json.JSONArray
|
||||||
|
|
||||||
/** Optional Decky Loader installation for the ARM64 Linux guest. */
|
/** Optional Decky Loader installation for the ARM64 Linux guest. */
|
||||||
@@ -84,7 +83,7 @@ object DeckyManager {
|
|||||||
val n = it.optString("name")
|
val n = it.optString("name")
|
||||||
(n == "$name.sha256" || n == "$name.sha256sum" || n == "$name.sha256.txt") && it.optString("browser_download_url").startsWith("https://")
|
(n == "$name.sha256" || n == "$name.sha256sum" || n == "$name.sha256.txt") && it.optString("browser_download_url").startsWith("https://")
|
||||||
}?.optString("browser_download_url")?.takeIf { it.startsWith("https://") }
|
}?.optString("browser_download_url")?.takeIf { it.startsWith("https://") }
|
||||||
val digest = binary.optString("digest").takeIf { it.matches(Regex("(?i)sha256:[0-9a-f]{64}")) }
|
val digest = binary.optString("digest").takeIf { Hashes.isGithubSha256(it) }
|
||||||
if (digest == null && checksum == null) continue
|
if (digest == null && checksum == null) continue
|
||||||
val size = binary.optLong("size", 0)
|
val size = binary.optLong("size", 0)
|
||||||
if (size <= 0) continue
|
if (size <= 0) continue
|
||||||
@@ -109,7 +108,7 @@ object DeckyManager {
|
|||||||
Regex("(?i)\\b[0-9a-f]{64}\\b").find(checksumBody)?.value
|
Regex("(?i)\\b[0-9a-f]{64}\\b").find(checksumBody)?.value
|
||||||
} ?: run { temp.delete(); return "Release checksum is missing" }
|
} ?: run { temp.delete(); return "Release checksum is missing" }
|
||||||
if (!expected.matches(Regex("(?i)[0-9a-f]{64}"))) { temp.delete(); return "Release checksum is invalid" }
|
if (!expected.matches(Regex("(?i)[0-9a-f]{64}"))) { temp.delete(); return "Release checksum is invalid" }
|
||||||
if (!expected.equals(sha256(temp), true)) { temp.delete(); return "Decky Loader checksum mismatch" }
|
if (!expected.equals(Hashes.sha256(temp), true)) { temp.delete(); return "Decky Loader checksum mismatch" }
|
||||||
if (!validElf(temp, release.machine)) { temp.delete(); return "Release asset is not a compatible 64-bit Linux executable" }
|
if (!validElf(temp, release.machine)) { temp.delete(); return "Release asset is not a compatible 64-bit Linux executable" }
|
||||||
if (SessionState.running) { temp.delete(); return "A session started during the download; stop it before installing Decky Loader" }
|
if (SessionState.running) { temp.delete(); return "A session started during the download; stop it before installing Decky Loader" }
|
||||||
if (!temp.setExecutable(true, false)) { temp.delete(); return "Could not mark PluginLoader executable" }
|
if (!temp.setExecutable(true, false)) { temp.delete(); return "Could not mark PluginLoader executable" }
|
||||||
@@ -148,15 +147,6 @@ object DeckyManager {
|
|||||||
if (wipeData) File(root, "root/homebrew").deleteRecursively()
|
if (wipeData) File(root, "root/homebrew").deleteRecursively()
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun sha256(file: File): String {
|
|
||||||
val digest = MessageDigest.getInstance("SHA-256")
|
|
||||||
FileInputStream(file).buffered().use { input ->
|
|
||||||
val buffer = ByteArray(1024 * 1024)
|
|
||||||
while (true) { val n = input.read(buffer); if (n < 0) break; digest.update(buffer, 0, n) }
|
|
||||||
}
|
|
||||||
return digest.digest().joinToString("") { "%02x".format(it.toInt() and 255) }
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun validElf(file: File, machine: Int): Boolean = runCatching {
|
private fun validElf(file: File, machine: Int): Boolean = runCatching {
|
||||||
file.inputStream().use { input ->
|
file.inputStream().use { input ->
|
||||||
val h = ByteArray(20)
|
val h = ByteArray(20)
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
package com.droiddeck.launcher.runtime
|
package com.droiddeck.launcher.runtime
|
||||||
|
|
||||||
|
import com.droiddeck.launcher.core.Hashes
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
import android.util.Log
|
import android.util.Log
|
||||||
import com.droiddeck.launcher.core.Downloader
|
import com.droiddeck.launcher.core.Downloader
|
||||||
@@ -81,6 +82,8 @@ object DesktopCatalog {
|
|||||||
fun install(context: Context, entry: Entry, listener: LinuxRuntimeInstaller.ProgressListener?): String? {
|
fun install(context: Context, entry: Entry, listener: LinuxRuntimeInstaller.ProgressListener?): String? {
|
||||||
val root = LinuxRuntime.rootDir(context)
|
val root = LinuxRuntime.rootDir(context)
|
||||||
if (!root.isDirectory) return "The Linux runtime is not installed"
|
if (!root.isDirectory) return "The Linux runtime is not installed"
|
||||||
|
// Every catalog row carries a sha256; one without is refused rather than trusted.
|
||||||
|
if (entry.sha256.isEmpty()) return "The catalog has no checksum for ${entry.name}"
|
||||||
val download = File(context.cacheDir, "pkg-${entry.id}.download")
|
val download = File(context.cacheDir, "pkg-${entry.id}.download")
|
||||||
try {
|
try {
|
||||||
listener?.onProgress("Downloading ${entry.name}", 0)
|
listener?.onProgress("Downloading ${entry.name}", 0)
|
||||||
@@ -88,11 +91,9 @@ object DesktopCatalog {
|
|||||||
listener?.onProgress("Downloading ${entry.name}", if (f < 0) -1 else Math.round(f * 100f))
|
listener?.onProgress("Downloading ${entry.name}", if (f < 0) -1 else Math.round(f * 100f))
|
||||||
}
|
}
|
||||||
if (!ok) return "Download failed"
|
if (!ok) return "Download failed"
|
||||||
if (entry.sha256.isNotEmpty()) {
|
listener?.onProgress("Verifying", -1)
|
||||||
listener?.onProgress("Verifying", -1)
|
val actual = Hashes.sha256(download)
|
||||||
val actual = LinuxRuntimeInstaller.sha256(download)
|
if (!entry.sha256.equals(actual, ignoreCase = true)) return "Checksum mismatch - nothing was changed"
|
||||||
if (!entry.sha256.equals(actual, ignoreCase = true)) return "Checksum mismatch - nothing was changed"
|
|
||||||
}
|
|
||||||
listener?.onProgress("Installing ${entry.name}", -1)
|
listener?.onProgress("Installing ${entry.name}", -1)
|
||||||
when (entry.kind) {
|
when (entry.kind) {
|
||||||
"appimage" -> {
|
"appimage" -> {
|
||||||
|
|||||||
@@ -4,7 +4,9 @@ import android.content.Context;
|
|||||||
import android.util.Log;
|
import android.util.Log;
|
||||||
|
|
||||||
|
|
||||||
|
import com.droiddeck.launcher.core.ArchivePaths;
|
||||||
import com.droiddeck.launcher.core.Downloader;
|
import com.droiddeck.launcher.core.Downloader;
|
||||||
|
import com.droiddeck.launcher.core.Hashes;
|
||||||
import com.droiddeck.launcher.core.FileUtils;
|
import com.droiddeck.launcher.core.FileUtils;
|
||||||
|
|
||||||
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
|
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
|
||||||
@@ -23,7 +25,8 @@ import java.io.OutputStream;
|
|||||||
import java.nio.charset.StandardCharsets;
|
import java.nio.charset.StandardCharsets;
|
||||||
import java.nio.file.Files;
|
import java.nio.file.Files;
|
||||||
import java.nio.file.StandardCopyOption;
|
import java.nio.file.StandardCopyOption;
|
||||||
import java.security.MessageDigest;
|
import java.util.concurrent.CopyOnWriteArrayList;
|
||||||
|
import java.util.concurrent.CountDownLatch;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Downloads and unpacks the Linux runtime rootfs into {@code files/linuxfs}. It is opt-in: nothing
|
* Downloads and unpacks the Linux runtime rootfs into {@code files/linuxfs}. It is opt-in: nothing
|
||||||
@@ -52,7 +55,7 @@ public final class LinuxRuntimeInstaller {
|
|||||||
public final String sha256;
|
public final String sha256;
|
||||||
public final long size;
|
public final long size;
|
||||||
|
|
||||||
Release(String version, String url, String sha256, long size) {
|
public Release(String version, String url, String sha256, long size) {
|
||||||
this.version = version;
|
this.version = version;
|
||||||
this.url = url;
|
this.url = url;
|
||||||
this.sha256 = sha256;
|
this.sha256 = sha256;
|
||||||
@@ -60,6 +63,23 @@ public final class LinuxRuntimeInstaller {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* One install per process. The launcher and the session screen can both start one, and a
|
||||||
|
* launcher rebuilt mid-install (a pad plugged in, dark mode switched) forgets it had: a second
|
||||||
|
* install would share the first one's archive and staging directory and wreck both.
|
||||||
|
*/
|
||||||
|
private static final class Job {
|
||||||
|
final CopyOnWriteArrayList<ProgressListener> listeners = new CopyOnWriteArrayList<>();
|
||||||
|
final CountDownLatch done = new CountDownLatch(1);
|
||||||
|
volatile String stage = "Starting\u2026";
|
||||||
|
volatile int percent = -1;
|
||||||
|
volatile boolean ok;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static final Object JOB_LOCK = new Object();
|
||||||
|
private static Job running;
|
||||||
|
private static boolean removing;
|
||||||
|
|
||||||
private LinuxRuntimeInstaller() {}
|
private LinuxRuntimeInstaller() {}
|
||||||
|
|
||||||
/** The build currently unpacked, or null when the runtime is not installed. */
|
/** The build currently unpacked, or null when the runtime is not installed. */
|
||||||
@@ -104,6 +124,66 @@ public final class LinuxRuntimeInstaller {
|
|||||||
* not. An update therefore keeps Steam, the login and the installed games.
|
* not. An update therefore keeps Steam, the login and the installed games.
|
||||||
*/
|
*/
|
||||||
public static boolean install(Context context, Release release, ProgressListener listener) {
|
public static boolean install(Context context, Release release, ProgressListener listener) {
|
||||||
|
Job job;
|
||||||
|
boolean owner;
|
||||||
|
synchronized (JOB_LOCK) {
|
||||||
|
if (removing) return false;
|
||||||
|
owner = running == null;
|
||||||
|
if (owner) running = new Job();
|
||||||
|
job = running;
|
||||||
|
if (listener != null) job.listeners.add(listener);
|
||||||
|
}
|
||||||
|
if (!owner) return join(job, listener);
|
||||||
|
try {
|
||||||
|
job.ok = installOnce(context.getApplicationContext(), release, (stage, percent) -> {
|
||||||
|
job.stage = stage;
|
||||||
|
job.percent = percent;
|
||||||
|
for (ProgressListener l : job.listeners) l.onProgress(stage, percent);
|
||||||
|
});
|
||||||
|
return job.ok;
|
||||||
|
} finally {
|
||||||
|
synchronized (JOB_LOCK) {
|
||||||
|
running = null;
|
||||||
|
}
|
||||||
|
job.done.countDown();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** True while an install is running in this process, whoever started it. */
|
||||||
|
public static boolean isInstalling() {
|
||||||
|
synchronized (JOB_LOCK) {
|
||||||
|
return running != null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Follows the install already running, for a screen that was rebuilt mid-install. Blocks until
|
||||||
|
* it ends and returns its result, or returns null at once when nothing is installing.
|
||||||
|
*/
|
||||||
|
public static Boolean attach(ProgressListener listener) {
|
||||||
|
Job job;
|
||||||
|
synchronized (JOB_LOCK) {
|
||||||
|
job = running;
|
||||||
|
if (job == null) return null;
|
||||||
|
if (listener != null) job.listeners.add(listener);
|
||||||
|
}
|
||||||
|
return join(job, listener);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean join(Job job, ProgressListener listener) {
|
||||||
|
try {
|
||||||
|
if (listener != null) listener.onProgress(job.stage, job.percent);
|
||||||
|
job.done.await();
|
||||||
|
return job.ok;
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
Thread.currentThread().interrupt();
|
||||||
|
return false;
|
||||||
|
} finally {
|
||||||
|
if (listener != null) job.listeners.remove(listener);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean installOnce(Context context, Release release, ProgressListener listener) {
|
||||||
File archive = new File(context.getCacheDir(), "linuxfs.tar.zst");
|
File archive = new File(context.getCacheDir(), "linuxfs.tar.zst");
|
||||||
try {
|
try {
|
||||||
if (listener != null) listener.onProgress("Downloading", 0);
|
if (listener != null) listener.onProgress("Downloading", 0);
|
||||||
@@ -120,7 +200,7 @@ public final class LinuxRuntimeInstaller {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (listener != null) listener.onProgress("Verifying", -1);
|
if (listener != null) listener.onProgress("Verifying", -1);
|
||||||
String actual = sha256(archive);
|
String actual = Hashes.sha256(archive);
|
||||||
if (!release.sha256.equalsIgnoreCase(actual)) {
|
if (!release.sha256.equalsIgnoreCase(actual)) {
|
||||||
Log.w(TAG, "checksum mismatch: wanted " + release.sha256 + ", got " + actual);
|
Log.w(TAG, "checksum mismatch: wanted " + release.sha256 + ", got " + actual);
|
||||||
return false;
|
return false;
|
||||||
@@ -130,6 +210,8 @@ public final class LinuxRuntimeInstaller {
|
|||||||
// runtime that isInstalled() would happily launch.
|
// runtime that isInstalled() would happily launch.
|
||||||
File root = LinuxRuntime.rootDir(context);
|
File root = LinuxRuntime.rootDir(context);
|
||||||
File staging = new File(root.getParentFile(), LinuxRuntime.DIR + ".new");
|
File staging = new File(root.getParentFile(), LinuxRuntime.DIR + ".new");
|
||||||
|
File old = new File(root.getParentFile(), LinuxRuntime.DIR + ".old");
|
||||||
|
recoverInterruptedSwap(root, staging, old);
|
||||||
FileUtils.delete(staging);
|
FileUtils.delete(staging);
|
||||||
if (!staging.mkdirs()) return false;
|
if (!staging.mkdirs()) return false;
|
||||||
if (listener != null) listener.onProgress("Extracting", -1);
|
if (listener != null) listener.onProgress("Extracting", -1);
|
||||||
@@ -139,7 +221,6 @@ public final class LinuxRuntimeInstaller {
|
|||||||
}
|
}
|
||||||
FileUtils.writeString(new File(staging, VERSION_FILE), release.version);
|
FileUtils.writeString(new File(staging, VERSION_FILE), release.version);
|
||||||
|
|
||||||
File old = new File(root.getParentFile(), LinuxRuntime.DIR + ".old");
|
|
||||||
FileUtils.delete(old);
|
FileUtils.delete(old);
|
||||||
if (root.isDirectory() && !root.renameTo(old)) {
|
if (root.isDirectory() && !root.renameTo(old)) {
|
||||||
FileUtils.delete(staging);
|
FileUtils.delete(staging);
|
||||||
@@ -164,6 +245,8 @@ public final class LinuxRuntimeInstaller {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (!staging.renameTo(root)) {
|
if (!staging.renameTo(root)) {
|
||||||
|
File keptTo = new File(staging, USER_DATA);
|
||||||
|
if (keptTo.isDirectory() && old.isDirectory()) keptTo.renameTo(new File(old, USER_DATA));
|
||||||
if (old.isDirectory()) old.renameTo(root);
|
if (old.isDirectory()) old.renameTo(root);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@@ -177,8 +260,38 @@ public final class LinuxRuntimeInstaller {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void uninstall(Context context) {
|
private static void recoverInterruptedSwap(File root, File staging, File old) {
|
||||||
FileUtils.delete(LinuxRuntime.rootDir(context));
|
File target = root.isDirectory() ? root : old;
|
||||||
|
File stagedHome = new File(staging, USER_DATA);
|
||||||
|
File home = new File(target, USER_DATA);
|
||||||
|
if (target.isDirectory() && stagedHome.isDirectory() && (!home.exists() || isEmptyDir(home))) {
|
||||||
|
FileUtils.delete(home);
|
||||||
|
if (stagedHome.renameTo(home)) Log.w(TAG, "recovered " + USER_DATA + " from an interrupted update");
|
||||||
|
}
|
||||||
|
if (!root.isDirectory() && old.isDirectory() && old.renameTo(root)) {
|
||||||
|
Log.w(TAG, "restored the previous runtime after an interrupted update");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean isEmptyDir(File dir) {
|
||||||
|
String[] names = dir.list();
|
||||||
|
return dir.isDirectory() && names != null && names.length == 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Removes the runtime; returns false without touching it while an install is running. */
|
||||||
|
public static boolean uninstall(Context context) {
|
||||||
|
synchronized (JOB_LOCK) {
|
||||||
|
if (running != null || removing) return false;
|
||||||
|
removing = true;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
FileUtils.delete(LinuxRuntime.rootDir(context));
|
||||||
|
return true;
|
||||||
|
} finally {
|
||||||
|
synchronized (JOB_LOCK) {
|
||||||
|
removing = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -193,12 +306,10 @@ public final class LinuxRuntimeInstaller {
|
|||||||
new BufferedInputStream(new FileInputStream(archive), 1 << 16));
|
new BufferedInputStream(new FileInputStream(archive), 1 << 16));
|
||||||
TarArchiveInputStream tar = new TarArchiveInputStream(in)) {
|
TarArchiveInputStream tar = new TarArchiveInputStream(in)) {
|
||||||
TarArchiveEntry entry;
|
TarArchiveEntry entry;
|
||||||
String base = destination.getCanonicalPath() + File.separator;
|
|
||||||
while ((entry = tar.getNextTarEntry()) != null) {
|
while ((entry = tar.getNextTarEntry()) != null) {
|
||||||
File file = new File(destination, entry.getName());
|
|
||||||
// Refuse anything that would land outside the runtime directory.
|
// Refuse anything that would land outside the runtime directory.
|
||||||
if (!(file.getCanonicalPath() + (entry.isDirectory() ? File.separator : "")).startsWith(base)
|
File file = ArchivePaths.inside(destination, entry.getName());
|
||||||
&& !file.getCanonicalPath().equals(destination.getCanonicalPath())) {
|
if (file == null) {
|
||||||
Log.w(TAG, "skipping entry outside the rootfs: " + entry.getName());
|
Log.w(TAG, "skipping entry outside the rootfs: " + entry.getName());
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@@ -215,7 +326,13 @@ public final class LinuxRuntimeInstaller {
|
|||||||
} else if (entry.isLink()) {
|
} else if (entry.isLink()) {
|
||||||
// A hard link to an earlier entry. Link where the filesystem allows it and
|
// A hard link to an earlier entry. Link where the filesystem allows it and
|
||||||
// fall back to a copy, which costs space but always works.
|
// fall back to a copy, which costs space but always works.
|
||||||
File target = new File(destination, entry.getLinkName());
|
// The target is checked too: a link to "../../shared_prefs/x" would pull a
|
||||||
|
// file from outside the rootfs into it.
|
||||||
|
File target = ArchivePaths.inside(destination, entry.getLinkName());
|
||||||
|
if (target == null) {
|
||||||
|
Log.w(TAG, "skipping hard link outside the rootfs: " + entry.getLinkName());
|
||||||
|
continue;
|
||||||
|
}
|
||||||
file.delete();
|
file.delete();
|
||||||
try {
|
try {
|
||||||
Files.createLink(file.toPath(), target.toPath());
|
Files.createLink(file.toPath(), target.toPath());
|
||||||
@@ -244,16 +361,4 @@ public final class LinuxRuntimeInstaller {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static String sha256(File file) throws Exception {
|
|
||||||
MessageDigest digest = MessageDigest.getInstance("SHA-256");
|
|
||||||
try (InputStream in = new BufferedInputStream(new FileInputStream(file), 1 << 16)) {
|
|
||||||
byte[] buffer = new byte[1 << 16];
|
|
||||||
int read;
|
|
||||||
while ((read = in.read(buffer)) != -1) digest.update(buffer, 0, read);
|
|
||||||
}
|
|
||||||
StringBuilder sb = new StringBuilder();
|
|
||||||
for (byte b : digest.digest()) sb.append(String.format("%02x", b));
|
|
||||||
return sb.toString();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,100 @@
|
|||||||
|
package com.droiddeck.launcher.runtime
|
||||||
|
|
||||||
|
import android.app.Notification
|
||||||
|
import android.app.NotificationChannel
|
||||||
|
import android.app.NotificationManager
|
||||||
|
import android.app.PendingIntent
|
||||||
|
import android.app.Service
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.Intent
|
||||||
|
import android.os.Build
|
||||||
|
import android.os.IBinder
|
||||||
|
import com.droiddeck.launcher.MainActivity
|
||||||
|
import com.droiddeck.launcher.R
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Keeps the process in the foreground while the Linux runtime downloads and unpacks. The runtime
|
||||||
|
* is several hundred megabytes; without a foreground service Android may kill the app the moment
|
||||||
|
* the user switches away, and the install starts over from the resumable part file.
|
||||||
|
*
|
||||||
|
* The install itself is [LinuxRuntimeInstaller.install], which runs one job per process: the
|
||||||
|
* screen that asked for it joins the same job to show progress, so it does not matter which of the
|
||||||
|
* two gets there first.
|
||||||
|
*/
|
||||||
|
class RuntimeInstallService : Service() {
|
||||||
|
override fun onBind(intent: Intent?): IBinder? = null
|
||||||
|
|
||||||
|
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||||
|
val release = intent?.let(::releaseFrom)
|
||||||
|
startForeground(NOTIFICATION_ID, notification("Starting…", -1))
|
||||||
|
if (release == null) {
|
||||||
|
stopSelf(startId)
|
||||||
|
return START_NOT_STICKY
|
||||||
|
}
|
||||||
|
Thread({
|
||||||
|
val manager = getSystemService(NotificationManager::class.java)
|
||||||
|
var shown = Int.MIN_VALUE
|
||||||
|
LinuxRuntimeInstaller.install(applicationContext, release) { stage, percent ->
|
||||||
|
// Every percent at most once: a notification per read would flood the system.
|
||||||
|
if (percent != shown) {
|
||||||
|
shown = percent
|
||||||
|
manager?.notify(NOTIFICATION_ID, notification(stage, percent))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@Suppress("DEPRECATION")
|
||||||
|
stopForeground(true)
|
||||||
|
stopSelf(startId)
|
||||||
|
}, "runtime-install").start()
|
||||||
|
return START_NOT_STICKY
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun notification(stage: String, percent: Int): Notification {
|
||||||
|
val manager = getSystemService(NotificationManager::class.java)
|
||||||
|
manager?.createNotificationChannel(NotificationChannel(CHANNEL_ID, "Runtime install",
|
||||||
|
NotificationManager.IMPORTANCE_LOW).apply {
|
||||||
|
description = "Shows while the Linux runtime downloads and installs"
|
||||||
|
setShowBadge(false)
|
||||||
|
setSound(null, null)
|
||||||
|
enableVibration(false)
|
||||||
|
})
|
||||||
|
val open = PendingIntent.getActivity(this, 0,
|
||||||
|
Intent(this, MainActivity::class.java).setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_REORDER_TO_FRONT),
|
||||||
|
PendingIntent.FLAG_IMMUTABLE)
|
||||||
|
return Notification.Builder(this, CHANNEL_ID)
|
||||||
|
.setSmallIcon(R.drawable.ic_stat_session)
|
||||||
|
.setContentTitle("Installing the Linux runtime")
|
||||||
|
.setContentText(stage)
|
||||||
|
.setProgress(100, percent.coerceIn(0, 100), percent < 0)
|
||||||
|
.setContentIntent(open)
|
||||||
|
.setOngoing(true)
|
||||||
|
.setOnlyAlertOnce(true)
|
||||||
|
.setShowWhen(false)
|
||||||
|
.build()
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
private const val CHANNEL_ID = "runtime-install"
|
||||||
|
private const val NOTIFICATION_ID = 2
|
||||||
|
private const val EXTRA_VERSION = "version"
|
||||||
|
private const val EXTRA_URL = "url"
|
||||||
|
private const val EXTRA_SHA256 = "sha256"
|
||||||
|
private const val EXTRA_SIZE = "size"
|
||||||
|
|
||||||
|
/** Starts the install of [release] in the foreground; a running install is joined instead. */
|
||||||
|
fun start(context: Context, release: LinuxRuntimeInstaller.Release) {
|
||||||
|
val intent = Intent(context, RuntimeInstallService::class.java)
|
||||||
|
.putExtra(EXTRA_VERSION, release.version)
|
||||||
|
.putExtra(EXTRA_URL, release.url)
|
||||||
|
.putExtra(EXTRA_SHA256, release.sha256)
|
||||||
|
.putExtra(EXTRA_SIZE, release.size)
|
||||||
|
if (Build.VERSION.SDK_INT >= 26) context.startForegroundService(intent) else context.startService(intent)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun releaseFrom(intent: Intent): LinuxRuntimeInstaller.Release? {
|
||||||
|
val version = intent.getStringExtra(EXTRA_VERSION) ?: return null
|
||||||
|
val url = intent.getStringExtra(EXTRA_URL) ?: return null
|
||||||
|
val sha256 = intent.getStringExtra(EXTRA_SHA256) ?: return null
|
||||||
|
return LinuxRuntimeInstaller.Release(version, url, sha256, intent.getLongExtra(EXTRA_SIZE, 0L))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
package com.droiddeck.launcher.session
|
package com.droiddeck.launcher.session
|
||||||
|
|
||||||
|
import com.droiddeck.launcher.core.Hashes
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
import android.util.Log
|
import android.util.Log
|
||||||
import com.droiddeck.launcher.core.Downloader
|
import com.droiddeck.launcher.core.Downloader
|
||||||
@@ -16,7 +17,6 @@ import java.io.BufferedOutputStream
|
|||||||
import java.io.File
|
import java.io.File
|
||||||
import java.io.FileInputStream
|
import java.io.FileInputStream
|
||||||
import java.io.FileOutputStream
|
import java.io.FileOutputStream
|
||||||
import java.security.MessageDigest
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* FEX, DXVK and VKD3D-Proton per Proton, for the Linux Steam client.
|
* FEX, DXVK and VKD3D-Proton per Proton, for the Linux Steam client.
|
||||||
@@ -245,17 +245,8 @@ object ComponentsManager {
|
|||||||
|
|
||||||
private fun owned(comp: String, rel: String) = comp == "fex" || PE_ARCHES.any { "/$it/" in rel }
|
private fun owned(comp: String, rel: String) = comp == "fex" || PE_ARCHES.any { "/$it/" in rel }
|
||||||
|
|
||||||
private fun sha256(f: File): String {
|
|
||||||
val md = MessageDigest.getInstance("SHA-256")
|
|
||||||
FileInputStream(f).use { input ->
|
|
||||||
val buf = ByteArray(1 shl 16)
|
|
||||||
while (true) { val n = input.read(buf); if (n < 0) break; md.update(buf, 0, n) }
|
|
||||||
}
|
|
||||||
return md.digest().joinToString("") { "%02x".format(it.toInt() and 255) }
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun fingerprint(dir: File, comp: String): Map<String, String> =
|
private fun fingerprint(dir: File, comp: String): Map<String, String> =
|
||||||
compFiles(dir, comp).filter { owned(comp, it) }.associateWith { sha256(File(dir, it)) }
|
compFiles(dir, comp).filter { owned(comp, it) }.associateWith { Hashes.sha256(File(dir, it)) }
|
||||||
|
|
||||||
// ------------------------------------------------------------------ packages
|
// ------------------------------------------------------------------ packages
|
||||||
|
|
||||||
@@ -316,7 +307,7 @@ object ComponentsManager {
|
|||||||
if (rel.endsWith(".so")) tmp.setExecutable(true, false)
|
if (rel.endsWith(".so")) tmp.setExecutable(true, false)
|
||||||
tmp.setReadable(true, false)
|
tmp.setReadable(true, false)
|
||||||
if (!tmp.renameTo(dst)) { dst.delete(); check(tmp.renameTo(dst)) { "could not place $rel" } }
|
if (!tmp.renameTo(dst)) { dst.delete(); check(tmp.renameTo(dst)) { "could not place $rel" } }
|
||||||
hashes[rel] = sha256(dst)
|
hashes[rel] = Hashes.sha256(dst)
|
||||||
}
|
}
|
||||||
return hashes
|
return hashes
|
||||||
} finally {
|
} finally {
|
||||||
@@ -629,6 +620,8 @@ object ComponentsManager {
|
|||||||
val a = assets.getJSONObject(i)
|
val a = assets.getJSONObject(i)
|
||||||
val name = a.optString("name")
|
val name = a.optString("name")
|
||||||
if (!name.endsWith(".wcp")) continue
|
if (!name.endsWith(".wcp")) continue
|
||||||
|
// Only packages GitHub has a sha256 for are offered: the download is checked against it.
|
||||||
|
if (!Hashes.isGithubSha256(a.optString("digest"))) continue
|
||||||
items.put(JSONObject().put("file", name).put("comp", comp).put("release", tag)
|
items.put(JSONObject().put("file", name).put("comp", comp).put("release", tag)
|
||||||
.put("url", a.optString("browser_download_url")).put("size", a.optLong("size")).put("digest", a.optString("digest")))
|
.put("url", a.optString("browser_download_url")).put("size", a.optLong("size")).put("digest", a.optString("digest")))
|
||||||
}
|
}
|
||||||
@@ -650,13 +643,12 @@ object ComponentsManager {
|
|||||||
/** Downloads a catalog item into storage, verifying the release's sha256 and the package type. */
|
/** Downloads a catalog item into storage, verifying the release's sha256 and the package type. */
|
||||||
fun download(context: Context, item: CatalogItem, progress: (Int) -> Unit): Package {
|
fun download(context: Context, item: CatalogItem, progress: (Int) -> Unit): Package {
|
||||||
require(item.url.startsWith("https://github.com/$NIGHTLIES/releases/download/")) { "Downloads come only from the Nightlies releases" }
|
require(item.url.startsWith("https://github.com/$NIGHTLIES/releases/download/")) { "Downloads come only from the Nightlies releases" }
|
||||||
|
require(Hashes.isGithubSha256(item.digest)) { "This package list predates checksums - refresh it and try again" }
|
||||||
val dest = File(packagesDir(context), safeName(item.file))
|
val dest = File(packagesDir(context), safeName(item.file))
|
||||||
val part = File(dest.parentFile, dest.name + ".part")
|
val part = File(dest.parentFile, dest.name + ".part")
|
||||||
part.delete()
|
part.delete()
|
||||||
check(Downloader.downloadFile(item.url, part, false) { f -> progress(if (f < 0) -1 else (f * 100).toInt().coerceIn(0, 100)) }) { "Download failed" }
|
check(Downloader.downloadFile(item.url, part, false) { f -> progress(if (f < 0) -1 else (f * 100).toInt().coerceIn(0, 100)) }) { "Download failed" }
|
||||||
if (item.digest.startsWith("sha256:")) {
|
if (!Hashes.sha256(part).equals(item.digest.substringAfter(':'), true)) { part.delete(); error("Checksum mismatch") }
|
||||||
if (!sha256(part).equals(item.digest.substringAfter(':'), true)) { part.delete(); error("Checksum mismatch") }
|
|
||||||
}
|
|
||||||
val info = runCatching { packageInfo(part) }.getOrElse { part.delete(); throw it }
|
val info = runCatching { packageInfo(part) }.getOrElse { part.delete(); throw it }
|
||||||
synchronized(lock) { part.renameTo(dest) }
|
synchronized(lock) { part.renameTo(dest) }
|
||||||
return info.copy(file = dest.name)
|
return info.copy(file = dest.name)
|
||||||
|
|||||||
@@ -17,15 +17,20 @@ import java.nio.charset.StandardCharsets
|
|||||||
* progress, and lifting that out is the difference between "starting the Steam client" for three
|
* progress, and lifting that out is the difference between "starting the Steam client" for three
|
||||||
* minutes and a percentage that moves.
|
* minutes and a percentage that moves.
|
||||||
*/
|
*/
|
||||||
class LoadingState(context: Context) {
|
class LoadingState(context: Context, steam: Boolean = true) {
|
||||||
var visible by mutableStateOf(true)
|
var visible by mutableStateOf(true)
|
||||||
var step by mutableStateOf("Starting the session…")
|
var step by mutableStateOf("Starting the session…")
|
||||||
var percent by mutableIntStateOf(-1)
|
var percent by mutableIntStateOf(-1)
|
||||||
var elapsed by mutableStateOf("")
|
var elapsed by mutableStateOf("")
|
||||||
var hint by mutableStateOf("")
|
var hint by mutableStateOf("")
|
||||||
var ended by mutableStateOf(false)
|
var ended by mutableStateOf(false)
|
||||||
|
/** The technical side of an ended session (exit status, log path), under the advice in [step]. */
|
||||||
|
var endedDetail by mutableStateOf<String?>(null)
|
||||||
|
|
||||||
private val hints = context.resources.getStringArray(com.droiddeck.launcher.R.array.loading_hints)
|
// The desktop and the emulators get their own: the Steam ones talk about Steam.
|
||||||
|
private val hints = context.resources.getStringArray(
|
||||||
|
if (steam) com.droiddeck.launcher.R.array.loading_hints else com.droiddeck.launcher.R.array.loading_hints_desktop,
|
||||||
|
)
|
||||||
private val startedAt = SystemClock.elapsedRealtime()
|
private val startedAt = SystemClock.elapsedRealtime()
|
||||||
|
|
||||||
/** Once a second: the clock and the hint. */
|
/** Once a second: the clock and the hint. */
|
||||||
@@ -35,10 +40,11 @@ class LoadingState(context: Context) {
|
|||||||
hint = hints[((seconds / 8) % hints.size).toInt()]
|
hint = hints[((seconds / 8) % hints.size).toInt()]
|
||||||
}
|
}
|
||||||
|
|
||||||
fun showEnded(message: String) {
|
fun showEnded(message: String, detail: String? = null) {
|
||||||
visible = true
|
visible = true
|
||||||
ended = true
|
ended = true
|
||||||
step = message
|
step = message
|
||||||
|
endedDetail = detail
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Re-reads the end of the log and updates the line and the bar. */
|
/** Re-reads the end of the log and updates the line and the bar. */
|
||||||
|
|||||||
@@ -81,7 +81,7 @@ class PerfHud(context: Context) {
|
|||||||
|
|
||||||
fun stop() {
|
fun stop() {
|
||||||
running = false
|
running = false
|
||||||
WaylandCompositor.setGameListener(null)
|
WaylandCompositor.clearGameListener(listener)
|
||||||
text = ""
|
text = ""
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
package com.droiddeck.launcher.session
|
package com.droiddeck.launcher.session
|
||||||
|
|
||||||
|
import com.droiddeck.launcher.core.Hashes
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
import android.os.StatFs
|
import android.os.StatFs
|
||||||
import android.util.Log
|
import android.util.Log
|
||||||
@@ -7,7 +8,6 @@ import com.droiddeck.launcher.core.Downloader
|
|||||||
import com.droiddeck.launcher.core.FileUtils
|
import com.droiddeck.launcher.core.FileUtils
|
||||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||||
import java.io.File
|
import java.io.File
|
||||||
import java.security.MessageDigest
|
|
||||||
import org.json.JSONArray
|
import org.json.JSONArray
|
||||||
|
|
||||||
/** Immediate download and installation of the optional ARM64 Proton builds. */
|
/** Immediate download and installation of the optional ARM64 Proton builds. */
|
||||||
@@ -21,7 +21,9 @@ object ProtonExtras {
|
|||||||
|
|
||||||
class Tool(val id: String, val name: String, val prefix: String, val repo: String, val assetPattern: Regex)
|
class Tool(val id: String, val name: String, val prefix: String, val repo: String, val assetPattern: Regex)
|
||||||
|
|
||||||
private data class Asset(val tag: String, val name: String, val url: String, val sha512: String?, val size: Long)
|
/** [sha256] from GitHub's asset digest; [sha512] the URL of a checksum file published beside it. */
|
||||||
|
private data class Asset(val tag: String, val name: String, val url: String, val sha512: String?, val size: Long,
|
||||||
|
val sha256: String? = null)
|
||||||
|
|
||||||
val tools = listOf(
|
val tools = listOf(
|
||||||
Tool("ge", "GE-Proton", "GE-Proton", "GloriousEggroll/proton-ge-custom", Regex("aarch64\\.tar\\.(gz|xz)$")),
|
Tool("ge", "GE-Proton", "GE-Proton", "GloriousEggroll/proton-ge-custom", Regex("aarch64\\.tar\\.(gz|xz)$")),
|
||||||
@@ -99,14 +101,24 @@ object ProtonExtras {
|
|||||||
return "Download was incomplete; the partial file is kept for a resumable retry"
|
return "Download was incomplete; the partial file is kept for a resumable retry"
|
||||||
}
|
}
|
||||||
|
|
||||||
asset.sha512?.let { checksumUrl ->
|
// One checksum has to be found and has to match: GitHub's sha256 digest, else the
|
||||||
onProgress("Verifying download", -1)
|
// release's own sha512 file. A download neither vouches for is not installed.
|
||||||
val checksumText = Downloader.downloadString(checksumUrl)
|
onProgress("Verifying download", -1)
|
||||||
val expected = checksumText?.let { Regex("(?i)\\b[0-9a-f]{128}\\b").find(it)?.value }
|
val verified = when {
|
||||||
if (expected != null && !expected.equals(sha512(archive), ignoreCase = true)) {
|
asset.sha256 != null -> asset.sha256.equals(Hashes.sha256(archive), ignoreCase = true)
|
||||||
archive.delete()
|
asset.sha512 != null -> {
|
||||||
return "Checksum mismatch; the download was deleted"
|
val expected = Downloader.downloadString(asset.sha512)?.let { Regex("(?i)\\b[0-9a-f]{128}\\b").find(it)?.value }
|
||||||
|
?: return "Could not read the release checksum; try again"
|
||||||
|
expected.equals(Hashes.sha512(archive), ignoreCase = true)
|
||||||
}
|
}
|
||||||
|
else -> {
|
||||||
|
archive.delete()
|
||||||
|
return "${tool.name} ${asset.tag} publishes no checksum; nothing was installed"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!verified) {
|
||||||
|
archive.delete()
|
||||||
|
return "Checksum mismatch; the download was deleted"
|
||||||
}
|
}
|
||||||
|
|
||||||
if (SessionState.running) return "A session started during the download; stop it before installing compatibility tools"
|
if (SessionState.running) return "A session started during the download; stop it before installing compatibility tools"
|
||||||
@@ -170,6 +182,7 @@ object ProtonExtras {
|
|||||||
release.optString("tag_name"), name,
|
release.optString("tag_name"), name,
|
||||||
archive.optString("browser_download_url").takeIf { it.startsWith("http") } ?: continue, checksum,
|
archive.optString("browser_download_url").takeIf { it.startsWith("http") } ?: continue, checksum,
|
||||||
archive.optLong("size", 0L),
|
archive.optLong("size", 0L),
|
||||||
|
Hashes.githubSha256(archive.optString("digest")),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
null
|
null
|
||||||
@@ -179,19 +192,6 @@ object ProtonExtras {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun sha512(file: File): String {
|
|
||||||
val digest = MessageDigest.getInstance("SHA-512")
|
|
||||||
file.inputStream().buffered().use { input ->
|
|
||||||
val buffer = ByteArray(4 * 1024 * 1024)
|
|
||||||
while (true) {
|
|
||||||
val read = input.read(buffer)
|
|
||||||
if (read < 0) break
|
|
||||||
digest.update(buffer, 0, read)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return digest.digest().joinToString("") { "%02x".format(it.toInt() and 0xff) }
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun requestLines(context: Context): List<String> =
|
private fun requestLines(context: Context): List<String> =
|
||||||
FileUtils.readString(requests(context))?.lines()?.filter { it.isNotBlank() } ?: emptyList()
|
FileUtils.readString(requests(context))?.lines()?.filter { it.isNotBlank() } ?: emptyList()
|
||||||
}
|
}
|
||||||
@@ -57,6 +57,7 @@ import java.util.Locale
|
|||||||
*/
|
*/
|
||||||
class SessionService : Service() {
|
class SessionService : Service() {
|
||||||
private val components = java.util.concurrent.CopyOnWriteArrayList<SessionPart>()
|
private val components = java.util.concurrent.CopyOnWriteArrayList<SessionPart>()
|
||||||
|
private val stopLock = Any()
|
||||||
private var wakeLock: PowerManager.WakeLock? = null
|
private var wakeLock: PowerManager.WakeLock? = null
|
||||||
private var wifiLock: WifiManager.WifiLock? = null
|
private var wifiLock: WifiManager.WifiLock? = null
|
||||||
private var sessionPid = -1
|
private var sessionPid = -1
|
||||||
@@ -84,7 +85,7 @@ class SessionService : Service() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
/** Counts sessions this service has started; a process exit from an earlier one is ignored. */
|
/** Counts sessions this service has started; a process exit from an earlier one is ignored. */
|
||||||
private var sessionGen = 0
|
@Volatile private var sessionGen = 0
|
||||||
|
|
||||||
override fun onCreate() {
|
override fun onCreate() {
|
||||||
super.onCreate()
|
super.onCreate()
|
||||||
@@ -263,150 +264,17 @@ class SessionService : Service() {
|
|||||||
killStragglers()
|
killStragglers()
|
||||||
SessionFiles.stage(this, root)
|
SessionFiles.stage(this, root)
|
||||||
|
|
||||||
// One folder per session, claimed by whoever started first - the activity starts the
|
val sessionDir = openSessionFolder()
|
||||||
// compositor before this service runs - so the compositor's log lands in the same place.
|
|
||||||
val sessionDir = SessionPaths.beginOrCurrent(this)
|
|
||||||
val sessionLog = File(sessionDir, "session.log")
|
val sessionLog = File(sessionDir, "session.log")
|
||||||
SessionState.logFile = sessionLog
|
|
||||||
SessionState.logDirectory = sessionDir
|
|
||||||
SessionState.sessionId = sessionDir.name
|
|
||||||
SessionState.eventsFile = File(sessionDir, "events.jsonl")
|
|
||||||
SessionEvents.record("session.logs_ready", mapOf("logDir" to sessionDir.path))
|
|
||||||
// Written first, so a session that dies in its first second still says what it ran on.
|
|
||||||
DeviceReport.write(this, File(sessionDir, "device.txt"), SessionState.mode)
|
|
||||||
NetworkReport.write(this, File(sessionDir, "network.txt"))
|
|
||||||
// Everything the app decides from here on - the driver it chose, the audio line, a rival
|
|
||||||
// client stopped, the exit status - reaches logcat and nowhere a user can get at. Mirror it.
|
|
||||||
SessionLogCapture.start(File(sessionDir, "app.log"))
|
|
||||||
|
|
||||||
val size = SessionState.outputSize
|
val size = SessionState.outputSize
|
||||||
val guest = ArrayList<String>()
|
val guest = ArrayList<String>()
|
||||||
guest.add("/usr/bin/env")
|
|
||||||
guest.add("-i")
|
|
||||||
guest.add("HOME=/root")
|
|
||||||
guest.add("USER=root")
|
|
||||||
guest.add("PATH=/usr/local/bin:/usr/bin:/bin")
|
|
||||||
guest.add("TERM=xterm-256color")
|
|
||||||
guest.add("LANG=C.UTF-8")
|
|
||||||
// Without this the session is UTC: the client's clock, its logs and every timestamp in a
|
|
||||||
// session bundle sit hours off the device's. Bannerlator carries the same line.
|
|
||||||
guest.add("TZ=" + java.util.TimeZone.getDefault().id)
|
|
||||||
guest.add("XDG_RUNTIME_DIR=" + runtimeDir.path)
|
|
||||||
guest.add("XDG_SESSION_TYPE=wayland")
|
|
||||||
guest.add("WAYLAND_DISPLAY=wayland-0")
|
|
||||||
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")
|
|
||||||
guest.add("GALLIUM_DRIVER=zink")
|
|
||||||
guest.add("LIBGL_KOPPER_DRI2=true")
|
|
||||||
LinuxRuntime.vulkanIcd(this)?.let { guest.add("VK_ICD_FILENAMES=" + it.path) }
|
|
||||||
// An imported glibc Turnip for this mode, when the user chose one: the session script checks
|
|
||||||
// the manifest and its library from inside and points the loader at it with VK_DRIVER_FILES,
|
|
||||||
// so the runtime's own driver above stays untouched and is what a bad import falls back to.
|
|
||||||
// A program from the rail is one of the desktop's emulators, so it draws with the desktop's
|
|
||||||
// Linux driver, not the Steam session's: the driver's shader cache is keyed on the driver
|
|
||||||
// build, and with two drivers every emulator compiled its shaders twice - once per way of
|
|
||||||
// starting it (RPCS3's 6650 interpreter variants on each first boot).
|
|
||||||
val driverMode = if (SessionState.mode == MODE_RUN) MODE_DESKTOP else SessionPrefs.prefMode(SessionState.mode)
|
|
||||||
val linuxDriverId = SessionPrefs.linuxDriver(this, driverMode)
|
|
||||||
LinuxVulkanDriver.resolveIcdPath(this, linuxDriverId)
|
|
||||||
?.let { guest.add(LinuxVulkanDriver.ENV + "=" + it) }
|
|
||||||
// Turnip's own debug switches, for the runtime's driver and everything on it. The file in
|
|
||||||
// Downloads holds the value verbatim ("sysmem", "sysmem,deck_emu"); with nothing there, an
|
|
||||||
// imported driver from the A710/A720/A722 legs gets "sysmem" on its own, which is what both
|
|
||||||
// its authors advise for those GPUs and what nothing else in the list needs.
|
|
||||||
tuDebug(linuxDriverId)?.let { guest.add("TU_DEBUG=$it") }
|
|
||||||
// Zink renders the client's UI (Chromium -> ANGLE -> Zink -> Turnip). Lazy descriptors is
|
|
||||||
// the mode Zink recommends where the driver has no descriptor buffer, and what Ludashi ships
|
|
||||||
// by default for its Zink path; a switch here because on one Fold the menus run at 14 fps.
|
|
||||||
if (SessionPrefs.zinkLazy(this)) guest.add("ZINK_DESCRIPTORS=lazy")
|
|
||||||
// The rest of the client-interface switches (SessionPrefs): GL marshalled off the calling
|
|
||||||
// thread, no GL error checks, and the client run as SteamOS runs it (the script reads
|
|
||||||
// BL_STEAMDECK; it is the one that builds the command line).
|
|
||||||
if (SessionPrefs.glThread(this)) guest.add("mesa_glthread=true")
|
|
||||||
if (SessionPrefs.noGlError(this)) guest.add("MESA_NO_ERROR=1")
|
|
||||||
if (SessionState.mode == MODE_STEAM) guest.add("BL_STEAMDECK=" + (if (SessionPrefs.steamDeckMode(this)) "1" else "0"))
|
|
||||||
// The desktop's Steam launchers start the client there (bannerlator-steam-launch), through the
|
// The desktop's Steam launchers start the client there (bannerlator-steam-launch), through the
|
||||||
// same set-up as a Steam session: it gets what the client and its games are started with.
|
// same set-up as a Steam session: it gets what the client and its games are started with.
|
||||||
val steamHere = SessionState.mode == MODE_STEAM || SessionState.mode == MODE_DESKTOP
|
val steamHere = SessionState.mode == MODE_STEAM || SessionState.mode == MODE_DESKTOP
|
||||||
if (steamHere) guest.add("BL_STEAM_CHANNEL=" + SessionPrefs.steamChannel(this))
|
addClientEnvironment(guest, runtimeDir, steamHere)
|
||||||
if (SessionState.mode == MODE_STEAM) {
|
|
||||||
guest.add("BL_GAMESCOPE_FORCE_FULLSCREEN=" + (if (SessionPrefs.forceFullscreen(this)) "1" else "0"))
|
|
||||||
SessionPrefs.writeForceFullscreenFlag(this)
|
|
||||||
}
|
|
||||||
// Proton's own gate for its xalia helper (its `proton` script reads this, and sets
|
|
||||||
// XALIA_SUPPORTED_ONLY itself otherwise). Off by default: xalia is Valve's, and on a device
|
|
||||||
// whose seccomp answers its syscalls normally there is no reason to take it away.
|
|
||||||
if (SessionPrefs.noXalia(this)) guest.add("PROTON_USE_XALIA=0")
|
|
||||||
// The FEXCore preset for the x86 games the client launches: its FEX_* variables go in
|
|
||||||
// here, before the script, so every game process inherits them from the client. The
|
|
||||||
// default preset sets nothing, which is what every session ran on before.
|
|
||||||
if (steamHere) {
|
|
||||||
val preset = SessionPrefs.fexPreset(this)
|
|
||||||
val vars = com.droiddeck.launcher.core.FexPreset.env(preset)
|
|
||||||
vars.forEach { guest.add(it) }
|
|
||||||
if (vars.isNotEmpty()) Log.i(TAG, "fex preset $preset: ${vars.joinToString(" ")}")
|
|
||||||
}
|
|
||||||
// Anything else, for a device that cannot be reached with a debugger: Downloads/droiddeck-env
|
|
||||||
// holds KEY=VALUE lines that go into the session's environment as written, after ours, so a
|
|
||||||
// line here wins. Zink and Turnip tunables (ZINK_DESCRIPTORS=lazy, MESA_*), gamescope's,
|
|
||||||
// the client's - whatever the experiment needs, without a build per attempt.
|
|
||||||
extraEnv().forEach { guest.add(it) }
|
|
||||||
// Core masks, Bannerlator's two (cfca3912). The client's is sent whenever the override is
|
|
||||||
// on, even naming every core: it exists to undo the pin Steam applies to its own interface
|
|
||||||
// renderer, and the scheduler's default is exactly what that pin takes away. A game's is
|
|
||||||
// sent only when it is a real restriction - a game has no pin of its own to undo.
|
|
||||||
if (steamHere && SessionPrefs.clientCpusOverride(this)) {
|
|
||||||
guest.add("BL_CLIENT_CPUS=" + CpuCores.listOrAll(SessionPrefs.clientCpus(this)))
|
|
||||||
}
|
|
||||||
// The game cores also pin the desktop and a program from the rail; without a choice the
|
|
||||||
// session script picks every core but the slowest cluster for those (program_cores).
|
|
||||||
CpuCores.restrictionOrEmpty(SessionPrefs.gameCpus(this))
|
|
||||||
.takeIf { it.isNotEmpty() }?.let { guest.add("BL_GAME_CPUS=$it") }
|
|
||||||
|
|
||||||
// PulseAudio always: the client is a native Linux program and has no other way to make a
|
val pulse = startAudio(guest, sessionDir)
|
||||||
// sound - its menus, its music and its voice chat all go through here. DirectAudio is not
|
|
||||||
// an alternative to it on this path: it replaces the audio driver INSIDE Wine, so it
|
|
||||||
// changes what games do and leaves the client alone. The microphone is its own opt-in on
|
|
||||||
// top, and the helper only opens an input stream when asked - so a user who wants game
|
|
||||||
// sound but no recording gets exactly that, and Android's recording indicator stays off.
|
|
||||||
val wantsDirectAudio = SessionState.mode == MODE_STEAM && SessionPrefs.directAudio(this)
|
|
||||||
val wantsMic = SessionPrefs.micEnabled(this) &&
|
|
||||||
checkSelfPermission(android.Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED
|
|
||||||
// Both paths sit under the app's files directory, which the session binds at its own path,
|
|
||||||
// so the same string is valid on both sides and nothing has to be translated.
|
|
||||||
val audioDir = File(filesDir, "directaudio").apply { mkdirs() }
|
|
||||||
val relaySocket = File(audioDir, "relay.sock")
|
|
||||||
val micFifo = if (wantsMic) File(audioDir, "mic.fifo") else null
|
|
||||||
|
|
||||||
val audioLog = File(sessionDir, "audio.log")
|
|
||||||
val pulse = PulseAudioComponent(this, micFifo?.absolutePath)
|
|
||||||
// With DirectAudio on, the client's own sound goes through the relay too: the daemon
|
|
||||||
// fills the relay's ring and the relay, outside proot, drives the device.
|
|
||||||
// The client's own sound: the classic AAudio sink unless the user chose the relay.
|
|
||||||
val clientDirectAudio = SessionState.mode == MODE_STEAM && SessionPrefs.clientDirectAudio(this)
|
|
||||||
if (clientDirectAudio) pulse.setRelaySocket(relaySocket.absolutePath)
|
|
||||||
pulse.setLogFile(audioLog)
|
|
||||||
pulse.attach(this)
|
|
||||||
guest.add("PULSE_SERVER=unix:" + pulse.socket().absolutePath)
|
|
||||||
components.add(pulse)
|
|
||||||
if (wantsDirectAudio || wantsMic || clientDirectAudio) {
|
|
||||||
// After the daemon in the list, so it can wait for the pipe the daemon makes.
|
|
||||||
val relay = DirectAudioRelayComponent(relaySocket, micFifo)
|
|
||||||
relay.setLogFile(audioLog)
|
|
||||||
relay.attach(this)
|
|
||||||
components.add(relay)
|
|
||||||
}
|
|
||||||
if (wantsDirectAudio) {
|
|
||||||
// Read by the Proton wrappers, which point Wine at the driver and name it in the
|
|
||||||
// prefix. Absent, they take an early return and the game uses Proton's own audio - so
|
|
||||||
// this variable is the whole of the selection.
|
|
||||||
guest.add("BL_DIRECTAUDIO=/" + SessionFiles.DIRECTAUDIO_DIR)
|
|
||||||
guest.add("BANNER_AUDIO_DIRECT_RELAY=" + relaySocket.absolutePath)
|
|
||||||
}
|
|
||||||
Log.i(TAG, "audio: client " + (if (clientDirectAudio) "DirectAudio" else "classic AAudio sink") + (if (wantsDirectAudio) " + DirectAudio for games" else "")
|
|
||||||
+ (if (wantsMic) " + microphone" else "") +
|
|
||||||
(if (SessionPrefs.micEnabled(this) && !wantsMic) " (microphone wanted but RECORD_AUDIO not granted)" else ""))
|
|
||||||
|
|
||||||
guest.add("BL_WIDTH=" + size.first)
|
guest.add("BL_WIDTH=" + size.first)
|
||||||
guest.add("BL_HEIGHT=" + size.second)
|
guest.add("BL_HEIGHT=" + size.second)
|
||||||
@@ -424,28 +292,7 @@ class SessionService : Service() {
|
|||||||
|
|
||||||
val fakeInputDir = File(sessionRoot, "dev/input").apply { mkdirs() }
|
val fakeInputDir = File(sessionRoot, "dev/input").apply { mkdirs() }
|
||||||
val controllersOn = !File(Environment.getExternalStorageDirectory(), NO_PAD_SWITCH).exists()
|
val controllersOn = !File(Environment.getExternalStorageDirectory(), NO_PAD_SWITCH).exists()
|
||||||
if (controllersOn) {
|
if (controllersOn) addControllerEnvironment(guest, fakeInputDir)
|
||||||
FakeInputWriter.prepareRingSlots(fakeInputDir, 4)
|
|
||||||
guest.add("FAKE_EVDEV_DIR=" + fakeInputDir.path)
|
|
||||||
val rings = FakeInputWriter.getRingEnv(fakeInputDir)
|
|
||||||
if (!rings.isNullOrEmpty()) guest.add("FAKE_EVDEV_MEMFD_PATHS=$rings")
|
|
||||||
// SDL and Steam key their mapping database on bus+vendor+product: only a known
|
|
||||||
// identity gets the standard layout without the user configuring the pad by hand.
|
|
||||||
guest.add("FAKE_EVDEV_IDENTITY=xbox360")
|
|
||||||
guest.add("FAKE_EVDEV_VIBRATION=1")
|
|
||||||
// Steam Input's virtual-gamepad identity is for games the client starts, which are
|
|
||||||
// meant to see that pad. Everywhere else (the desktop, a program from the rail) it
|
|
||||||
// hides the pad: SDL ignores a Steam virtual gamepad unless it runs under Steam, so
|
|
||||||
// every SDL emulator came up with no controller. There it is a plain Xbox 360 pad.
|
|
||||||
if (SessionState.mode == MODE_STEAM) guest.add("FAKE_EVDEV_STEAM_VIRTUAL=1")
|
|
||||||
guest.add("SDL_JOYSTICK_DISABLE_UDEV=1")
|
|
||||||
guest.add("SDL_HIDAPI_JOYSTICK_DISABLE_UDEV=1")
|
|
||||||
guest.add("SDL_JOYSTICK_HIDAPI=0")
|
|
||||||
if (File(Environment.getExternalStorageDirectory(), PAD_LOG_SWITCH).exists()) {
|
|
||||||
guest.add("FAKE_EVDEV_LOG=1")
|
|
||||||
}
|
|
||||||
SessionState.fakeInputDir = fakeInputDir
|
|
||||||
}
|
|
||||||
// The desktop is wlroots (labwc). Stock wlroots allocates through gbm on a real DRM render
|
// The desktop is wlroots (labwc). Stock wlroots allocates through gbm on a real DRM render
|
||||||
// node, and ours is a KGSL stand-in - labwc died at "unable to create allocator" - so the
|
// node, and ours is a KGSL stand-in - labwc died at "unable to create allocator" - so the
|
||||||
// default is pixman (software, shm), where a Vulkan program cannot draw at all; those run
|
// default is pixman (software, shm), where a Vulkan program cannot draw at all; those run
|
||||||
@@ -506,6 +353,282 @@ class SessionService : Service() {
|
|||||||
// whatever a session leaves behind. The client abandons tens of megabytes of streams a run.
|
// whatever a session leaves behind. The client abandons tens of megabytes of streams a run.
|
||||||
FileUtils.clear(File(cacheDir, "shm"))
|
FileUtils.clear(File(cacheDir, "shm"))
|
||||||
|
|
||||||
|
val binds = sessionBinds(controllersOn, fakeInputDir)
|
||||||
|
|
||||||
|
val command = LinuxRuntime.command(
|
||||||
|
this, sessionRoot, runtimeDir, Environment.getExternalStorageDirectory(), binds, guest,
|
||||||
|
)
|
||||||
|
|
||||||
|
val hostEnv = HostEnvironment()
|
||||||
|
hostEnv["PROOT_LOADER"] = LinuxRuntime.prootLoader(this).path
|
||||||
|
hostEnv["PROOT_TMP_DIR"] = cacheDir.path
|
||||||
|
// proot links against a libtalloc beside it, and Android's linker does not search an
|
||||||
|
// executable's own directory: unnamed, the process dies before it starts and says so only
|
||||||
|
// in `logcat -b crash`.
|
||||||
|
// proot reads this itself, so it belongs in proot's own environment rather than the guest's.
|
||||||
|
if (SessionPrefs.prootNoSeccomp(this)) {
|
||||||
|
hostEnv["PROOT_NO_SECCOMP"] = "1"
|
||||||
|
Log.i(TAG, "proot: seccomp acceleration off by request")
|
||||||
|
}
|
||||||
|
val prootLibs = LinuxRuntime.prootLibraryPath(this)
|
||||||
|
if (prootLibs.isNotEmpty()) hostEnv["LD_LIBRARY_PATH"] = prootLibs
|
||||||
|
|
||||||
|
val terminalCommand = LinuxRuntime.command(
|
||||||
|
this, sessionRoot, runtimeDir, Environment.getExternalStorageDirectory(), binds, shellGuest,
|
||||||
|
)
|
||||||
|
val terminalHostEnvironment = LinkedHashMap(System.getenv())
|
||||||
|
hostEnv.asArray().forEach { entry ->
|
||||||
|
val separator = entry.indexOf('=')
|
||||||
|
if (separator > 0) terminalHostEnvironment[entry.substring(0, separator)] = entry.substring(separator + 1)
|
||||||
|
}
|
||||||
|
if (gen == sessionGen && SessionState.running) {
|
||||||
|
SessionTerminal.prepare(terminalCommand, terminalHostEnvironment.map { (key, value) -> "$key=$value" }.toTypedArray(), root, gen)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Whether the client signs in to Valve or starts offline: read once, while it starts, and
|
||||||
|
// rewritten by the client when it exits, so it is set again here at every session start.
|
||||||
|
if (SessionState.mode == MODE_STEAM || SessionState.mode == MODE_DESKTOP) OfflineMode.apply(this, root)
|
||||||
|
|
||||||
|
val networkLink = LinuxNetworkLinkComponent(this, root)
|
||||||
|
networkLink.attach(this)
|
||||||
|
networkLink.publish()
|
||||||
|
components.add(networkLink)
|
||||||
|
if (gen != sessionGen || !SessionState.running) {
|
||||||
|
Log.i(TAG, "session stopped while it was starting; not launching it")
|
||||||
|
if (gen == sessionGen) components.clear()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
components.forEach { it.start() }
|
||||||
|
|
||||||
|
val line = command.joinToString(" ") {
|
||||||
|
it.replace("\\", "\\\\").replace(" ", "\\ ")
|
||||||
|
}
|
||||||
|
watchLaunchRequests(sessionRoot)
|
||||||
|
// One session replacing another (the desktop's Steam launchers): the old proot is killed
|
||||||
|
// by the teardown a second after the new one has started, and its exit used to arrive
|
||||||
|
// here as "session ended: 137" and end the NEW session. An exit belongs to the session
|
||||||
|
// that started it.
|
||||||
|
val pid = HostProcess.start(line, hostEnv.asArray(), root, { status ->
|
||||||
|
if (gen != sessionGen) {
|
||||||
|
Log.i(TAG, "an earlier session's process ended ($status); the current one carries on")
|
||||||
|
return@start
|
||||||
|
}
|
||||||
|
Log.i(TAG, "session ended: $status")
|
||||||
|
stopSession(status ?: -1)
|
||||||
|
}, null)
|
||||||
|
Log.i(TAG, "session pid $pid, log ${sessionLog.path}")
|
||||||
|
if (gen != sessionGen || !SessionState.running) {
|
||||||
|
Log.i(TAG, "session stopped while its guest was starting; taking it down")
|
||||||
|
if (gen == sessionGen) {
|
||||||
|
launchWatcher?.stopWatching()
|
||||||
|
launchWatcher = null
|
||||||
|
components.reversed().forEach { runCatching { it.stop() } }
|
||||||
|
components.clear()
|
||||||
|
}
|
||||||
|
if (pid > 1) Thread({ teardown(pid) }, "session-teardown").start()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
sessionPid = pid
|
||||||
|
if (pid > 1) {
|
||||||
|
SessionEvents.guestStarted(pid)
|
||||||
|
} else {
|
||||||
|
SessionEvents.record("guest.start_failed", mapOf("pid" to pid))
|
||||||
|
SessionEvents.fail("GUEST_START_FAILED", "The guest process could not be started", pid)
|
||||||
|
stopSession(-1)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (gen == sessionGen && SessionState.running) {
|
||||||
|
suspendController = SessionSuspendController(
|
||||||
|
sessionRoot = { sessionPid },
|
||||||
|
helperRoots = { components.mapNotNull { it.suspendPid().takeIf { pid -> pid > 1 } } },
|
||||||
|
suspendAudio = {
|
||||||
|
if (!pulse.setSinkSuspended(true)) Log.w(TAG, "could not suspend audio sink")
|
||||||
|
},
|
||||||
|
resumeAudio = {
|
||||||
|
if (!pulse.setSinkSuspended(false)) Log.w(TAG, "could not resume audio sink")
|
||||||
|
},
|
||||||
|
)
|
||||||
|
mainHandler.post { updateSuspendPolicy() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The session's own log folder, opened and filled with what is known before anything starts. */
|
||||||
|
private fun openSessionFolder(): File {
|
||||||
|
// One folder per session, claimed by whoever started first - the activity starts the
|
||||||
|
// compositor before this service runs - so the compositor's log lands in the same place.
|
||||||
|
val sessionDir = SessionPaths.beginOrCurrent(this)
|
||||||
|
val sessionLog = File(sessionDir, "session.log")
|
||||||
|
SessionState.logFile = sessionLog
|
||||||
|
SessionState.logDirectory = sessionDir
|
||||||
|
SessionState.sessionId = sessionDir.name
|
||||||
|
SessionState.eventsFile = File(sessionDir, "events.jsonl")
|
||||||
|
SessionEvents.record("session.logs_ready", mapOf("logDir" to sessionDir.path))
|
||||||
|
// Written first, so a session that dies in its first second still says what it ran on.
|
||||||
|
DeviceReport.write(this, File(sessionDir, "device.txt"), SessionState.mode)
|
||||||
|
NetworkReport.write(this, File(sessionDir, "network.txt"))
|
||||||
|
// Everything the app decides from here on - the driver it chose, the audio line, a rival
|
||||||
|
// client stopped, the exit status - reaches logcat and nowhere a user can get at. Mirror it.
|
||||||
|
SessionLogCapture.start(File(sessionDir, "app.log"))
|
||||||
|
return sessionDir
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The guest's base environment: paths, the display, the GL/Vulkan stack and the client's switches. */
|
||||||
|
private fun addClientEnvironment(guest: MutableList<String>, runtimeDir: File, steamHere: Boolean) {
|
||||||
|
guest.add("/usr/bin/env")
|
||||||
|
guest.add("-i")
|
||||||
|
guest.add("HOME=/root")
|
||||||
|
guest.add("USER=root")
|
||||||
|
guest.add("PATH=/usr/local/bin:/usr/bin:/bin")
|
||||||
|
guest.add("TERM=xterm-256color")
|
||||||
|
guest.add("LANG=C.UTF-8")
|
||||||
|
// Without this the session is UTC: the client's clock, its logs and every timestamp in a
|
||||||
|
// session bundle sit hours off the device's. Bannerlator carries the same line.
|
||||||
|
guest.add("TZ=" + java.util.TimeZone.getDefault().id)
|
||||||
|
guest.add("XDG_RUNTIME_DIR=" + runtimeDir.path)
|
||||||
|
guest.add("XDG_SESSION_TYPE=wayland")
|
||||||
|
guest.add("WAYLAND_DISPLAY=wayland-0")
|
||||||
|
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")
|
||||||
|
guest.add("GALLIUM_DRIVER=zink")
|
||||||
|
guest.add("LIBGL_KOPPER_DRI2=true")
|
||||||
|
LinuxRuntime.vulkanIcd(this)?.let { guest.add("VK_ICD_FILENAMES=" + it.path) }
|
||||||
|
// An imported glibc Turnip for this mode, when the user chose one: the session script checks
|
||||||
|
// the manifest and its library from inside and points the loader at it with VK_DRIVER_FILES,
|
||||||
|
// so the runtime's own driver above stays untouched and is what a bad import falls back to.
|
||||||
|
// A program from the rail is one of the desktop's emulators, so it draws with the desktop's
|
||||||
|
// Linux driver, not the Steam session's: the driver's shader cache is keyed on the driver
|
||||||
|
// build, and with two drivers every emulator compiled its shaders twice - once per way of
|
||||||
|
// starting it (RPCS3's 6650 interpreter variants on each first boot).
|
||||||
|
val driverMode = if (SessionState.mode == MODE_RUN) MODE_DESKTOP else SessionPrefs.prefMode(SessionState.mode)
|
||||||
|
val linuxDriverId = SessionPrefs.linuxDriver(this, driverMode)
|
||||||
|
LinuxVulkanDriver.resolveIcdPath(this, linuxDriverId)
|
||||||
|
?.let { guest.add(LinuxVulkanDriver.ENV + "=" + it) }
|
||||||
|
// Turnip's own debug switches, for the runtime's driver and everything on it. The file in
|
||||||
|
// Downloads holds the value verbatim ("sysmem", "sysmem,deck_emu"); with nothing there, an
|
||||||
|
// imported driver from the A710/A720/A722 legs gets "sysmem" on its own, which is what both
|
||||||
|
// its authors advise for those GPUs and what nothing else in the list needs.
|
||||||
|
tuDebug(linuxDriverId)?.let { guest.add("TU_DEBUG=$it") }
|
||||||
|
// Zink renders the client's UI (Chromium -> ANGLE -> Zink -> Turnip). Lazy descriptors is
|
||||||
|
// the mode Zink recommends where the driver has no descriptor buffer, and what Ludashi ships
|
||||||
|
// by default for its Zink path; a switch here because on one Fold the menus run at 14 fps.
|
||||||
|
if (SessionPrefs.zinkLazy(this)) guest.add("ZINK_DESCRIPTORS=lazy")
|
||||||
|
// The rest of the client-interface switches (SessionPrefs): GL marshalled off the calling
|
||||||
|
// thread, no GL error checks, and the client run as SteamOS runs it (the script reads
|
||||||
|
// BL_STEAMDECK; it is the one that builds the command line).
|
||||||
|
if (SessionPrefs.glThread(this)) guest.add("mesa_glthread=true")
|
||||||
|
if (SessionPrefs.noGlError(this)) guest.add("MESA_NO_ERROR=1")
|
||||||
|
if (SessionState.mode == MODE_STEAM) guest.add("BL_STEAMDECK=" + (if (SessionPrefs.steamDeckMode(this)) "1" else "0"))
|
||||||
|
if (steamHere) guest.add("BL_STEAM_CHANNEL=" + SessionPrefs.steamChannel(this))
|
||||||
|
if (SessionState.mode == MODE_STEAM) {
|
||||||
|
guest.add("BL_GAMESCOPE_FORCE_FULLSCREEN=" + (if (SessionPrefs.forceFullscreen(this)) "1" else "0"))
|
||||||
|
SessionPrefs.writeForceFullscreenFlag(this)
|
||||||
|
}
|
||||||
|
// Proton's own gate for its xalia helper (its `proton` script reads this, and sets
|
||||||
|
// XALIA_SUPPORTED_ONLY itself otherwise). Off by default: xalia is Valve's, and on a device
|
||||||
|
// whose seccomp answers its syscalls normally there is no reason to take it away.
|
||||||
|
if (SessionPrefs.noXalia(this)) guest.add("PROTON_USE_XALIA=0")
|
||||||
|
// The FEXCore preset for the x86 games the client launches: its FEX_* variables go in
|
||||||
|
// here, before the script, so every game process inherits them from the client. The
|
||||||
|
// default preset sets nothing, which is what every session ran on before.
|
||||||
|
if (steamHere) {
|
||||||
|
val preset = SessionPrefs.fexPreset(this)
|
||||||
|
val vars = com.droiddeck.launcher.core.FexPreset.env(preset)
|
||||||
|
vars.forEach { guest.add(it) }
|
||||||
|
if (vars.isNotEmpty()) Log.i(TAG, "fex preset $preset: ${vars.joinToString(" ")}")
|
||||||
|
}
|
||||||
|
// Anything else, for a device that cannot be reached with a debugger: Downloads/droiddeck-env
|
||||||
|
// holds KEY=VALUE lines that go into the session's environment as written, after ours, so a
|
||||||
|
// line here wins. Zink and Turnip tunables (ZINK_DESCRIPTORS=lazy, MESA_*), gamescope's,
|
||||||
|
// the client's - whatever the experiment needs, without a build per attempt.
|
||||||
|
extraEnv().forEach { guest.add(it) }
|
||||||
|
// Core masks, Bannerlator's two (cfca3912). The client's is sent whenever the override is
|
||||||
|
// on, even naming every core: it exists to undo the pin Steam applies to its own interface
|
||||||
|
// renderer, and the scheduler's default is exactly what that pin takes away. A game's is
|
||||||
|
// sent only when it is a real restriction - a game has no pin of its own to undo.
|
||||||
|
if (steamHere && SessionPrefs.clientCpusOverride(this)) {
|
||||||
|
guest.add("BL_CLIENT_CPUS=" + CpuCores.listOrAll(SessionPrefs.clientCpus(this)))
|
||||||
|
}
|
||||||
|
// The game cores also pin the desktop and a program from the rail; without a choice the
|
||||||
|
// session script picks every core but the slowest cluster for those (program_cores).
|
||||||
|
CpuCores.restrictionOrEmpty(SessionPrefs.gameCpus(this))
|
||||||
|
.takeIf { it.isNotEmpty() }?.let { guest.add("BL_GAME_CPUS=$it") }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** PulseAudio, and the DirectAudio relay when a path needs it; returns the daemon for suspend and resume. */
|
||||||
|
private fun startAudio(guest: MutableList<String>, sessionDir: File): PulseAudioComponent {
|
||||||
|
// PulseAudio always: the client is a native Linux program and has no other way to make a
|
||||||
|
// sound - its menus, its music and its voice chat all go through here. DirectAudio is not
|
||||||
|
// an alternative to it on this path: it replaces the audio driver INSIDE Wine, so it
|
||||||
|
// changes what games do and leaves the client alone. The microphone is its own opt-in on
|
||||||
|
// top, and the helper only opens an input stream when asked - so a user who wants game
|
||||||
|
// sound but no recording gets exactly that, and Android's recording indicator stays off.
|
||||||
|
val wantsDirectAudio = SessionState.mode == MODE_STEAM && SessionPrefs.directAudio(this)
|
||||||
|
val wantsMic = SessionPrefs.micEnabled(this) &&
|
||||||
|
checkSelfPermission(android.Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED
|
||||||
|
// Both paths sit under the app's files directory, which the session binds at its own path,
|
||||||
|
// so the same string is valid on both sides and nothing has to be translated.
|
||||||
|
val audioDir = File(filesDir, "directaudio").apply { mkdirs() }
|
||||||
|
val relaySocket = File(audioDir, "relay.sock")
|
||||||
|
val micFifo = if (wantsMic) File(audioDir, "mic.fifo") else null
|
||||||
|
|
||||||
|
val audioLog = File(sessionDir, "audio.log")
|
||||||
|
val pulse = PulseAudioComponent(this, micFifo?.absolutePath)
|
||||||
|
// With DirectAudio on, the client's own sound goes through the relay too: the daemon
|
||||||
|
// fills the relay's ring and the relay, outside proot, drives the device.
|
||||||
|
// The client's own sound: the classic AAudio sink unless the user chose the relay.
|
||||||
|
val clientDirectAudio = SessionState.mode == MODE_STEAM && SessionPrefs.clientDirectAudio(this)
|
||||||
|
if (clientDirectAudio) pulse.setRelaySocket(relaySocket.absolutePath)
|
||||||
|
pulse.setLogFile(audioLog)
|
||||||
|
pulse.attach(this)
|
||||||
|
guest.add("PULSE_SERVER=unix:" + pulse.socket().absolutePath)
|
||||||
|
components.add(pulse)
|
||||||
|
if (wantsDirectAudio || wantsMic || clientDirectAudio) {
|
||||||
|
// After the daemon in the list, so it can wait for the pipe the daemon makes.
|
||||||
|
val relay = DirectAudioRelayComponent(relaySocket, micFifo)
|
||||||
|
relay.setLogFile(audioLog)
|
||||||
|
relay.attach(this)
|
||||||
|
components.add(relay)
|
||||||
|
}
|
||||||
|
if (wantsDirectAudio) {
|
||||||
|
// Read by the Proton wrappers, which point Wine at the driver and name it in the
|
||||||
|
// prefix. Absent, they take an early return and the game uses Proton's own audio - so
|
||||||
|
// this variable is the whole of the selection.
|
||||||
|
guest.add("BL_DIRECTAUDIO=/" + SessionFiles.DIRECTAUDIO_DIR)
|
||||||
|
guest.add("BANNER_AUDIO_DIRECT_RELAY=" + relaySocket.absolutePath)
|
||||||
|
}
|
||||||
|
Log.i(TAG, "audio: client " + (if (clientDirectAudio) "DirectAudio" else "classic AAudio sink") + (if (wantsDirectAudio) " + DirectAudio for games" else "")
|
||||||
|
+ (if (wantsMic) " + microphone" else "") +
|
||||||
|
(if (SessionPrefs.micEnabled(this) && !wantsMic) " (microphone wanted but RECORD_AUDIO not granted)" else ""))
|
||||||
|
return pulse
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The fake evdev pads: the ring files the app writes and the identity SDL and Steam see. */
|
||||||
|
private fun addControllerEnvironment(guest: MutableList<String>, fakeInputDir: File) {
|
||||||
|
FakeInputWriter.prepareRingSlots(fakeInputDir, 4)
|
||||||
|
guest.add("FAKE_EVDEV_DIR=" + fakeInputDir.path)
|
||||||
|
val rings = FakeInputWriter.getRingEnv(fakeInputDir)
|
||||||
|
if (!rings.isNullOrEmpty()) guest.add("FAKE_EVDEV_MEMFD_PATHS=$rings")
|
||||||
|
// SDL and Steam key their mapping database on bus+vendor+product: only a known
|
||||||
|
// identity gets the standard layout without the user configuring the pad by hand.
|
||||||
|
guest.add("FAKE_EVDEV_IDENTITY=xbox360")
|
||||||
|
guest.add("FAKE_EVDEV_VIBRATION=1")
|
||||||
|
// Steam Input's virtual-gamepad identity is for games the client starts, which are
|
||||||
|
// meant to see that pad. Everywhere else (the desktop, a program from the rail) it
|
||||||
|
// hides the pad: SDL ignores a Steam virtual gamepad unless it runs under Steam, so
|
||||||
|
// every SDL emulator came up with no controller. There it is a plain Xbox 360 pad.
|
||||||
|
if (SessionState.mode == MODE_STEAM) guest.add("FAKE_EVDEV_STEAM_VIRTUAL=1")
|
||||||
|
guest.add("SDL_JOYSTICK_DISABLE_UDEV=1")
|
||||||
|
guest.add("SDL_HIDAPI_JOYSTICK_DISABLE_UDEV=1")
|
||||||
|
guest.add("SDL_JOYSTICK_HIDAPI=0")
|
||||||
|
if (File(Environment.getExternalStorageDirectory(), PAD_LOG_SWITCH).exists()) {
|
||||||
|
guest.add("FAKE_EVDEV_LOG=1")
|
||||||
|
}
|
||||||
|
SessionState.fakeInputDir = fakeInputDir
|
||||||
|
}
|
||||||
|
|
||||||
|
/** What proot binds into the guest: the pads, the battery, storage, the game library, added games and ROMs. */
|
||||||
|
private fun sessionBinds(controllersOn: Boolean, fakeInputDir: File): ArrayList<String> {
|
||||||
val binds = ArrayList<String>()
|
val binds = ArrayList<String>()
|
||||||
if (controllersOn) binds.add(fakeInputDir.path + ":/dev/input")
|
if (controllersOn) binds.add(fakeInputDir.path + ":/dev/input")
|
||||||
// The client's battery readout (the Quick Access Menu, the top bar) reads
|
// The client's battery readout (the Quick Access Menu, the top bar) reads
|
||||||
@@ -563,85 +686,7 @@ class SessionService : Service() {
|
|||||||
} else if (roms != null) {
|
} else if (roms != null) {
|
||||||
Log.w(TAG, "roms: $roms is not a readable folder; /root/ROMs not offered this session")
|
Log.w(TAG, "roms: $roms is not a readable folder; /root/ROMs not offered this session")
|
||||||
}
|
}
|
||||||
|
return binds
|
||||||
val command = LinuxRuntime.command(
|
|
||||||
this, sessionRoot, runtimeDir, Environment.getExternalStorageDirectory(), binds, guest,
|
|
||||||
)
|
|
||||||
|
|
||||||
val hostEnv = HostEnvironment()
|
|
||||||
hostEnv["PROOT_LOADER"] = LinuxRuntime.prootLoader(this).path
|
|
||||||
hostEnv["PROOT_TMP_DIR"] = cacheDir.path
|
|
||||||
// proot links against a libtalloc beside it, and Android's linker does not search an
|
|
||||||
// executable's own directory: unnamed, the process dies before it starts and says so only
|
|
||||||
// in `logcat -b crash`.
|
|
||||||
// proot reads this itself, so it belongs in proot's own environment rather than the guest's.
|
|
||||||
if (SessionPrefs.prootNoSeccomp(this)) {
|
|
||||||
hostEnv["PROOT_NO_SECCOMP"] = "1"
|
|
||||||
Log.i(TAG, "proot: seccomp acceleration off by request")
|
|
||||||
}
|
|
||||||
val prootLibs = LinuxRuntime.prootLibraryPath(this)
|
|
||||||
if (prootLibs.isNotEmpty()) hostEnv["LD_LIBRARY_PATH"] = prootLibs
|
|
||||||
|
|
||||||
val terminalCommand = LinuxRuntime.command(
|
|
||||||
this, sessionRoot, runtimeDir, Environment.getExternalStorageDirectory(), binds, shellGuest,
|
|
||||||
)
|
|
||||||
val terminalHostEnvironment = LinkedHashMap(System.getenv())
|
|
||||||
hostEnv.asArray().forEach { entry ->
|
|
||||||
val separator = entry.indexOf('=')
|
|
||||||
if (separator > 0) terminalHostEnvironment[entry.substring(0, separator)] = entry.substring(separator + 1)
|
|
||||||
}
|
|
||||||
if (gen == sessionGen && SessionState.running) {
|
|
||||||
SessionTerminal.prepare(terminalCommand, terminalHostEnvironment.map { (key, value) -> "$key=$value" }.toTypedArray(), root, gen)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Whether the client signs in to Valve or starts offline: read once, while it starts, and
|
|
||||||
// rewritten by the client when it exits, so it is set again here at every session start.
|
|
||||||
if (SessionState.mode == MODE_STEAM || SessionState.mode == MODE_DESKTOP) OfflineMode.apply(this, root)
|
|
||||||
|
|
||||||
val networkLink = LinuxNetworkLinkComponent(this, root)
|
|
||||||
networkLink.attach(this)
|
|
||||||
networkLink.publish()
|
|
||||||
components.add(networkLink)
|
|
||||||
components.forEach { it.start() }
|
|
||||||
|
|
||||||
val line = command.joinToString(" ") {
|
|
||||||
it.replace("\\", "\\\\").replace(" ", "\\ ")
|
|
||||||
}
|
|
||||||
watchLaunchRequests(sessionRoot)
|
|
||||||
// One session replacing another (the desktop's Steam launchers): the old proot is killed
|
|
||||||
// by the teardown a second after the new one has started, and its exit used to arrive
|
|
||||||
// here as "session ended: 137" and end the NEW session. An exit belongs to the session
|
|
||||||
// that started it.
|
|
||||||
sessionPid = HostProcess.start(line, hostEnv.asArray(), root, { status ->
|
|
||||||
if (gen != sessionGen) {
|
|
||||||
Log.i(TAG, "an earlier session's process ended ($status); the current one carries on")
|
|
||||||
return@start
|
|
||||||
}
|
|
||||||
Log.i(TAG, "session ended: $status")
|
|
||||||
stopSession(status ?: -1)
|
|
||||||
}, null)
|
|
||||||
Log.i(TAG, "session pid $sessionPid, log ${sessionLog.path}")
|
|
||||||
if (gen == sessionGen && SessionState.running && sessionPid > 1) {
|
|
||||||
SessionEvents.guestStarted(sessionPid)
|
|
||||||
} else if (gen == sessionGen && SessionState.running) {
|
|
||||||
SessionEvents.record("guest.start_failed", mapOf("pid" to sessionPid))
|
|
||||||
SessionEvents.fail("GUEST_START_FAILED", "The guest process could not be started", sessionPid)
|
|
||||||
stopSession(-1)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if (gen == sessionGen && SessionState.running) {
|
|
||||||
suspendController = SessionSuspendController(
|
|
||||||
sessionRoot = { sessionPid },
|
|
||||||
helperRoots = { components.mapNotNull { it.suspendPid().takeIf { pid -> pid > 1 } } },
|
|
||||||
suspendAudio = {
|
|
||||||
if (!pulse.setSinkSuspended(true)) Log.w(TAG, "could not suspend audio sink")
|
|
||||||
},
|
|
||||||
resumeAudio = {
|
|
||||||
if (!pulse.setSinkSuspended(false)) Log.w(TAG, "could not resume audio sink")
|
|
||||||
},
|
|
||||||
)
|
|
||||||
mainHandler.post { updateSuspendPolicy() }
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun teardown(prootPid: Int, expectedStartTime: Long? = null) {
|
private fun teardown(prootPid: Int, expectedStartTime: Long? = null) {
|
||||||
@@ -714,6 +759,30 @@ class SessionService : Service() {
|
|||||||
* behind, still holding the Wayland socket and the audio server the next session needs. They
|
* behind, still holding the Wayland socket and the audio server the next session needs. They
|
||||||
* are our uid, so they are ours to kill.
|
* are our uid, so they are ours to kill.
|
||||||
*/
|
*/
|
||||||
|
/**
|
||||||
|
* Every process of ours still running a program out of the Linux runtime once proot is gone.
|
||||||
|
* proot's --kill-on-exit and the tree sweep only reach what proot still traces; a tracee it
|
||||||
|
* lost - an Xwayland that aborted from one thread and then looped on a syscall proot's own
|
||||||
|
* seccomp filter, with no tracer left, answers ENOSYS - survives both, reparented to init,
|
||||||
|
* and wrote 9 GB of one line into the session log before anything killed it.
|
||||||
|
*/
|
||||||
|
private fun killGuestLeftovers() {
|
||||||
|
val me = android.os.Process.myPid()
|
||||||
|
val rootfs = try { File(filesDir, "linuxfs").canonicalPath } catch (e: Exception) { return } + "/"
|
||||||
|
val procs = File("/proc").listFiles { f -> f.name.all { it.isDigit() } } ?: return
|
||||||
|
var killed = 0
|
||||||
|
for (proc in procs) {
|
||||||
|
val pid = proc.name.toIntOrNull() ?: continue
|
||||||
|
if (pid == me) continue
|
||||||
|
// Another uid's exe is not ours to read; a process already gone has none.
|
||||||
|
val exe = try { File(proc, "exe").canonicalPath } catch (e: Exception) { continue }
|
||||||
|
if (!exe.startsWith(rootfs)) continue
|
||||||
|
android.os.Process.killProcess(pid)
|
||||||
|
killed++
|
||||||
|
}
|
||||||
|
if (killed > 0) Log.w(TAG, "killed $killed guest process(es) proot no longer tracked")
|
||||||
|
}
|
||||||
|
|
||||||
private fun killStragglers() {
|
private fun killStragglers() {
|
||||||
val me = android.os.Process.myPid()
|
val me = android.os.Process.myPid()
|
||||||
val procs = File("/proc").listFiles { f -> f.name.all { it.isDigit() } } ?: return
|
val procs = File("/proc").listFiles { f -> f.name.all { it.isDigit() } } ?: return
|
||||||
@@ -826,8 +895,12 @@ class SessionService : Service() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun finishSessionStop(status: Int) {
|
private fun finishSessionStop(status: Int, stoppedGen: Int) {
|
||||||
mainHandler.post {
|
mainHandler.post {
|
||||||
|
if (stoppedGen != sessionGen || SessionState.running) {
|
||||||
|
Log.i(TAG, "session $stoppedGen finished stopping after a new one started")
|
||||||
|
return@post
|
||||||
|
}
|
||||||
SessionState.suspended = false
|
SessionState.suspended = false
|
||||||
SessionState.guestPid = -1
|
SessionState.guestPid = -1
|
||||||
releaseLocks()
|
releaseLocks()
|
||||||
@@ -846,8 +919,11 @@ class SessionService : Service() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private fun stopSession(status: Int) {
|
private fun stopSession(status: Int) {
|
||||||
if (!SessionState.running) return
|
synchronized(stopLock) {
|
||||||
SessionState.running = false
|
if (!SessionState.running) return
|
||||||
|
SessionState.running = false
|
||||||
|
}
|
||||||
|
val stoppedGen = sessionGen
|
||||||
SessionState.stopRequested = false
|
SessionState.stopRequested = false
|
||||||
SessionEvents.record("guest.exited", mapOf("status" to status))
|
SessionEvents.record("guest.exited", mapOf("status" to status))
|
||||||
SessionEvents.transition(SessionPhase.STOPPING, "session.stopping", mapOf("status" to status))
|
SessionEvents.transition(SessionPhase.STOPPING, "session.stopping", mapOf("status" to status))
|
||||||
@@ -890,10 +966,11 @@ class SessionService : Service() {
|
|||||||
Thread({
|
Thread({
|
||||||
auxiliary.forEach { (pid, started) -> teardown(pid, started) }
|
auxiliary.forEach { (pid, started) -> teardown(pid, started) }
|
||||||
if (prootPid > 1) teardown(prootPid)
|
if (prootPid > 1) teardown(prootPid)
|
||||||
finishSessionStop(status)
|
killGuestLeftovers()
|
||||||
|
finishSessionStop(status, stoppedGen)
|
||||||
}, "session-teardown").start()
|
}, "session-teardown").start()
|
||||||
} else {
|
} else {
|
||||||
finishSessionStop(status)
|
finishSessionStop(status, stoppedGen)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (prootPid > 1) acquireLocks()
|
if (prootPid > 1) acquireLocks()
|
||||||
@@ -1075,6 +1152,10 @@ class SessionService : Service() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fun stop(context: Context) {
|
fun stop(context: Context) {
|
||||||
|
if (!SessionState.running) {
|
||||||
|
SessionState.stopRequested = true
|
||||||
|
return
|
||||||
|
}
|
||||||
context.startService(Intent(context, SessionService::class.java).setAction(ACTION_STOP))
|
context.startService(Intent(context, SessionService::class.java).setAction(ACTION_STOP))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -325,7 +325,7 @@ private fun SmallButton(text: String, enabled: Boolean = true, accent: Boolean =
|
|||||||
val hot = (src.collectIsFocusedAsState().value || src.collectIsHoveredAsState().value) && enabled
|
val hot = (src.collectIsFocusedAsState().value || src.collectIsHoveredAsState().value) && enabled
|
||||||
Box(
|
Box(
|
||||||
contentAlignment = Alignment.Center,
|
contentAlignment = Alignment.Center,
|
||||||
modifier = modifier.heightIn(min = 40.dp).clip(RoundedCornerShape(10.dp))
|
modifier = modifier.heightIn(min = 44.dp).clip(RoundedCornerShape(10.dp))
|
||||||
.background(if (hot) pal.signal else colors.surfaceVariant)
|
.background(if (hot) pal.signal else colors.surfaceVariant)
|
||||||
.border(2.dp, if (hot) colors.onBackground else pal.line2, RoundedCornerShape(10.dp))
|
.border(2.dp, if (hot) colors.onBackground else pal.line2, RoundedCornerShape(10.dp))
|
||||||
.hoverable(src).clickable(interactionSource = src, indication = null, enabled = enabled, onClick = onClick)
|
.hoverable(src).clickable(interactionSource = src, indication = null, enabled = enabled, onClick = onClick)
|
||||||
|
|||||||
@@ -41,12 +41,12 @@ fun ColumnScope.ControllerRows(host: MenuHost, oscMode: String, c: ControllerPre
|
|||||||
oscMode, note = "Auto shows all controls without a controller. Steam + QAM shows only those buttons.", onPick = a.onOsc,
|
oscMode, note = "Auto shows all controls without a controller. Steam + QAM shows only those buttons.", onPick = a.onOsc,
|
||||||
)
|
)
|
||||||
val tintOpen = host.open == "controller-tint"
|
val tintOpen = host.open == "controller-tint"
|
||||||
SettingsRow("Colour", "Tint of the on-screen buttons", highlighted = tintOpen) {
|
SettingsRow("Color", "Tint of the on-screen buttons", highlighted = tintOpen) {
|
||||||
Box {
|
Box {
|
||||||
ValueChip(ControllerPrefs.tints.firstOrNull { it.first == c.tint }?.second ?: "Custom", tintOpen) {
|
ValueChip(ControllerPrefs.tints.firstOrNull { it.first == c.tint }?.second ?: "Custom", tintOpen) {
|
||||||
host.open = if (tintOpen) null else "controller-tint"
|
host.open = if (tintOpen) null else "controller-tint"
|
||||||
}
|
}
|
||||||
AnchoredMenu(tintOpen, onDismiss = { if (host.open == "controller-tint") host.open = null }, title = "Colour") { firstItemFocus ->
|
AnchoredMenu(tintOpen, onDismiss = { if (host.open == "controller-tint") host.open = null }, title = "Color") { firstItemFocus ->
|
||||||
ControllerPrefs.tints.forEachIndexed { index, (color, name) ->
|
ControllerPrefs.tints.forEachIndexed { index, (color, name) ->
|
||||||
MenuItem(name, checked = c.tint == color, leading = { Swatch(color) }, focusRequester = if (index == 0) firstItemFocus else null) {
|
MenuItem(name, checked = c.tint == color, leading = { Swatch(color) }, focusRequester = if (index == 0) firstItemFocus else null) {
|
||||||
a.onTint(color)
|
a.onTint(color)
|
||||||
@@ -59,7 +59,7 @@ fun ColumnScope.ControllerRows(host: MenuHost, oscMode: String, c: ControllerPre
|
|||||||
ChoiceRow(host, "controller-opacity", "Opacity", null, ControllerPrefs.opacities.map { it to "$it%" }, c.opacity, onPick = a.onOpacity)
|
ChoiceRow(host, "controller-opacity", "Opacity", null, ControllerPrefs.opacities.map { it to "$it%" }, c.opacity, onPick = a.onOpacity)
|
||||||
ChoiceRow(host, "controller-size", "Button size", "100% keeps the standard size", ControllerPrefs.sizes.map { it to "$it%" }, c.size, onPick = a.onSize)
|
ChoiceRow(host, "controller-size", "Button size", "100% keeps the standard size", ControllerPrefs.sizes.map { it to "$it%" }, c.size, onPick = a.onSize)
|
||||||
ToggleRow(host, "controller-stick-click", "Stick click", "Double-tap a stick and hold for L3 or R3", c.stickClick, onChange = a.onStickClick)
|
ToggleRow(host, "controller-stick-click", "Stick click", "Double-tap a stick and hold for L3 or R3", c.stickClick, onChange = a.onStickClick)
|
||||||
ToggleRow(host, "controller-adaptive", "Adaptive sticks", "A stick centres where your thumb lands and returns home when you let go", c.adaptiveSticks, onChange = a.onAdaptiveSticks)
|
ToggleRow(host, "controller-adaptive", "Adaptive sticks", "A stick centers where your thumb lands and returns home when you let go", c.adaptiveSticks, onChange = a.onAdaptiveSticks)
|
||||||
SettingsRow("Layout", if (c.customLayout) "Custom positions saved" else "Placed for this screen's size and your grip") {
|
SettingsRow("Layout", if (c.customLayout) "Custom positions saved" else "Placed for this screen's size and your grip") {
|
||||||
Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) {
|
Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||||
SecondaryButton("Edit") { a.onEditLayout() }
|
SecondaryButton("Edit") { a.onEditLayout() }
|
||||||
@@ -68,7 +68,7 @@ fun ColumnScope.ControllerRows(host: MenuHost, oscMode: String, c: ControllerPre
|
|||||||
}
|
}
|
||||||
val remapped = c.mapping.count { (id, target) -> id != target }
|
val remapped = c.mapping.count { (id, target) -> id != target }
|
||||||
ActionRow("Button mapping", if (remapped == 0) "Every button sends its own input" else "$remapped of ${c.mapping.size} buttons remapped", "Configure", a.onMapping)
|
ActionRow("Button mapping", if (remapped == 0) "Every button sends its own input" else "$remapped of ${c.mapping.size} buttons remapped", "Configure", a.onMapping)
|
||||||
ActionRow("Reset controller", "Restore the default colour, opacity, size, stick behaviour, mapping and layout", "Reset", a.onResetAll)
|
ActionRow("Reset controller", "Restore the default color, opacity, size, stick behavior, mapping and layout", "Reset", a.onResetAll)
|
||||||
}
|
}
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
|
|||||||
@@ -0,0 +1,22 @@
|
|||||||
|
package com.droiddeck.launcher.ui
|
||||||
|
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import com.droiddeck.launcher.gpu.FrameGen
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The frame generation picker, anchored to whatever opened it (host key "fg"). One copy for Setup,
|
||||||
|
* a game's launch settings and the session drawer, so they say the same thing.
|
||||||
|
*/
|
||||||
|
@Composable
|
||||||
|
internal fun FrameGenMenu(
|
||||||
|
host: MenuHost, engine: String, multiplier: Int, lsfgReady: Boolean,
|
||||||
|
onPick: (engine: String, multiplier: Int) -> Unit,
|
||||||
|
) {
|
||||||
|
AnchoredMenu(host.open == "fg", onDismiss = { if (host.open == "fg") host.open = null }, title = "Frame generation") { firstItemFocus ->
|
||||||
|
val need = if (lsfgReady) null else "Needs Lossless Scaling installed in Steam"
|
||||||
|
fun pick(e: String, m: Int) { onPick(e, m); host.open = null }
|
||||||
|
MenuItem("Off", checked = engine == FrameGen.ENGINE_OFF, focusRequester = firstItemFocus) { pick(FrameGen.ENGINE_OFF, 2) }
|
||||||
|
for (m in 2..4) MenuItem(FrameGen.label(FrameGen.ENGINE_WINFG, m), checked = engine == FrameGen.ENGINE_WINFG && multiplier == m) { pick(FrameGen.ENGINE_WINFG, m) }
|
||||||
|
for (m in 2..4) MenuItem(FrameGen.label(FrameGen.ENGINE_LSFG, m), checked = engine == FrameGen.ENGINE_LSFG && multiplier == m, enabled = lsfgReady, detail = need) { pick(FrameGen.ENGINE_LSFG, m) }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,186 @@
|
|||||||
|
package com.droiddeck.launcher.ui
|
||||||
|
|
||||||
|
import android.graphics.Bitmap
|
||||||
|
import androidx.compose.animation.animateColorAsState
|
||||||
|
import androidx.compose.animation.core.Animatable
|
||||||
|
import androidx.compose.animation.core.Spring
|
||||||
|
import androidx.compose.animation.core.animateFloatAsState
|
||||||
|
import androidx.compose.foundation.ExperimentalFoundationApi
|
||||||
|
import androidx.compose.foundation.Image
|
||||||
|
import androidx.compose.foundation.LocalIndication
|
||||||
|
import androidx.compose.foundation.background
|
||||||
|
import androidx.compose.foundation.border
|
||||||
|
import androidx.compose.foundation.clickable
|
||||||
|
import androidx.compose.foundation.hoverable
|
||||||
|
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||||
|
import androidx.compose.foundation.interaction.collectIsPressedAsState
|
||||||
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
|
import androidx.compose.foundation.layout.Box
|
||||||
|
import androidx.compose.foundation.layout.BoxWithConstraints
|
||||||
|
import androidx.compose.runtime.key
|
||||||
|
import androidx.compose.foundation.layout.Column
|
||||||
|
import androidx.compose.foundation.layout.Row
|
||||||
|
import androidx.compose.foundation.layout.Spacer
|
||||||
|
import androidx.compose.foundation.layout.aspectRatio
|
||||||
|
import androidx.compose.foundation.layout.fillMaxSize
|
||||||
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
|
import androidx.compose.foundation.layout.height
|
||||||
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.foundation.layout.size
|
||||||
|
import androidx.compose.foundation.layout.width
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.LaunchedEffect
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.mutableStateOf
|
||||||
|
import androidx.compose.runtime.remember
|
||||||
|
import kotlinx.coroutines.flow.first
|
||||||
|
import androidx.compose.runtime.setValue
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.draw.alpha
|
||||||
|
import androidx.compose.ui.draw.blur
|
||||||
|
import androidx.compose.ui.draw.clip
|
||||||
|
import androidx.compose.ui.graphics.Brush
|
||||||
|
import androidx.compose.ui.graphics.Color
|
||||||
|
import androidx.compose.ui.graphics.asImageBitmap
|
||||||
|
import androidx.compose.ui.graphics.graphicsLayer
|
||||||
|
import androidx.compose.ui.layout.ContentScale
|
||||||
|
import androidx.compose.ui.res.painterResource
|
||||||
|
import androidx.compose.ui.semantics.contentDescription
|
||||||
|
import androidx.compose.ui.text.font.FontWeight
|
||||||
|
import androidx.compose.ui.text.style.TextOverflow
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import androidx.compose.ui.unit.sp
|
||||||
|
import androidx.compose.ui.zIndex
|
||||||
|
import coil.compose.AsyncImage
|
||||||
|
import java.io.File
|
||||||
|
|
||||||
|
// Cover art: posters, the art grid and its tiles.
|
||||||
|
|
||||||
|
internal class Tile(
|
||||||
|
val title: String, val sub: String?, val art: File?, val key: String,
|
||||||
|
val iconRes: Int? = null, val dim: Boolean = false, val iconBitmap: Bitmap? = null,
|
||||||
|
val showFooter: Boolean = true,
|
||||||
|
val onClick: () -> Unit,
|
||||||
|
)
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
internal fun Poster(art: File?, name: String, modifier: Modifier) {
|
||||||
|
val colors = MaterialTheme.colorScheme
|
||||||
|
val t = remember { Animatable(0f) }
|
||||||
|
LaunchedEffect(Unit) { t.animateTo(1f, Motion.sp(0.6f, Spring.StiffnessLow)) }
|
||||||
|
Box(
|
||||||
|
modifier = modifier.padding(start = 16.dp).aspectRatio(2f / 3f)
|
||||||
|
.graphicsLayer { alpha = t.value; translationY = (1f - t.value) * 16.dp.toPx(); rotationZ = (1f - t.value) * 2f; scaleX = 0.94f + 0.06f * t.value; scaleY = scaleX; shadowElevation = 22.dp.toPx(); shape = Shape12; clip = false }
|
||||||
|
.clip(Shape12).background(artBrush(hueOf(name))),
|
||||||
|
) {
|
||||||
|
if (art != null) CoverImage(art, Modifier.fillMaxSize())
|
||||||
|
else Text(name, fontSize = 12.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, modifier = Modifier.align(Alignment.BottomStart).padding(8.dp), maxLines = 3, overflow = TextOverflow.Ellipsis)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@OptIn(ExperimentalFoundationApi::class)
|
||||||
|
@Composable
|
||||||
|
internal fun ArtGrid(tiles: List<Tile>, wide: Boolean = false) {
|
||||||
|
val square = tiles.isNotEmpty() && tiles.all { it.art == null && (it.iconRes != null || it.iconBitmap != null) }
|
||||||
|
// Big enough to recognise a game by its art and read its name under it; icon tiles are squares.
|
||||||
|
val minSize = if (square) 76.dp else if (wide) 120.dp else 96.dp
|
||||||
|
val gap = 12.dp
|
||||||
|
// Laid out whole, not lazily: the pad's focus search only finds tiles that exist, and a lazy
|
||||||
|
// grid composes only the rows on screen, so a press towards the next row bounced back among
|
||||||
|
// the visible tiles. A few hundred tiles lay out fine; the page's scroll follows the focused one.
|
||||||
|
BoxWithConstraints(modifier = Modifier.fillMaxWidth()) {
|
||||||
|
val avail = maxWidth - 8.dp
|
||||||
|
val cols = ((avail + gap) / (minSize + gap)).toInt().coerceAtLeast(1)
|
||||||
|
val tileWidth = (avail - gap * (cols - 1)) / cols
|
||||||
|
Column(modifier = Modifier.fillMaxWidth().padding(top = 16.dp, bottom = 14.dp, start = 4.dp, end = 4.dp)) {
|
||||||
|
for (row in tiles.chunked(cols)) {
|
||||||
|
Row(horizontalArrangement = Arrangement.spacedBy(gap), modifier = Modifier.fillMaxWidth().padding(bottom = gap)) {
|
||||||
|
for (t in row) key(t.key) {
|
||||||
|
val src = remember { MutableInteractionSource() }
|
||||||
|
val hot = rememberHot(src)
|
||||||
|
val track = Modifier.paneItem("tile:" + t.key).then(if (t === tiles.first()) Modifier.firstTile() else Modifier)
|
||||||
|
Box(modifier = Modifier.width(tileWidth).zIndex(if (hot) 1f else 0f)) { GameTile(t, wide, square, src, hot, track) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun GameTile(t: Tile, wide: Boolean, square: Boolean, src: MutableInteractionSource, hot: Boolean, track: Modifier) {
|
||||||
|
val colors = MaterialTheme.colorScheme
|
||||||
|
val pressed by src.collectIsPressedAsState()
|
||||||
|
val scale by animateFloatAsState(if (pressed) 0.97f else if (hot) 1.04f else 1f, Motion.sp(0.55f, Spring.StiffnessMedium), label = "tileScale")
|
||||||
|
val lift by animateFloatAsState(if (hot) -5f else 0f, Motion.sp(0.6f), label = "tileLift")
|
||||||
|
val elev by animateFloatAsState(if (hot) 18f else 2f, Motion.tw(300), label = "tileElev")
|
||||||
|
val pal = LocalPalette.current
|
||||||
|
val ring by animateColorAsState(if (hot) pal.signal else Color.Transparent, Motion.tw(220), label = "tileRing")
|
||||||
|
Column(
|
||||||
|
modifier = track
|
||||||
|
.graphicsLayer { scaleX = scale; scaleY = scale; translationY = lift.dp.toPx(); shadowElevation = elev.dp.toPx(); shape = Shape12; clip = false; ambientShadowColor = if (hot) pal.signal else Color.Black; spotShadowColor = if (hot) pal.signal else Color.Black; transformOrigin = androidx.compose.ui.graphics.TransformOrigin(0.5f, 0.9f) }
|
||||||
|
.clip(Shape12)
|
||||||
|
.background(colors.surface)
|
||||||
|
.border(2.5.dp, ring, Shape12)
|
||||||
|
.alpha(if (t.dim && !hot) 0.55f else 1f)
|
||||||
|
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, onClick = t.onClick),
|
||||||
|
) {
|
||||||
|
Box(modifier = Modifier.fillMaxWidth().shine(hot)) {
|
||||||
|
Art(t.art, t.iconRes, t.title, Modifier.fillMaxWidth(), wide, t.iconBitmap)
|
||||||
|
}
|
||||||
|
if (t.showFooter) {
|
||||||
|
Column(modifier = Modifier.padding(horizontal = 8.dp, vertical = 6.dp)) {
|
||||||
|
Text(t.title, fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||||
|
if (t.sub != null) Text(t.sub, fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Art for a portrait (2:3) tile. Box art fills it; wide art - a PS3 disc's ICON0, a game's header -
|
||||||
|
* is shown whole over a blurred, darkened copy of itself instead of losing its sides to the crop.
|
||||||
|
*/
|
||||||
|
@Composable
|
||||||
|
private fun CoverImage(art: File, modifier: Modifier) {
|
||||||
|
var wideArt by remember(art) { mutableStateOf(false) }
|
||||||
|
Box(modifier) {
|
||||||
|
if (wideArt) {
|
||||||
|
AsyncImage(
|
||||||
|
model = art, contentDescription = null, contentScale = ContentScale.Crop,
|
||||||
|
modifier = Modifier.fillMaxSize().graphicsLayer { scaleX = 1.2f; scaleY = 1.2f }.blur(14.dp),
|
||||||
|
)
|
||||||
|
Spacer(Modifier.fillMaxSize().background(Color.Black.copy(alpha = 0.45f)))
|
||||||
|
}
|
||||||
|
AsyncImage(
|
||||||
|
model = art, contentDescription = null,
|
||||||
|
contentScale = if (wideArt) ContentScale.Fit else ContentScale.Crop,
|
||||||
|
onSuccess = { state ->
|
||||||
|
val size = state.painter.intrinsicSize
|
||||||
|
if (size.width > size.height * 1.1f) wideArt = true
|
||||||
|
},
|
||||||
|
modifier = Modifier.fillMaxSize(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun Art(art: File?, iconRes: Int?, label: String, modifier: Modifier, wide: Boolean = false, iconBitmap: Bitmap? = null) {
|
||||||
|
val colors = MaterialTheme.colorScheme
|
||||||
|
val ratio = if (art == null && (iconRes != null || iconBitmap != null)) 1f else if (wide) 16f / 9f else 2f / 3f
|
||||||
|
Box(modifier = modifier.aspectRatio(ratio).background(if (art == null && iconRes == null && iconBitmap == null) artBrush(hueOf(label)) else Brush.linearGradient(listOf(colors.surfaceVariant, colors.surface)))) {
|
||||||
|
when {
|
||||||
|
art != null -> if (wide) AsyncImage(model = art, contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier.fillMaxSize())
|
||||||
|
else CoverImage(art, Modifier.fillMaxSize())
|
||||||
|
iconRes != null -> Image(painterResource(iconRes), null, contentScale = ContentScale.Fit, modifier = Modifier.fillMaxSize().padding(if (wide) 10.dp else 8.dp))
|
||||||
|
iconBitmap != null -> Image(bitmap = iconBitmap.asImageBitmap(), contentDescription = null, contentScale = ContentScale.Fit, modifier = Modifier.fillMaxSize().padding(8.dp))
|
||||||
|
else -> {
|
||||||
|
Spacer(Modifier.fillMaxSize().background(Brush.verticalGradient(0f to Color.Transparent, 0.45f to Color.Transparent, 1f to Color.Black.copy(alpha = 0.55f))))
|
||||||
|
Text(label, fontSize = 12.sp, fontWeight = FontWeight.Bold, color = Color.White.copy(alpha = 0.92f), modifier = Modifier.align(Alignment.BottomStart).padding(6.dp), maxLines = 3, overflow = TextOverflow.Ellipsis)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,409 @@
|
|||||||
|
package com.droiddeck.launcher.ui
|
||||||
|
|
||||||
|
import androidx.compose.runtime.CompositionLocalProvider
|
||||||
|
import android.os.Build
|
||||||
|
import androidx.compose.animation.AnimatedContent
|
||||||
|
import androidx.compose.animation.Crossfade
|
||||||
|
import androidx.compose.animation.core.Spring
|
||||||
|
import androidx.compose.animation.core.animateFloatAsState
|
||||||
|
import androidx.compose.animation.fadeIn
|
||||||
|
import androidx.compose.animation.fadeOut
|
||||||
|
import androidx.compose.animation.slideInVertically
|
||||||
|
import androidx.compose.animation.slideOutVertically
|
||||||
|
import androidx.compose.animation.togetherWith
|
||||||
|
import androidx.compose.foundation.Image
|
||||||
|
import androidx.compose.foundation.LocalIndication
|
||||||
|
import androidx.compose.foundation.background
|
||||||
|
import androidx.compose.foundation.border
|
||||||
|
import androidx.compose.foundation.clickable
|
||||||
|
import androidx.compose.foundation.hoverable
|
||||||
|
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||||
|
import androidx.compose.foundation.interaction.collectIsPressedAsState
|
||||||
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
|
import androidx.compose.foundation.layout.Box
|
||||||
|
import androidx.compose.foundation.layout.BoxWithConstraints
|
||||||
|
import androidx.compose.runtime.key
|
||||||
|
import androidx.compose.foundation.layout.Column
|
||||||
|
import androidx.compose.foundation.layout.IntrinsicSize
|
||||||
|
import androidx.compose.foundation.layout.Row
|
||||||
|
import androidx.compose.foundation.layout.Spacer
|
||||||
|
import androidx.compose.foundation.layout.fillMaxHeight
|
||||||
|
import androidx.compose.foundation.layout.fillMaxSize
|
||||||
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
|
import androidx.compose.foundation.layout.height
|
||||||
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.foundation.layout.size
|
||||||
|
import androidx.compose.foundation.layout.width
|
||||||
|
import androidx.compose.foundation.rememberScrollState
|
||||||
|
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||||
|
import androidx.compose.foundation.verticalScroll
|
||||||
|
import androidx.compose.material.icons.Icons
|
||||||
|
import androidx.compose.material.icons.outlined.DesktopWindows
|
||||||
|
import androidx.compose.material3.Icon
|
||||||
|
import androidx.compose.material3.LinearProgressIndicator
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.remember
|
||||||
|
import kotlinx.coroutines.flow.first
|
||||||
|
import androidx.compose.runtime.setValue
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.draw.alpha
|
||||||
|
import androidx.compose.ui.draw.blur
|
||||||
|
import androidx.compose.ui.draw.clip
|
||||||
|
import androidx.compose.ui.geometry.Offset
|
||||||
|
import androidx.compose.ui.graphics.Brush
|
||||||
|
import androidx.compose.ui.graphics.Color
|
||||||
|
import androidx.compose.ui.graphics.graphicsLayer
|
||||||
|
import androidx.compose.ui.layout.ContentScale
|
||||||
|
import androidx.compose.ui.platform.LocalConfiguration
|
||||||
|
import androidx.compose.ui.res.painterResource
|
||||||
|
import androidx.compose.ui.semantics.Role
|
||||||
|
import androidx.compose.ui.semantics.contentDescription
|
||||||
|
import androidx.compose.ui.text.font.FontWeight
|
||||||
|
import androidx.compose.ui.text.style.TextOverflow
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import androidx.compose.ui.unit.sp
|
||||||
|
import coil.compose.AsyncImage
|
||||||
|
import com.droiddeck.launcher.HomeApp
|
||||||
|
import com.droiddeck.launcher.frontend.Library
|
||||||
|
import java.io.File
|
||||||
|
|
||||||
|
// The front end's right-hand pane and the page it shows: backdrop, desktop card and emulators.
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
internal fun Pane(
|
||||||
|
s: FrontEndState, selected: String, a: FrontEndActions, page: (@Composable () -> Unit)?, modifier: Modifier,
|
||||||
|
onSelect: (String) -> Unit, onAndroidAppClick: (HomeApp.LaunchableApp) -> Unit,
|
||||||
|
onOpenDeveloperOptions: () -> Unit, onRequestWirelessAdb: (Boolean) -> Unit,
|
||||||
|
) {
|
||||||
|
BoxWithConstraints(modifier = modifier) {
|
||||||
|
CompositionLocalProvider(LocalNarrowPane provides (maxWidth < NarrowPaneWidth)) {
|
||||||
|
val backdropArt: File? = when {
|
||||||
|
s.pageKey != null && page != null -> null
|
||||||
|
selected.startsWith("app:") -> s.steamGames.firstOrNull { "app:${it.appId}" == selected }?.art
|
||||||
|
selected == "games" -> s.steamGames.maxByOrNull { it.lastPlayed }?.art
|
||||||
|
selected.startsWith("rom:") -> romFor(s, selected)?.second?.art
|
||||||
|
else -> null
|
||||||
|
}
|
||||||
|
Backdrop(backdropArt)
|
||||||
|
AnimatedContent(
|
||||||
|
// Picking another game changes the detail beside the list, not the whole page.
|
||||||
|
targetState = if (page != null && s.pageKey != null) s.pageKey else if (selected.startsWith("app:")) "games" else selected,
|
||||||
|
transitionSpec = {
|
||||||
|
(fadeIn(Motion.tw(300, 80)) + slideInVertically(Motion.tw(420, 80)) { it / 24 })
|
||||||
|
.togetherWith(fadeOut(Motion.tw(170)) + slideOutVertically(Motion.tw(170)) { -it / 40 })
|
||||||
|
.apply { targetContentZIndex = 1f }
|
||||||
|
},
|
||||||
|
label = "pane",
|
||||||
|
) { key ->
|
||||||
|
if (page != null && key == s.pageKey) page()
|
||||||
|
else Content(s, if (key == "games") selected else key, a, Modifier.fillMaxSize(), onSelect, onAndroidAppClick, onOpenDeveloperOptions, onRequestWirelessAdb)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun Backdrop(art: File?) {
|
||||||
|
val colors = MaterialTheme.colorScheme
|
||||||
|
val pal = LocalPalette.current
|
||||||
|
Crossfade(targetState = art, animationSpec = Motion.tw(700), label = "backdrop") { a ->
|
||||||
|
// A game's own art, blurred, where it has some; otherwise the plain ground with one quiet
|
||||||
|
// glow of the theme's signal colour - a colour per title hash read as noise.
|
||||||
|
if (a != null && Build.VERSION.SDK_INT >= 31) {
|
||||||
|
Box(modifier = Modifier.fillMaxSize().alpha(0.26f).blur(70.dp)) {
|
||||||
|
AsyncImage(model = a, contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier.fillMaxSize().graphicsLayer { scaleX = 1.5f; scaleY = 1.5f })
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Box(modifier = Modifier.fillMaxSize().background(Brush.radialGradient(listOf(pal.signal.copy(alpha = 0.07f), Color.Transparent), center = Offset.Zero, radius = 1400f)))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Spacer(Modifier.fillMaxSize().background(Brush.verticalGradient(listOf(Color.Transparent, colors.background.copy(alpha = 0.35f)))))
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun romFor(s: FrontEndState, selected: String): Pair<Library.Emulator, Library.Rom>? {
|
||||||
|
val parts = selected.split(":")
|
||||||
|
val e = s.emulators.firstOrNull { it.id == parts.getOrNull(1) } ?: return null
|
||||||
|
val g = e.games.getOrNull(parts.getOrNull(2)?.toIntOrNull() ?: -1) ?: return null
|
||||||
|
return e to g
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun Content(
|
||||||
|
s: FrontEndState, selected: String, a: FrontEndActions, modifier: Modifier,
|
||||||
|
onSelect: (String) -> Unit, onAndroidAppClick: (HomeApp.LaunchableApp) -> Unit,
|
||||||
|
onOpenDeveloperOptions: () -> Unit, onRequestWirelessAdb: (Boolean) -> Unit,
|
||||||
|
) {
|
||||||
|
val colors = MaterialTheme.colorScheme
|
||||||
|
val detailPosterWidth = if (LocalConfiguration.current.screenHeightDp < 600) 72.dp else 120.dp
|
||||||
|
val narrow = LocalNarrowPane.current
|
||||||
|
val padH = if (narrow) 16.dp else 22.dp
|
||||||
|
val padV = if (narrow) 12.dp else 18.dp
|
||||||
|
// Setup scrolls inside itself, under its tabs.
|
||||||
|
if (selected == "setup") {
|
||||||
|
Column(modifier = modifier.padding(horizontal = padH, vertical = padV)) {
|
||||||
|
SetupPanel(s, a, onOpenDeveloperOptions, onRequestWirelessAdb)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// Steam is a full-bleed wall of the library with Play over it.
|
||||||
|
if (selected == "steam") {
|
||||||
|
SteamHome(s, a, modifier)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// The Games tab lays out its own list and detail.
|
||||||
|
if (selected == "games" || selected.startsWith("app:")) {
|
||||||
|
GamesPage(s, a, selected, onSelect, modifier)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// Every other page scrolls as one - header, hero and grid - so a short screen reaches the grid
|
||||||
|
// instead of showing a sliver of it under a fixed hero. A focused tile scrolls itself into view.
|
||||||
|
Column(modifier = modifier.verticalScroll(rememberScrollState()).padding(horizontal = padH, vertical = padV)) {
|
||||||
|
when {
|
||||||
|
selected == "android-apps" && s.isHomeApp -> {
|
||||||
|
Rise(0) { PageHeader("Android apps") { Chip("${s.androidApps.size} apps", ok = false) } }
|
||||||
|
if (s.androidApps.isEmpty()) Rise(3) { Note("No launchable Android apps found.") }
|
||||||
|
else Rise(3, Modifier.fillMaxWidth()) {
|
||||||
|
ArtGrid(s.androidApps.map { app ->
|
||||||
|
Tile(
|
||||||
|
app.label,
|
||||||
|
null,
|
||||||
|
null,
|
||||||
|
"android:${app.packageName}",
|
||||||
|
onClick = { onAndroidAppClick(app) },
|
||||||
|
iconBitmap = app.icon,
|
||||||
|
)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
selected == "desktop" -> {
|
||||||
|
val installed = s.emulators.filter { it.installed }
|
||||||
|
val available = s.emulators.filter { !it.installed }
|
||||||
|
Rise(0) {
|
||||||
|
PageHeader("Desktop") {
|
||||||
|
if (s.desktopInstalled) Chip("● Desktop installed", ok = true) else Chip("Installs on first open", ok = false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Rise(2) { DesktopCard(s, a) }
|
||||||
|
if (installed.isNotEmpty()) {
|
||||||
|
Rise(3) { SectionTitle("Emulators", "${installed.size} installed") }
|
||||||
|
Rise(4) { EmulatorGrid(installed, first = true, onSelect = onSelect) }
|
||||||
|
}
|
||||||
|
if (available.isNotEmpty()) {
|
||||||
|
Rise(5) { SectionTitle("Available to install", available.size.toString()) }
|
||||||
|
Rise(6) { EmulatorGrid(available, first = installed.isEmpty(), onSelect = onSelect) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
selected.startsWith("emu:") -> {
|
||||||
|
val e = s.emulators.firstOrNull { "emu:${it.id}" == selected }
|
||||||
|
if (e == null) Note("Not installed.") else {
|
||||||
|
val pkgId = Library.packageId(e.id)
|
||||||
|
val pkg = pkgId?.let { id -> s.packages?.firstOrNull { it.id == id } }
|
||||||
|
Rise(0) {
|
||||||
|
BackLink("Desktop") { onSelect("desktop") }
|
||||||
|
}
|
||||||
|
Rise(1) {
|
||||||
|
Row(
|
||||||
|
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(14.dp),
|
||||||
|
modifier = Modifier.padding(top = 12.dp, bottom = 12.dp),
|
||||||
|
) {
|
||||||
|
Image(painterResource(e.iconRes), null, modifier = Modifier.size(52.dp))
|
||||||
|
Column {
|
||||||
|
Text(e.name, fontSize = if (narrow) 22.sp else 26.sp, fontWeight = FontWeight.Bold, color = colors.onBackground)
|
||||||
|
Text(
|
||||||
|
e.system.replaceFirstChar { it.uppercase() } + if (e.installed) "" else " · not installed",
|
||||||
|
fontSize = 14.sp, color = colors.onSurfaceVariant,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (e.installed) {
|
||||||
|
Rise(3) {
|
||||||
|
Actions {
|
||||||
|
PrimaryButton("Open ${e.name}", enabled = !s.busy, main = true) { a.onEmulator(e) }
|
||||||
|
BusyChip(s)
|
||||||
|
SecondaryButton("ROMs folder", onClick = a.onRoms)
|
||||||
|
if (pkg != null) SecondaryButton(
|
||||||
|
if (pkg.kind == "appimage") "Remove" else "Hide",
|
||||||
|
enabled = s.packageBusyId == null && !s.sessionRunning,
|
||||||
|
) { a.onRemovePackage(pkg.id) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Rise(4) { SectionTitle("Games", e.games.size.toString()) }
|
||||||
|
if (e.games.isEmpty()) Rise(5) {
|
||||||
|
Note(
|
||||||
|
if (s.romsDir == null) "Choose a ROMs folder."
|
||||||
|
else if (e.id == "retroarch") "Browse to /root/ROMs in RetroArch."
|
||||||
|
else "Add ${e.system} games to ROMs/${e.system.substringBefore(' ')}.",
|
||||||
|
)
|
||||||
|
}
|
||||||
|
else Rise(5, Modifier.fillMaxWidth()) {
|
||||||
|
ArtGrid(e.games.mapIndexed { index, g -> Tile(g.name, if (g.art != null) "installed" else g.hostPath.extension.uppercase().ifEmpty { "folder" }, g.art, "rom:${e.id}:$index", e.iconRes) { onSelect("rom:${e.id}:$index") } }, wide = e.games.none { it.art != null })
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if (pkg != null) Rise(2) {
|
||||||
|
Actions {
|
||||||
|
PrimaryButton(
|
||||||
|
if (s.packageBusyId == pkg.id) "Installing…" else "Install ${e.name}",
|
||||||
|
enabled = s.packageBusyId == null && s.ready && !s.packageCatalogLoading && !s.sessionRunning,
|
||||||
|
) { a.onInstallPackage(pkg.id) }
|
||||||
|
if (s.sessionRunning) ActionChip("Stop session to install", ok = false)
|
||||||
|
else if (!s.ready) ActionChip("Runtime required", ok = false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Rise(3) {
|
||||||
|
Box(Modifier.fillMaxWidth().padding(horizontal = 8.dp, vertical = 8.dp)) {
|
||||||
|
Note(when {
|
||||||
|
s.packageCatalogLoading -> "Loading install details…"
|
||||||
|
pkg == null -> "Install details are unavailable right now. Try again when the package catalog is reachable."
|
||||||
|
!s.ready -> "Install the Linux runtime from Setup before installing desktop apps."
|
||||||
|
s.sessionRunning -> "Stop the active session before installing desktop apps."
|
||||||
|
pkg.notes.isNotBlank() -> pkg.notes
|
||||||
|
else -> "Install ${e.name} into the Linux desktop runtime."
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (s.packageBusyId == pkg?.id) Rise(4) {
|
||||||
|
val stage = s.packageStage
|
||||||
|
Text(
|
||||||
|
if (stage != null && s.packagePercent >= 0) "$stage · ${s.packagePercent}%" else stage ?: "Starting…",
|
||||||
|
fontSize = 12.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(bottom = 6.dp),
|
||||||
|
)
|
||||||
|
if (s.packagePercent >= 0) LinearProgressIndicator(progress = { s.packagePercent / 100f }, modifier = Modifier.fillMaxWidth().height(4.dp))
|
||||||
|
else LinearProgressIndicator(modifier = Modifier.fillMaxWidth().height(4.dp))
|
||||||
|
}
|
||||||
|
if (pkg?.kind == "tar") Rise(5) { Note("Hiding this package takes it off Desktop; its files stay in the Linux runtime.") }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
selected.startsWith("rom:") -> {
|
||||||
|
val pair = romFor(s, selected)
|
||||||
|
if (pair == null) Note("That game is gone from the ROMs folder.") else {
|
||||||
|
val (e, g) = pair
|
||||||
|
Rise(0) {
|
||||||
|
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||||
|
BackLink(e.name) { onSelect("emu:${e.id}") }
|
||||||
|
Eyebrow("Desktop · ${e.system}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Rise(1) { Title(g.name) }
|
||||||
|
Rise(2) {
|
||||||
|
Row {
|
||||||
|
Column(modifier = Modifier.weight(1f)) {
|
||||||
|
Text(g.guestPath, fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.clip(RoundedCornerShape(8.dp)).background(colors.surface).padding(horizontal = 10.dp, vertical = 6.dp))
|
||||||
|
Spacer(Modifier.height(14.dp))
|
||||||
|
Actions {
|
||||||
|
Image(painterResource(e.iconRes), null, modifier = Modifier.size(40.dp))
|
||||||
|
PrimaryButton("Launch in ${e.name}", enabled = !s.busy, main = true) { a.onRom(g) }
|
||||||
|
if (s.busy) BusyChip(s) else ActionChip(g.hostPath.extension.uppercase().ifEmpty { "folder" }, ok = false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (g.art != null && !narrow) Poster(g.art, g.name, Modifier.width(detailPosterWidth))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val others = e.games.filter { it !== g }
|
||||||
|
if (others.isNotEmpty()) {
|
||||||
|
Rise(3) { SectionTitle("Also in ${e.name}", null) }
|
||||||
|
Rise(4, Modifier.fillMaxWidth()) {
|
||||||
|
ArtGrid(others.map { x ->
|
||||||
|
val index = e.games.indexOf(x)
|
||||||
|
Tile(x.name, if (x.art != null) "installed" else x.hostPath.extension.uppercase().ifEmpty { "folder" }, x.art, "rom:${e.id}:$index", e.iconRes) { onSelect("rom:${e.id}:$index") }
|
||||||
|
}, wide = others.none { it.art != null })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else -> Note("That page is gone. Pick a section on the left.")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The Linux desktop itself, above the emulators that run in it. */
|
||||||
|
@Composable
|
||||||
|
private fun DesktopCard(s: FrontEndState, a: FrontEndActions) {
|
||||||
|
val colors = MaterialTheme.colorScheme
|
||||||
|
val pal = LocalPalette.current
|
||||||
|
val narrow = LocalNarrowPane.current
|
||||||
|
val actions: @Composable () -> Unit = {
|
||||||
|
Actions {
|
||||||
|
// Enabled without a runtime or the desktop: the session's loading screen installs them first.
|
||||||
|
PrimaryButton(if (s.desktopInstalled) "Open desktop" else "Install & open desktop", enabled = !s.busy, main = true, onClick = a.onDesktop)
|
||||||
|
Cog(onClick = a.onDesktopSettings)
|
||||||
|
BusyChip(s)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Column(
|
||||||
|
verticalArrangement = Arrangement.spacedBy(14.dp),
|
||||||
|
modifier = Modifier.fillMaxWidth().clip(Shape16).background(colors.surface).border(1.dp, pal.line, Shape16).padding(16.dp),
|
||||||
|
) {
|
||||||
|
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(14.dp)) {
|
||||||
|
Box(
|
||||||
|
contentAlignment = Alignment.Center,
|
||||||
|
modifier = Modifier.size(52.dp).clip(Shape14).background(colors.surfaceVariant).border(1.dp, pal.line2, Shape14),
|
||||||
|
) { Icon(Icons.Outlined.DesktopWindows, contentDescription = null, tint = colors.onBackground, modifier = Modifier.size(26.dp)) }
|
||||||
|
Column(modifier = Modifier.weight(1f)) {
|
||||||
|
Text("Linux desktop", fontSize = 18.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground)
|
||||||
|
Text("LXQt, Firefox and your emulators", fontSize = 14.sp, color = colors.onSurfaceVariant, maxLines = 2, overflow = TextOverflow.Ellipsis)
|
||||||
|
}
|
||||||
|
if (!narrow) actions()
|
||||||
|
}
|
||||||
|
if (narrow) actions()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Emulators as wide tiles - three across, or a list on a narrow page. */
|
||||||
|
@Composable
|
||||||
|
private fun EmulatorGrid(emulators: List<Library.Emulator>, first: Boolean, onSelect: (String) -> Unit) {
|
||||||
|
val columns = if (LocalNarrowPane.current) 1 else 3
|
||||||
|
Column(verticalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.fillMaxWidth().padding(top = 4.dp, bottom = 8.dp)) {
|
||||||
|
emulators.chunked(columns).forEachIndexed { r, row ->
|
||||||
|
Row(horizontalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.fillMaxWidth().height(IntrinsicSize.Min)) {
|
||||||
|
row.forEachIndexed { i, e ->
|
||||||
|
key(e.id) {
|
||||||
|
EmulatorTile(e, Modifier.weight(1f).fillMaxHeight(), isFirst = first && r == 0 && i == 0) { onSelect("emu:${e.id}") }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
repeat(columns - row.size) { Spacer(Modifier.weight(1f)) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* One emulator: its icon, system and games. One not yet installed says so in words and keeps full
|
||||||
|
* contrast - dimming it read as disabled rather than one press from installing.
|
||||||
|
*/
|
||||||
|
@Composable
|
||||||
|
private fun EmulatorTile(e: Library.Emulator, modifier: Modifier, isFirst: Boolean, onClick: () -> Unit) {
|
||||||
|
val colors = MaterialTheme.colorScheme
|
||||||
|
val pal = LocalPalette.current
|
||||||
|
val src = remember { MutableInteractionSource() }
|
||||||
|
val hot = rememberHot(src)
|
||||||
|
val pressed by src.collectIsPressedAsState()
|
||||||
|
val scale by animateFloatAsState(if (pressed) 0.97f else 1f, Motion.sp(0.5f, Spring.StiffnessMedium), label = "emuScale")
|
||||||
|
val system = e.system.replaceFirstChar { it.uppercase() }
|
||||||
|
val detail = if (e.installed && e.id != "retroarch") "$system · ${e.games.size} game${if (e.games.size == 1) "" else "s"}" else system
|
||||||
|
Row(
|
||||||
|
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp),
|
||||||
|
modifier = modifier.paneItem("tile:emu:${e.id}").then(if (isFirst) Modifier.firstTile() else Modifier)
|
||||||
|
.graphicsLayer { scaleX = scale; scaleY = scale }
|
||||||
|
.clip(Shape14)
|
||||||
|
.background(if (hot) pal.signal.copy(alpha = 0.10f) else if (e.installed) colors.surface else Color.Transparent)
|
||||||
|
.border(if (hot) 2.dp else 1.dp, if (hot) pal.signal else pal.line, Shape14)
|
||||||
|
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Button, onClick = onClick)
|
||||||
|
.padding(horizontal = 12.dp, vertical = 10.dp),
|
||||||
|
) {
|
||||||
|
Image(painterResource(e.iconRes), contentDescription = null, modifier = Modifier.size(if (e.installed) 44.dp else 36.dp))
|
||||||
|
Column(modifier = Modifier.weight(1f)) {
|
||||||
|
Text(e.name, fontSize = if (e.installed) 15.sp else 14.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||||
|
Text(detail, fontSize = if (e.installed) 13.sp else 12.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||||
|
}
|
||||||
|
if (!e.installed) Text(
|
||||||
|
"Install", fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = pal.signal,
|
||||||
|
modifier = Modifier.clip(RoundedCornerShape(8.dp)).border(1.dp, pal.line2, RoundedCornerShape(8.dp)).padding(horizontal = 10.dp, vertical = 6.dp),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,271 @@
|
|||||||
|
package com.droiddeck.launcher.ui
|
||||||
|
|
||||||
|
import androidx.compose.foundation.LocalIndication
|
||||||
|
import androidx.compose.foundation.background
|
||||||
|
import androidx.compose.foundation.border
|
||||||
|
import androidx.compose.foundation.clickable
|
||||||
|
import androidx.compose.foundation.hoverable
|
||||||
|
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||||
|
import androidx.compose.foundation.interaction.collectIsFocusedAsState
|
||||||
|
import androidx.compose.foundation.interaction.collectIsHoveredAsState
|
||||||
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
|
import androidx.compose.foundation.layout.Box
|
||||||
|
import androidx.compose.runtime.key
|
||||||
|
import androidx.compose.foundation.layout.Column
|
||||||
|
import androidx.compose.foundation.layout.ColumnScope
|
||||||
|
import androidx.compose.foundation.layout.RowScope
|
||||||
|
import androidx.compose.foundation.layout.Row
|
||||||
|
import androidx.compose.foundation.layout.Spacer
|
||||||
|
import androidx.compose.foundation.layout.fillMaxHeight
|
||||||
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
|
import androidx.compose.foundation.layout.height
|
||||||
|
import androidx.compose.foundation.layout.heightIn
|
||||||
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.foundation.layout.size
|
||||||
|
import androidx.compose.foundation.layout.width
|
||||||
|
import androidx.compose.foundation.rememberScrollState
|
||||||
|
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||||
|
import androidx.compose.foundation.verticalScroll
|
||||||
|
import androidx.compose.material.icons.Icons
|
||||||
|
import androidx.compose.material.icons.filled.PlayArrow
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.LaunchedEffect
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.remember
|
||||||
|
import kotlinx.coroutines.flow.first
|
||||||
|
import androidx.compose.runtime.setValue
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.draw.alpha
|
||||||
|
import androidx.compose.ui.draw.blur
|
||||||
|
import androidx.compose.ui.draw.clip
|
||||||
|
import androidx.compose.ui.graphics.Brush
|
||||||
|
import androidx.compose.ui.graphics.Color
|
||||||
|
import androidx.compose.ui.graphics.graphicsLayer
|
||||||
|
import androidx.compose.ui.layout.ContentScale
|
||||||
|
import androidx.compose.ui.semantics.contentDescription
|
||||||
|
import androidx.compose.ui.text.font.FontWeight
|
||||||
|
import androidx.compose.ui.text.style.TextOverflow
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import androidx.compose.ui.unit.sp
|
||||||
|
import coil.compose.AsyncImage
|
||||||
|
import com.droiddeck.launcher.frontend.Library
|
||||||
|
|
||||||
|
// The Games page: the list, the hero for the selected game and its labels.
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The Games tab: installed Steam games down the left, most recently played first, and the one
|
||||||
|
* picked beside them - its banner, Launch and the launch settings. One game skips the list.
|
||||||
|
*/
|
||||||
|
@Composable
|
||||||
|
internal fun GamesPage(s: FrontEndState, a: FrontEndActions, selected: String, onSelect: (String) -> Unit, modifier: Modifier) {
|
||||||
|
val games = remember(s.steamGames) { s.steamGames.sortedByDescending { it.lastPlayed } }
|
||||||
|
val narrow = LocalNarrowPane.current
|
||||||
|
val current = games.firstOrNull { "app:${it.appId}" == selected } ?: games.firstOrNull()
|
||||||
|
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("Games") }
|
||||||
|
Rise(1) { Note("Games you install in Steam show up here. Open Steam, install one, and it appears after the session.") }
|
||||||
|
Rise(2) {
|
||||||
|
Actions { PrimaryButton("Play Steam", enabled = !s.busy, main = true, icon = Icons.Filled.PlayArrow, modifier = Modifier.padding(top = 12.dp), onClick = a.onPlay) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
val host = rememberMenuHost()
|
||||||
|
if (games.size == 1) {
|
||||||
|
Column(modifier = modifier.verticalScroll(rememberScrollState()).padding(horizontal = if (narrow) 16.dp else 22.dp, vertical = if (narrow) 12.dp else 18.dp)) {
|
||||||
|
Rise(0) {
|
||||||
|
Row(verticalAlignment = Alignment.Bottom) {
|
||||||
|
GameHero(current, Modifier.weight(1f).heightIn(min = if (narrow) 190.dp else 250.dp)) {
|
||||||
|
GameHeroCopy(current, if (narrow) 28.sp else 38.sp)
|
||||||
|
GameActions(current, s, a)
|
||||||
|
}
|
||||||
|
if (!narrow) Poster(current.art, current.name, Modifier.width(168.dp))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Rise(1) { SectionTitle("Launch settings", null) }
|
||||||
|
Rise(2) { LaunchSettings(s, a, host) }
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
val pal = LocalPalette.current
|
||||||
|
Row(modifier = modifier) {
|
||||||
|
GameList(games, current, onSelect = { onSelect("app:${it.appId}") }, onLaunch = { a.onSteamGame(it) },
|
||||||
|
modifier = Modifier.width(if (narrow) 168.dp else 250.dp).fillMaxHeight())
|
||||||
|
Box(Modifier.width(1.dp).fillMaxHeight().background(pal.line))
|
||||||
|
Column(
|
||||||
|
modifier = Modifier.weight(1f).fillMaxHeight().verticalScroll(rememberScrollState())
|
||||||
|
.padding(horizontal = if (narrow) 14.dp else 20.dp, vertical = 16.dp),
|
||||||
|
) {
|
||||||
|
GameHero(current, Modifier.fillMaxWidth().heightIn(min = if (narrow) 170.dp else 200.dp)) {
|
||||||
|
GameHeroCopy(current, if (narrow) 24.sp else 32.sp)
|
||||||
|
GameActions(current, s, a)
|
||||||
|
}
|
||||||
|
SectionTitle("Launch settings", null)
|
||||||
|
LaunchSettings(s, a, host)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun GameActions(g: Library.SteamGame, s: FrontEndState, a: FrontEndActions) {
|
||||||
|
Actions {
|
||||||
|
PrimaryButton("Launch", enabled = !s.busy, main = true, icon = Icons.Filled.PlayArrow) { a.onSteamGame(g) }
|
||||||
|
g.gameFiles?.takeIf { it.isDirectory }?.let { dir ->
|
||||||
|
SecondaryButton("Game files", compact = true) { a.onBrowseFiles(dir) }
|
||||||
|
}
|
||||||
|
g.protonPrefix?.takeIf { it.isDirectory }?.let { dir ->
|
||||||
|
SecondaryButton("Proton prefix", compact = true) { a.onBrowseFiles(dir) }
|
||||||
|
}
|
||||||
|
BusyChip(s)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** When it was last played (or where it is, if never) over its name, then room for Launch. */
|
||||||
|
@Composable
|
||||||
|
private fun ColumnScope.GameHeroCopy(g: Library.SteamGame, titleSize: androidx.compose.ui.unit.TextUnit) {
|
||||||
|
Text(
|
||||||
|
(lastPlayedText(g.lastPlayed) ?: libraryLabel(g.library)).uppercase(),
|
||||||
|
fontSize = 12.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 1.2.sp, color = LocalPalette.current.signal,
|
||||||
|
maxLines = 1, overflow = TextOverflow.Ellipsis,
|
||||||
|
)
|
||||||
|
Text(
|
||||||
|
g.name, fontSize = titleSize, lineHeight = titleSize * 1.15f, fontWeight = FontWeight.Bold,
|
||||||
|
color = MaterialTheme.colorScheme.onBackground, maxLines = 2, overflow = TextOverflow.Ellipsis,
|
||||||
|
)
|
||||||
|
Spacer(Modifier.height(8.dp))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun GameList(
|
||||||
|
games: List<Library.SteamGame>, current: Library.SteamGame,
|
||||||
|
onSelect: (Library.SteamGame) -> Unit, onLaunch: (Library.SteamGame) -> Unit, modifier: Modifier,
|
||||||
|
) {
|
||||||
|
val colors = MaterialTheme.colorScheme
|
||||||
|
// Laid out whole, as the art grid is: the pad's focus search only finds rows that exist.
|
||||||
|
Column(
|
||||||
|
verticalArrangement = Arrangement.spacedBy(2.dp),
|
||||||
|
modifier = modifier.verticalScroll(rememberScrollState()).padding(start = 12.dp, end = 10.dp, top = 16.dp, bottom = 16.dp),
|
||||||
|
) {
|
||||||
|
Row(verticalAlignment = Alignment.Bottom, horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.padding(start = 6.dp, bottom = 10.dp)) {
|
||||||
|
Text("Games", fontSize = 22.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, maxLines = 1)
|
||||||
|
Text(games.size.toString(), fontSize = 13.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(bottom = 3.dp))
|
||||||
|
}
|
||||||
|
for (g in games) key(g.appId) {
|
||||||
|
GameRow(g, g.appId == current.appId, onSelect = { onSelect(g) }, onLaunch = { onLaunch(g) })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One game in the list. Moving onto it with the pad shows it; A launches it, a tap only shows it. */
|
||||||
|
@Composable
|
||||||
|
private fun GameRow(g: Library.SteamGame, selected: Boolean, onSelect: () -> Unit, onLaunch: () -> Unit) {
|
||||||
|
val colors = MaterialTheme.colorScheme
|
||||||
|
val pal = LocalPalette.current
|
||||||
|
val src = remember { MutableInteractionSource() }
|
||||||
|
val focused by src.collectIsFocusedAsState()
|
||||||
|
val hovered by src.collectIsHoveredAsState()
|
||||||
|
LaunchedEffect(focused) { if (focused && !selected) onSelect() }
|
||||||
|
Row(
|
||||||
|
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp),
|
||||||
|
modifier = Modifier.fillMaxWidth().paneItem("game:${g.appId}")
|
||||||
|
.clip(Shape12)
|
||||||
|
.background(if (selected) pal.signal.copy(alpha = 0.14f) else if (hovered) Color.White.copy(alpha = 0.05f) else Color.Transparent)
|
||||||
|
.border(2.dp, if (selected || focused) pal.signal else Color.Transparent, Shape12)
|
||||||
|
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, onClick = onSelect)
|
||||||
|
.controllerConfirm(onClick = onLaunch)
|
||||||
|
.padding(horizontal = 10.dp, vertical = 6.dp),
|
||||||
|
) {
|
||||||
|
Box(Modifier.width(30.dp).height(45.dp).clip(RoundedCornerShape(5.dp)).background(artBrush(hueOf(g.name)))) {
|
||||||
|
if (g.art != null) AsyncImage(model = g.art, contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier.matchParentSize())
|
||||||
|
}
|
||||||
|
Column(modifier = Modifier.weight(1f)) {
|
||||||
|
Text(g.name, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||||
|
Text(
|
||||||
|
lastPlayedText(g.lastPlayed)?.removePrefix("Last played ")?.replaceFirstChar { it.uppercase() } ?: "Never played",
|
||||||
|
fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A page's title, with room at its right for a status chip. */
|
||||||
|
@Composable
|
||||||
|
internal fun PageHeader(title: String, trailing: @Composable RowScope.() -> Unit = {}) {
|
||||||
|
Row(
|
||||||
|
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp),
|
||||||
|
modifier = Modifier.fillMaxWidth().padding(bottom = 10.dp),
|
||||||
|
) {
|
||||||
|
Text(
|
||||||
|
title, fontSize = if (LocalNarrowPane.current) 22.sp else 26.sp, fontWeight = FontWeight.Bold,
|
||||||
|
color = MaterialTheme.colorScheme.onBackground, maxLines = 1,
|
||||||
|
)
|
||||||
|
trailing()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Why a launch button is greyed out: the runtime is being worked on. Nothing when it is not. */
|
||||||
|
@Composable
|
||||||
|
internal fun BusyChip(s: FrontEndState) {
|
||||||
|
if (s.busy) ActionChip(if (s.percent >= 0) "Runtime busy · ${s.percent}%" else "Runtime busy", ok = false)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Whether Steam can start, said where Play is rather than only in Setup. */
|
||||||
|
@Composable
|
||||||
|
internal fun RuntimeChip(s: FrontEndState) = when {
|
||||||
|
s.busy -> Chip(if (s.percent >= 0) "${s.stage} · ${s.percent}%" else s.stage, ok = false)
|
||||||
|
!s.ready -> Chip("Runtime installs on first Play", ok = false)
|
||||||
|
s.available != null && s.available != s.installed -> Chip("Runtime update available", ok = false)
|
||||||
|
else -> Chip("● Runtime ready", ok = true)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** "Last played 3 days ago" from Steam's unix seconds; null for a game never played. */
|
||||||
|
private fun lastPlayedText(lastPlayed: Long): String? {
|
||||||
|
if (lastPlayed <= 0L) return null
|
||||||
|
val span = android.text.format.DateUtils.getRelativeTimeSpanString(
|
||||||
|
lastPlayed * 1000L, System.currentTimeMillis(), android.text.format.DateUtils.MINUTE_IN_MILLIS,
|
||||||
|
).toString()
|
||||||
|
return "Last played " + span.replaceFirstChar { it.lowercase() }
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun libraryLabel(library: String): String = when (library) {
|
||||||
|
"internal" -> "Internal storage"
|
||||||
|
"added" -> "Added game"
|
||||||
|
else -> library
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A game's wide banner: Steam's hero art where the client cached one, else its capsule blurred to
|
||||||
|
* fill the width. The copy sits bottom-left over a scrim of the ground colour so it always reads;
|
||||||
|
* the art takes the banner's size, so a banner given a minimum height grows to fit its copy.
|
||||||
|
*/
|
||||||
|
@Composable
|
||||||
|
private fun GameHero(g: Library.SteamGame, modifier: Modifier, content: @Composable ColumnScope.() -> Unit) {
|
||||||
|
val colors = MaterialTheme.colorScheme
|
||||||
|
Box(modifier = modifier.clip(Shape16).background(artBrush(hueOf(g.name)))) {
|
||||||
|
val image = g.hero ?: g.art
|
||||||
|
if (image != null) AsyncImage(
|
||||||
|
model = image, contentDescription = null, contentScale = ContentScale.Crop,
|
||||||
|
modifier = Modifier.matchParentSize()
|
||||||
|
.then(if (g.hero == null) Modifier.blur(24.dp).graphicsLayer { scaleX = 1.3f; scaleY = 1.3f } else Modifier),
|
||||||
|
)
|
||||||
|
Spacer(
|
||||||
|
Modifier.matchParentSize().background(
|
||||||
|
Brush.horizontalGradient(
|
||||||
|
0f to colors.background.copy(alpha = 0.92f),
|
||||||
|
0.55f to colors.background.copy(alpha = 0.6f),
|
||||||
|
1f to Color.Transparent,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
Column(
|
||||||
|
verticalArrangement = Arrangement.spacedBy(4.dp),
|
||||||
|
modifier = Modifier.align(Alignment.BottomStart).padding(horizontal = 22.dp, vertical = 18.dp),
|
||||||
|
content = content,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,261 @@
|
|||||||
|
package com.droiddeck.launcher.ui
|
||||||
|
|
||||||
|
import androidx.compose.ui.focus.focusRequester
|
||||||
|
import androidx.compose.animation.AnimatedVisibility
|
||||||
|
import androidx.compose.animation.animateColorAsState
|
||||||
|
import androidx.compose.animation.core.RepeatMode
|
||||||
|
import androidx.compose.animation.core.Spring
|
||||||
|
import androidx.compose.animation.core.animateFloat
|
||||||
|
import androidx.compose.animation.core.animateFloatAsState
|
||||||
|
import androidx.compose.animation.core.infiniteRepeatable
|
||||||
|
import androidx.compose.animation.core.rememberInfiniteTransition
|
||||||
|
import androidx.compose.animation.core.tween
|
||||||
|
import androidx.compose.animation.expandVertically
|
||||||
|
import androidx.compose.animation.fadeIn
|
||||||
|
import androidx.compose.animation.fadeOut
|
||||||
|
import androidx.compose.animation.shrinkVertically
|
||||||
|
import androidx.compose.foundation.Image
|
||||||
|
import androidx.compose.foundation.LocalIndication
|
||||||
|
import androidx.compose.foundation.background
|
||||||
|
import androidx.compose.foundation.border
|
||||||
|
import androidx.compose.foundation.clickable
|
||||||
|
import androidx.compose.foundation.hoverable
|
||||||
|
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||||
|
import androidx.compose.foundation.interaction.collectIsFocusedAsState
|
||||||
|
import androidx.compose.foundation.interaction.collectIsHoveredAsState
|
||||||
|
import androidx.compose.foundation.interaction.collectIsPressedAsState
|
||||||
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
|
import androidx.compose.foundation.layout.Box
|
||||||
|
import androidx.compose.runtime.key
|
||||||
|
import androidx.compose.foundation.layout.Column
|
||||||
|
import androidx.compose.foundation.layout.Row
|
||||||
|
import androidx.compose.foundation.layout.Spacer
|
||||||
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
|
import androidx.compose.foundation.layout.height
|
||||||
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.foundation.layout.size
|
||||||
|
import androidx.compose.foundation.layout.width
|
||||||
|
import androidx.compose.foundation.rememberScrollState
|
||||||
|
import androidx.compose.foundation.shape.CircleShape
|
||||||
|
import androidx.compose.foundation.verticalScroll
|
||||||
|
import androidx.compose.material.icons.Icons
|
||||||
|
import androidx.compose.material.icons.outlined.Apps
|
||||||
|
import androidx.compose.material.icons.outlined.DesktopWindows
|
||||||
|
import androidx.compose.material.icons.outlined.Layers
|
||||||
|
import androidx.compose.material.icons.outlined.SportsEsports
|
||||||
|
import androidx.compose.material.icons.outlined.Tune
|
||||||
|
import androidx.compose.material.icons.outlined.VideoLibrary
|
||||||
|
import androidx.compose.ui.graphics.vector.ImageVector
|
||||||
|
import androidx.compose.material3.Icon
|
||||||
|
import androidx.compose.material3.LinearProgressIndicator
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.LaunchedEffect
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||||
|
import androidx.compose.foundation.layout.widthIn
|
||||||
|
import androidx.compose.runtime.mutableStateOf
|
||||||
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.runtime.setValue
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.draw.alpha
|
||||||
|
import androidx.compose.ui.draw.clip
|
||||||
|
import androidx.compose.ui.graphics.Color
|
||||||
|
import androidx.compose.ui.graphics.graphicsLayer
|
||||||
|
import androidx.compose.ui.platform.LocalConfiguration
|
||||||
|
import androidx.compose.ui.res.painterResource
|
||||||
|
import androidx.compose.ui.semantics.Role
|
||||||
|
import androidx.compose.ui.semantics.contentDescription
|
||||||
|
import androidx.compose.ui.semantics.semantics
|
||||||
|
import androidx.compose.ui.text.font.FontWeight
|
||||||
|
import androidx.compose.ui.text.style.TextOverflow
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import androidx.compose.ui.unit.sp
|
||||||
|
import com.droiddeck.launcher.R
|
||||||
|
import com.droiddeck.launcher.core.PhantomProcessLimit
|
||||||
|
|
||||||
|
// The front end's side rail: the page list, the resume entry and the controller hints under it.
|
||||||
|
|
||||||
|
/** What the pad's face buttons do here, along the bottom edge as on a console. */
|
||||||
|
@Composable
|
||||||
|
internal fun ControllerHints(select: String = "Select", tabs: Boolean = false) {
|
||||||
|
val colors = MaterialTheme.colorScheme
|
||||||
|
val pal = LocalPalette.current
|
||||||
|
Column(modifier = Modifier.fillMaxWidth()) {
|
||||||
|
Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line))
|
||||||
|
Row(
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
horizontalArrangement = Arrangement.spacedBy(18.dp, Alignment.End),
|
||||||
|
modifier = Modifier.fillMaxWidth().height(34.dp).background(colors.surface).padding(horizontal = 20.dp),
|
||||||
|
) {
|
||||||
|
if (tabs) HintGlyph("LB RB", "Tabs")
|
||||||
|
HintGlyph("A", select)
|
||||||
|
HintGlyph("B", "Back")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun HintGlyph(button: String, action: String) {
|
||||||
|
val colors = MaterialTheme.colorScheme
|
||||||
|
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||||
|
// Face buttons are round; bumpers are a wider keycap.
|
||||||
|
val shape = if (button.length == 1) CircleShape else RoundedCornerShape(6.dp)
|
||||||
|
Box(
|
||||||
|
contentAlignment = Alignment.Center,
|
||||||
|
modifier = Modifier.height(20.dp).widthIn(min = 20.dp).clip(shape).background(colors.onBackground).padding(horizontal = if (button.length == 1) 0.dp else 6.dp),
|
||||||
|
) {
|
||||||
|
Text(button, fontSize = 12.sp, fontWeight = FontWeight.Bold, color = colors.background)
|
||||||
|
}
|
||||||
|
Text(action, fontSize = 13.sp, color = colors.onSurfaceVariant)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal val AttentionAmber = Color(0xFFFFB547)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The launcher's sections, always on screen down the left edge: the app is landscape-only, so the
|
||||||
|
* width a hamburger menu would save is better spent keeping every section one press away.
|
||||||
|
*/
|
||||||
|
@Composable
|
||||||
|
internal fun SideRail(
|
||||||
|
s: FrontEndState, selected: String,
|
||||||
|
onSelect: (String) -> Unit, onFocusSelect: (String) -> Unit, a: FrontEndActions, modifier: Modifier,
|
||||||
|
) {
|
||||||
|
val colors = MaterialTheme.colorScheme
|
||||||
|
val compact = LocalConfiguration.current.screenHeightDp < 420
|
||||||
|
// Under 600dp wide (4:3 and square screens) the labels would cost a fifth of the width.
|
||||||
|
val iconOnly = isNarrowScreen()
|
||||||
|
val setupNeedsAttention = !s.ready || (s.available != null && s.available != s.installed) ||
|
||||||
|
PhantomProcessLimit.blocksSteam(s.phantomProcessStatus)
|
||||||
|
Column(
|
||||||
|
horizontalAlignment = Alignment.CenterHorizontally,
|
||||||
|
modifier = modifier.width(if (iconOnly) 64.dp else 92.dp).background(colors.surface).padding(vertical = if (compact) 8.dp else 12.dp),
|
||||||
|
) {
|
||||||
|
Image(painterResource(R.drawable.logo), contentDescription = "DroidDeck", modifier = Modifier.size(if (compact) 28.dp else 34.dp))
|
||||||
|
Spacer(Modifier.height(if (compact) 6.dp else 12.dp))
|
||||||
|
Column(
|
||||||
|
horizontalAlignment = Alignment.CenterHorizontally,
|
||||||
|
verticalArrangement = Arrangement.spacedBy(4.dp),
|
||||||
|
modifier = Modifier.weight(1f).fillMaxWidth().verticalScroll(rememberScrollState()),
|
||||||
|
) {
|
||||||
|
RailItem("Steam", Icons.Outlined.SportsEsports, "steam", selected == "steam", compact, iconOnly, onFocus = { onFocusSelect("steam") }) { onSelect("steam") }
|
||||||
|
// Always there, so the items below it never move; an empty library says how to fill it.
|
||||||
|
RailItem("Games", Icons.Outlined.VideoLibrary, "games", selected == "games", compact, iconOnly, onFocus = { onFocusSelect("games") }) { onSelect("games") }
|
||||||
|
RailItem("Desktop", Icons.Outlined.DesktopWindows, "desktop", selected == "desktop", compact, iconOnly, onFocus = { onFocusSelect("desktop") }) { onSelect("desktop") }
|
||||||
|
RailItem("Components", Icons.Outlined.Layers, "components", selected == "components", compact, iconOnly, onFocus = { onFocusSelect("components") }) { onSelect("components") }
|
||||||
|
// Home mode's extra section goes last, so it shifts nothing above it.
|
||||||
|
if (s.isHomeApp) RailItem("Apps", Icons.Outlined.Apps, "android-apps", selected == "android-apps", compact, iconOnly, onFocus = { onFocusSelect("android-apps") }) { onSelect("android-apps") }
|
||||||
|
RailItem("Setup", Icons.Outlined.Tune, "setup", selected == "setup", compact, iconOnly, badge = setupNeedsAttention, onFocus = { onFocusSelect("setup") }) { onSelect("setup") }
|
||||||
|
}
|
||||||
|
AnimatedVisibility(s.busy, enter = expandVertically() + fadeIn(), exit = shrinkVertically() + fadeOut()) {
|
||||||
|
Column(horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier.padding(bottom = 8.dp)) {
|
||||||
|
val barWidth = if (iconOnly) 44.dp else 60.dp
|
||||||
|
if (s.percent >= 0) LinearProgressIndicator(progress = { s.percent / 100f }, modifier = Modifier.width(barWidth))
|
||||||
|
else LinearProgressIndicator(modifier = Modifier.width(barWidth))
|
||||||
|
Text(if (s.percent >= 0) "${s.percent}%" else if (iconOnly) "…" else "Working", fontSize = 12.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(top = 4.dp))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var lastRunning by remember { mutableStateOf("") }
|
||||||
|
if (s.running != null) lastRunning = s.running
|
||||||
|
AnimatedVisibility(
|
||||||
|
s.running != null,
|
||||||
|
enter = expandVertically(Motion.sp(0.75f)) + fadeIn(Motion.tw(300)),
|
||||||
|
exit = shrinkVertically(Motion.tw(220)) + fadeOut(Motion.tw(180)),
|
||||||
|
) { ResumeRailItem(lastRunning, compact, iconOnly, a.onResume) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun RailItem(
|
||||||
|
label: String, icon: ImageVector, key: String, current: Boolean, compact: Boolean, iconOnly: Boolean,
|
||||||
|
badge: Boolean = false, onFocus: () -> Unit = {}, onClick: () -> Unit,
|
||||||
|
) {
|
||||||
|
val colors = MaterialTheme.colorScheme
|
||||||
|
val pal = LocalPalette.current
|
||||||
|
val frontFocus = LocalFrontFocus.current
|
||||||
|
val src = remember { MutableInteractionSource() }
|
||||||
|
val focused by src.collectIsFocusedAsState()
|
||||||
|
val hovered by src.collectIsHoveredAsState()
|
||||||
|
val pressed by src.collectIsPressedAsState()
|
||||||
|
if (frontFocus != null) LaunchedEffect(focused) {
|
||||||
|
if (focused) {
|
||||||
|
frontFocus.focusedRail = key
|
||||||
|
onFocus()
|
||||||
|
}
|
||||||
|
else if (frontFocus.focusedRail == key) frontFocus.focusedRail = null
|
||||||
|
}
|
||||||
|
val fg by animateColorAsState(
|
||||||
|
if (current) pal.signal else if (focused || hovered) colors.onBackground else colors.onSurfaceVariant,
|
||||||
|
Motion.tw(220), label = "railFg",
|
||||||
|
)
|
||||||
|
val fill by animateColorAsState(
|
||||||
|
if (current) pal.signal.copy(alpha = 0.14f) else if (focused || hovered) Color.White.copy(alpha = 0.05f) else Color.Transparent,
|
||||||
|
Motion.tw(220), label = "railFill",
|
||||||
|
)
|
||||||
|
val ring by animateColorAsState(if (focused) pal.signal else Color.Transparent, Motion.tw(180), label = "railRing")
|
||||||
|
val scale by animateFloatAsState(if (pressed) 0.95f else 1f, Motion.sp(0.5f, Spring.StiffnessMedium), label = "railScale")
|
||||||
|
Box(
|
||||||
|
contentAlignment = Alignment.Center,
|
||||||
|
modifier = Modifier
|
||||||
|
.then(if (frontFocus != null) Modifier.focusRequester(frontFocus.railFor(key)) else Modifier)
|
||||||
|
.graphicsLayer { scaleX = scale; scaleY = scale }
|
||||||
|
.size(width = if (iconOnly) 52.dp else 80.dp, height = if (iconOnly) 48.dp else if (compact) 52.dp else 60.dp)
|
||||||
|
.clip(Shape14)
|
||||||
|
.background(fill)
|
||||||
|
.border(2.dp, ring, Shape14)
|
||||||
|
.hoverable(src)
|
||||||
|
.clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Tab, onClick = onClick)
|
||||||
|
.then(if (iconOnly) Modifier.semantics { contentDescription = label } else Modifier),
|
||||||
|
) {
|
||||||
|
if (iconOnly) Icon(icon, contentDescription = null, tint = fg, modifier = Modifier.size(22.dp))
|
||||||
|
else Column(horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(3.dp)) {
|
||||||
|
Icon(icon, contentDescription = null, tint = fg, modifier = Modifier.size(if (compact) 20.dp else 22.dp))
|
||||||
|
Text(label, fontSize = 12.sp, fontWeight = FontWeight.SemiBold, color = fg, maxLines = 1, softWrap = false)
|
||||||
|
}
|
||||||
|
if (badge) Box(
|
||||||
|
modifier = Modifier.align(Alignment.TopEnd).padding(top = if (iconOnly) 7.dp else 8.dp, end = if (iconOnly) 9.dp else 18.dp)
|
||||||
|
.size(8.dp).clip(CircleShape).background(AttentionAmber),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The running session, one press from anywhere in the launcher. */
|
||||||
|
@Composable
|
||||||
|
private fun ResumeRailItem(name: String, compact: Boolean, iconOnly: Boolean, onResume: () -> Unit) {
|
||||||
|
val colors = MaterialTheme.colorScheme
|
||||||
|
val pal = LocalPalette.current
|
||||||
|
val src = remember { MutableInteractionSource() }
|
||||||
|
val focused by src.collectIsFocusedAsState()
|
||||||
|
val hovered by src.collectIsHoveredAsState()
|
||||||
|
val pulse = rememberInfiniteTransition(label = "pulse")
|
||||||
|
val ringScale by pulse.animateFloat(0.4f, 1.6f, infiniteRepeatable(tween(Motion.ms(1600).coerceAtLeast(1), easing = Motion.Ease), RepeatMode.Restart), label = "ring")
|
||||||
|
// Animations off: the live dot alone, no pulsing ring.
|
||||||
|
val still = Motion.scale == 0f
|
||||||
|
Column(
|
||||||
|
horizontalAlignment = Alignment.CenterHorizontally,
|
||||||
|
verticalArrangement = Arrangement.spacedBy(3.dp),
|
||||||
|
modifier = Modifier
|
||||||
|
.padding(top = 6.dp)
|
||||||
|
.width(if (iconOnly) 52.dp else 80.dp)
|
||||||
|
.clip(Shape14)
|
||||||
|
.background(pal.good.copy(alpha = if (focused || hovered) 0.20f else 0.12f))
|
||||||
|
.border(2.dp, if (focused) pal.signal else Color.Transparent, Shape14)
|
||||||
|
.hoverable(src)
|
||||||
|
.clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Button, onClick = onResume)
|
||||||
|
.semantics { contentDescription = "Resume $name" }
|
||||||
|
.padding(vertical = if (iconOnly) 15.dp else if (compact) 6.dp else 9.dp, horizontal = 4.dp),
|
||||||
|
) {
|
||||||
|
Box(modifier = Modifier.size(14.dp), contentAlignment = Alignment.Center) {
|
||||||
|
if (!still) Box(modifier = Modifier.size(14.dp).graphicsLayer { scaleX = ringScale; scaleY = ringScale; alpha = (1.6f - ringScale) / 1.2f }.border(1.5.dp, pal.good, CircleShape))
|
||||||
|
Box(modifier = Modifier.size(7.dp).clip(CircleShape).background(pal.good))
|
||||||
|
}
|
||||||
|
// Icons only: the live dot alone says something is running; its description says what.
|
||||||
|
if (!iconOnly) {
|
||||||
|
Text("Resume", fontSize = 12.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, softWrap = false)
|
||||||
|
Text(name, fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,434 @@
|
|||||||
|
package com.droiddeck.launcher.ui
|
||||||
|
|
||||||
|
import androidx.compose.ui.focus.focusRequester
|
||||||
|
import androidx.compose.ui.focus.FocusRequester
|
||||||
|
import android.os.Build
|
||||||
|
import androidx.compose.animation.AnimatedVisibility
|
||||||
|
import androidx.compose.animation.animateColorAsState
|
||||||
|
import androidx.compose.animation.core.Spring
|
||||||
|
import androidx.compose.animation.core.animateFloatAsState
|
||||||
|
import androidx.compose.animation.expandVertically
|
||||||
|
import androidx.compose.animation.fadeIn
|
||||||
|
import androidx.compose.animation.fadeOut
|
||||||
|
import androidx.compose.animation.shrinkVertically
|
||||||
|
import androidx.compose.foundation.LocalIndication
|
||||||
|
import androidx.compose.foundation.background
|
||||||
|
import androidx.compose.foundation.border
|
||||||
|
import androidx.compose.foundation.clickable
|
||||||
|
import androidx.compose.foundation.hoverable
|
||||||
|
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||||
|
import androidx.compose.foundation.interaction.collectIsPressedAsState
|
||||||
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
|
import androidx.compose.foundation.layout.Box
|
||||||
|
import androidx.compose.foundation.layout.Column
|
||||||
|
import androidx.compose.foundation.layout.IntrinsicSize
|
||||||
|
import androidx.compose.foundation.layout.Row
|
||||||
|
import androidx.compose.foundation.layout.Spacer
|
||||||
|
import androidx.compose.foundation.layout.fillMaxHeight
|
||||||
|
import androidx.compose.foundation.layout.fillMaxSize
|
||||||
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
|
import androidx.compose.foundation.layout.height
|
||||||
|
import androidx.compose.foundation.layout.heightIn
|
||||||
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.foundation.layout.size
|
||||||
|
import androidx.compose.foundation.rememberScrollState
|
||||||
|
import androidx.compose.foundation.shape.CircleShape
|
||||||
|
import androidx.compose.foundation.verticalScroll
|
||||||
|
import androidx.compose.material.icons.Icons
|
||||||
|
import androidx.compose.material.icons.filled.Refresh
|
||||||
|
import androidx.compose.material.icons.filled.Check
|
||||||
|
import androidx.compose.material.icons.filled.PriorityHigh
|
||||||
|
import androidx.compose.material.icons.outlined.Extension
|
||||||
|
import androidx.compose.material.icons.outlined.Folder
|
||||||
|
import androidx.compose.material.icons.outlined.Speed
|
||||||
|
import androidx.compose.material.icons.outlined.VideogameAsset
|
||||||
|
import androidx.compose.ui.graphics.vector.ImageVector
|
||||||
|
import androidx.compose.material3.Icon
|
||||||
|
import androidx.compose.material3.LinearProgressIndicator
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.LaunchedEffect
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.mutableStateOf
|
||||||
|
import androidx.compose.runtime.remember
|
||||||
|
import kotlinx.coroutines.flow.first
|
||||||
|
import androidx.compose.runtime.saveable.rememberSaveable
|
||||||
|
import androidx.compose.runtime.setValue
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.draw.alpha
|
||||||
|
import androidx.compose.ui.draw.clip
|
||||||
|
import androidx.compose.ui.graphics.Color
|
||||||
|
import androidx.compose.ui.graphics.graphicsLayer
|
||||||
|
import androidx.compose.ui.platform.LocalInputModeManager
|
||||||
|
import androidx.compose.ui.input.InputMode
|
||||||
|
import androidx.compose.ui.semantics.Role
|
||||||
|
import androidx.compose.ui.semantics.contentDescription
|
||||||
|
import androidx.compose.ui.text.font.FontWeight
|
||||||
|
import androidx.compose.ui.text.style.TextOverflow
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import androidx.compose.ui.unit.sp
|
||||||
|
import com.droiddeck.launcher.core.DeviceSupport
|
||||||
|
import com.droiddeck.launcher.core.PhantomProcessLimit
|
||||||
|
import com.droiddeck.launcher.core.PhantomProcessStatus
|
||||||
|
import com.droiddeck.launcher.session.SessionPrefs
|
||||||
|
|
||||||
|
// The Setup page: runtime and device checks, tools, frame generation and launch settings.
|
||||||
|
|
||||||
|
private enum class CheckState { OK, WARN, BUSY }
|
||||||
|
|
||||||
|
/** One requirement in Setup's system check: a status mark, what it is, and at most one action. */
|
||||||
|
@Composable
|
||||||
|
private fun CheckRow(state: CheckState, title: String, detail: String?, divider: Boolean = true, action: (@Composable () -> Unit)? = null) {
|
||||||
|
val colors = MaterialTheme.colorScheme
|
||||||
|
val pal = LocalPalette.current
|
||||||
|
val tint = when (state) {
|
||||||
|
CheckState.OK -> pal.good
|
||||||
|
CheckState.WARN -> AttentionAmber
|
||||||
|
CheckState.BUSY -> pal.signal
|
||||||
|
}
|
||||||
|
Row(
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
horizontalArrangement = Arrangement.spacedBy(14.dp),
|
||||||
|
modifier = Modifier.fillMaxWidth()
|
||||||
|
.background(if (state == CheckState.WARN) AttentionAmber.copy(alpha = 0.07f) else Color.Transparent)
|
||||||
|
.heightIn(min = 60.dp)
|
||||||
|
.padding(horizontal = 14.dp, vertical = 10.dp),
|
||||||
|
) {
|
||||||
|
Box(contentAlignment = Alignment.Center, modifier = Modifier.size(28.dp).clip(CircleShape).background(tint.copy(alpha = 0.16f))) {
|
||||||
|
Icon(
|
||||||
|
when (state) {
|
||||||
|
CheckState.OK -> Icons.Filled.Check
|
||||||
|
CheckState.WARN -> Icons.Filled.PriorityHigh
|
||||||
|
CheckState.BUSY -> Icons.Filled.Refresh
|
||||||
|
},
|
||||||
|
contentDescription = when (state) {
|
||||||
|
CheckState.OK -> "Done"
|
||||||
|
CheckState.WARN -> "Needs attention"
|
||||||
|
CheckState.BUSY -> "Working"
|
||||||
|
},
|
||||||
|
tint = tint, modifier = Modifier.size(16.dp),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
Column(modifier = Modifier.weight(1f)) {
|
||||||
|
Text(title, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground)
|
||||||
|
if (detail != null) Text(detail, fontSize = 13.sp, color = colors.onSurfaceVariant, maxLines = 2, overflow = TextOverflow.Ellipsis)
|
||||||
|
}
|
||||||
|
if (action != null) action()
|
||||||
|
}
|
||||||
|
if (divider) Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
internal fun SetupPanel(
|
||||||
|
s: FrontEndState,
|
||||||
|
a: FrontEndActions,
|
||||||
|
onOpenDeveloperOptions: () -> Unit,
|
||||||
|
onRequestWirelessAdb: (Boolean) -> Unit,
|
||||||
|
) {
|
||||||
|
val host = rememberMenuHost()
|
||||||
|
var processLimitBusy by remember { mutableStateOf(false) }
|
||||||
|
var processLimitMessage by remember { mutableStateOf<String?>(null) }
|
||||||
|
val setProcessLimit: (Boolean) -> Unit = { enabled ->
|
||||||
|
processLimitBusy = true
|
||||||
|
processLimitMessage = null
|
||||||
|
a.onSetPhantomProcessLimit(enabled) { error ->
|
||||||
|
processLimitBusy = false
|
||||||
|
if (error == null) {
|
||||||
|
a.onRefreshPhantomStatus()
|
||||||
|
} else {
|
||||||
|
processLimitMessage = "Check the Wireless debugging IP address & Port, or pair again if Android removed this device."
|
||||||
|
onRequestWirelessAdb(enabled)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val runtime = when {
|
||||||
|
s.busy -> "Working…"
|
||||||
|
!s.ready -> "Install"
|
||||||
|
s.available != null && s.available != s.installed -> "Update"
|
||||||
|
else -> "Manage"
|
||||||
|
}
|
||||||
|
val colors = MaterialTheme.colorScheme
|
||||||
|
val pal = LocalPalette.current
|
||||||
|
val gpuOk = remember { DeviceSupport.adreno() }
|
||||||
|
val gpuName = remember { DeviceSupport.gpuName() }
|
||||||
|
val limitBlocks = PhantomProcessLimit.blocksSteam(s.phantomProcessStatus)
|
||||||
|
val signedIn = s.offlineAccount != null
|
||||||
|
var showLimitDetails by rememberSaveable { mutableStateOf(false) }
|
||||||
|
val checks = 4
|
||||||
|
val readyCount = listOf(gpuOk, s.ready && !s.busy, !limitBlocks, signedIn).count { it }
|
||||||
|
// Five tabs instead of one long scroll; LB and RB turn them from anywhere on the page.
|
||||||
|
val tabs = listOf("Overview", "Controller", "Session", "Launcher", "About")
|
||||||
|
var tab by rememberSaveable { mutableStateOf(0) }
|
||||||
|
val tabFocus = remember { List(tabs.size) { FocusRequester() } }
|
||||||
|
var tabTurned by remember { mutableStateOf(false) }
|
||||||
|
val pick: (Int) -> Unit = { i -> tab = i; tabTurned = true }
|
||||||
|
val inputModeManager = LocalInputModeManager.current
|
||||||
|
// The control a controller was on went with the old tab: it lands on the new tab itself.
|
||||||
|
LaunchedEffect(tab) {
|
||||||
|
if (tabTurned && inputModeManager.inputMode == InputMode.Keyboard) {
|
||||||
|
androidx.compose.runtime.withFrameNanos { }
|
||||||
|
runCatching { tabFocus[tab].requestFocus() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Rise(0, Modifier.fillMaxSize()) {
|
||||||
|
Column(
|
||||||
|
modifier = Modifier.fillMaxSize().bumpers(
|
||||||
|
onPrevious = { pick((tab + tabs.size - 1) % tabs.size) },
|
||||||
|
onNext = { pick((tab + 1) % tabs.size) },
|
||||||
|
),
|
||||||
|
) {
|
||||||
|
PageHeader("Setup") {
|
||||||
|
Chip(if (readyCount == checks) "● All set" else "$readyCount of $checks ready", ok = readyCount == checks)
|
||||||
|
}
|
||||||
|
TabStrip(tabs, tab, pick, Modifier.padding(bottom = 4.dp), tabFocus)
|
||||||
|
Column(modifier = Modifier.weight(1f).fillMaxWidth().verticalScroll(rememberScrollState()).padding(bottom = 24.dp)) {
|
||||||
|
when (tab) {
|
||||||
|
0 -> {
|
||||||
|
SectionTitle("System check", null)
|
||||||
|
// What Steam needs, one row each: green when done, one button when not. The
|
||||||
|
// process-limit controls only open under their row.
|
||||||
|
Column(modifier = Modifier.fillMaxWidth().clip(Shape14).background(colors.surface).border(1.dp, pal.line, Shape14)) {
|
||||||
|
CheckRow(
|
||||||
|
if (gpuOk) CheckState.OK else CheckState.WARN,
|
||||||
|
if (gpuOk) "Device supported" else "GPU not supported",
|
||||||
|
if (gpuOk) gpuName else "Steam draws with an Adreno driver; $gpuName may show a black screen",
|
||||||
|
)
|
||||||
|
CheckRow(
|
||||||
|
when { s.busy -> CheckState.BUSY; !s.ready -> CheckState.WARN; else -> CheckState.OK },
|
||||||
|
"Linux runtime",
|
||||||
|
when {
|
||||||
|
s.busy -> if (s.percent >= 0) "${s.stage} · ${s.percent}%" else s.stage
|
||||||
|
!s.ready -> "Not installed · about 3 GB, installed on the first Play"
|
||||||
|
s.available != null && s.available != s.installed -> "${s.installed ?: "Installed"} · update available"
|
||||||
|
else -> "${s.installed ?: "Installed"} · up to date"
|
||||||
|
},
|
||||||
|
) { SecondaryButton(runtime, enabled = !s.busy, compact = true, onClick = a.onRuntime) }
|
||||||
|
CheckRow(
|
||||||
|
if (limitBlocks) CheckState.WARN else CheckState.OK,
|
||||||
|
"Child-process limit",
|
||||||
|
when (s.phantomProcessStatus) {
|
||||||
|
PhantomProcessStatus.ENABLED -> "On · Android may close Steam. Turning it off takes a minute"
|
||||||
|
PhantomProcessStatus.UNSET -> "Not set · the ROM default may close Steam. Turning it off takes a minute"
|
||||||
|
PhantomProcessStatus.UNREADABLE -> "Could not be checked · turning it off takes a minute"
|
||||||
|
else -> PhantomProcessLimit.title(s.phantomProcessStatus)
|
||||||
|
},
|
||||||
|
) {
|
||||||
|
if (limitBlocks) PrimaryButton(if (showLimitDetails) "Hide" else "Fix it", compact = true) { showLimitDetails = !showLimitDetails }
|
||||||
|
else if (s.phantomProcessStatus != PhantomProcessStatus.NOT_APPLICABLE) {
|
||||||
|
SecondaryButton(if (showLimitDetails) "Hide" else "Details", compact = true) { showLimitDetails = !showLimitDetails }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
AnimatedVisibility(showLimitDetails, enter = expandVertically() + fadeIn(), exit = shrinkVertically() + fadeOut()) {
|
||||||
|
// One sentence and at most three buttons. The computer route and its
|
||||||
|
// raw command live on the full page Wireless debugging opens.
|
||||||
|
Column(modifier = Modifier.fillMaxWidth().padding(start = 56.dp, end = 14.dp, top = 4.dp, bottom = 10.dp)) {
|
||||||
|
Text(
|
||||||
|
if (limitBlocks) PhantomProcessLimit.gateInstructions(s.phantomProcessStatus)
|
||||||
|
else PhantomProcessLimit.instructions(s.phantomProcessStatus),
|
||||||
|
fontSize = 14.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(vertical = 4.dp),
|
||||||
|
)
|
||||||
|
Actions {
|
||||||
|
if (limitBlocks) {
|
||||||
|
PrimaryButton("Developer options", compact = true, onClick = onOpenDeveloperOptions)
|
||||||
|
SecondaryButton("Use Wireless debugging", compact = true, enabled = !processLimitBusy) { setProcessLimit(false) }
|
||||||
|
SecondaryButton("Check again", compact = true, onClick = a.onRefreshPhantomStatus)
|
||||||
|
} else if (s.phantomProcessStatus == PhantomProcessStatus.DISABLED) {
|
||||||
|
SecondaryButton("Turn limit on", compact = true, enabled = !processLimitBusy) { setProcessLimit(true) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (processLimitBusy) LinearProgressIndicator(modifier = Modifier.fillMaxWidth().padding(vertical = 6.dp))
|
||||||
|
processLimitMessage?.let { Text(it, fontSize = 14.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(vertical = 4.dp)) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
CheckRow(
|
||||||
|
if (signedIn) CheckState.OK else CheckState.WARN,
|
||||||
|
"Steam account",
|
||||||
|
s.offlineAccount?.let { if (s.offline) "Signed in as $it · offline mode" else "Signed in as $it" } ?: "Press Play and sign in to Steam",
|
||||||
|
divider = false,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
SectionTitle("Tools", null)
|
||||||
|
ToolGrid(s, a)
|
||||||
|
}
|
||||||
|
1 -> {
|
||||||
|
val controller = s.controller
|
||||||
|
if (controller != null && a.controller != null) SettingsGroup("Controller") {
|
||||||
|
ControllerRows(host, s.oscMode, controller, a.controller)
|
||||||
|
}
|
||||||
|
if (s.controller == null || a.controller == null) Note("Controller settings are unavailable.")
|
||||||
|
}
|
||||||
|
2 -> {
|
||||||
|
SettingsGroup("Session") {
|
||||||
|
ChoiceRow(
|
||||||
|
host, "back-actions", "Back", SessionPrefs.backActionsOrder(s.backActionsInverted),
|
||||||
|
listOf(
|
||||||
|
false to SessionPrefs.BACK_MENU_THEN_QAM,
|
||||||
|
true to SessionPrefs.BACK_QAM_THEN_MENU,
|
||||||
|
), s.backActionsInverted, onPick = a.onBackActionsInverted,
|
||||||
|
)
|
||||||
|
SettingsRow("Frame generation", "Select the frame generation mode") {
|
||||||
|
Box {
|
||||||
|
ValueChip(s.frameGenLabel, host.open == "fg") { host.open = if (host.open == "fg") null else "fg" }
|
||||||
|
FrameGenMenu(s, a, host)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ToggleRow(host, "logs", "Session logs", "Saved after each session", s.logsEnabled) { a.onLogs() }
|
||||||
|
ActionRow("Latest session logs", "Send them with a bug report", "Share logs", a.onShareLogs)
|
||||||
|
ToggleRow(
|
||||||
|
host, "offline", "Offline mode",
|
||||||
|
s.offlineAccount?.let { "Signed in as $it" } ?: "Sign in to Steam first",
|
||||||
|
s.offline, enabled = s.offlineAccount != null,
|
||||||
|
) { a.onOffline() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
3 -> {
|
||||||
|
SettingsGroup("Launcher") {
|
||||||
|
SettingsRow("Theme", "Choose the launcher appearance") {
|
||||||
|
Box {
|
||||||
|
ValueChip(Themes.byId(s.theme).label, host.open == "theme") { host.open = if (host.open == "theme") null else "theme" }
|
||||||
|
AnchoredMenu(host.open == "theme", onDismiss = { if (host.open == "theme") host.open = null }, title = "Theme") { firstItemFocus ->
|
||||||
|
Themes.all.forEachIndexed { index, theme ->
|
||||||
|
MenuItem(theme.label, checked = s.theme == theme.id, focusRequester = if (index == 0) firstItemFocus else null) {
|
||||||
|
a.onTheme(theme.id)
|
||||||
|
host.open = null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ToggleRow(
|
||||||
|
host, "home-screen", "Use as a Home screen",
|
||||||
|
if (s.homeScreenEnabled) "DroidDeck can be the phone's Home app" else "Off: DroidDeck is never offered as a Home app",
|
||||||
|
s.homeScreenEnabled,
|
||||||
|
) { a.onHomeScreen(it) }
|
||||||
|
ToggleRow(
|
||||||
|
host, "launcher-fullscreen", "Fullscreen",
|
||||||
|
if (s.launcherFullscreen) "Hide the Android status and navigation bars" else "Show the Android status and navigation bars",
|
||||||
|
s.launcherFullscreen,
|
||||||
|
) { a.onLauncherFullscreen(it) }
|
||||||
|
if (s.homeScreenEnabled) {
|
||||||
|
ActionRow("Default Home app", s.defaultHomeLabel ?: "Choose a Home app", "Choose", a.onHomeApp)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else -> {
|
||||||
|
SettingsGroup("About") {
|
||||||
|
ActionRow("Build", s.buildLabel, "Check for newer", a.onCheckLatestBuild)
|
||||||
|
ActionRow("Credits", "The people and projects DroidDeck builds on", "View", a.onCredits)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The launcher's own tools as cards: four across, two by two on a narrow page. */
|
||||||
|
@Composable
|
||||||
|
private fun ToolGrid(s: FrontEndState, a: FrontEndActions) {
|
||||||
|
val columns = if (LocalNarrowPane.current) 2 else 4
|
||||||
|
val tools = listOf(
|
||||||
|
ToolSpec(Icons.Outlined.Folder, "Files", "Browse and manage files", a.onFiles),
|
||||||
|
ToolSpec(Icons.Outlined.Extension, "Proton versions", "Install ARM64 Proton builds", a.onProtons),
|
||||||
|
ToolSpec(Icons.Outlined.Speed, "Performance", "CPU core assignment", a.onPerformance),
|
||||||
|
ToolSpec(Icons.Outlined.VideogameAsset, "ROMs folder", s.romsDir ?: "Choose where emulator games are stored", a.onRoms),
|
||||||
|
)
|
||||||
|
Column(verticalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.fillMaxWidth()) {
|
||||||
|
for (row in tools.chunked(columns)) {
|
||||||
|
Row(horizontalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.fillMaxWidth().height(IntrinsicSize.Min)) {
|
||||||
|
for (t in row) ToolCard(t, Modifier.weight(1f).fillMaxHeight())
|
||||||
|
repeat(columns - row.size) { Spacer(Modifier.weight(1f)) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private class ToolSpec(val icon: ImageVector, val title: String, val detail: String, val onClick: () -> Unit)
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun ToolCard(t: ToolSpec, modifier: Modifier) {
|
||||||
|
val colors = MaterialTheme.colorScheme
|
||||||
|
val pal = LocalPalette.current
|
||||||
|
val src = remember { MutableInteractionSource() }
|
||||||
|
val hot = rememberHot(src)
|
||||||
|
val pressed by src.collectIsPressedAsState()
|
||||||
|
val scale by animateFloatAsState(if (pressed) 0.97f else 1f, Motion.sp(0.5f, Spring.StiffnessMedium), label = "toolScale")
|
||||||
|
Column(
|
||||||
|
verticalArrangement = Arrangement.spacedBy(4.dp),
|
||||||
|
modifier = modifier.paneItem("tool:${t.title}")
|
||||||
|
.graphicsLayer { scaleX = scale; scaleY = scale }
|
||||||
|
.clip(Shape14)
|
||||||
|
.background(if (hot) pal.signal.copy(alpha = 0.10f) else colors.surface)
|
||||||
|
.border(if (hot) 2.dp else 1.dp, if (hot) pal.signal else pal.line, Shape14)
|
||||||
|
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Button, onClick = t.onClick)
|
||||||
|
.controllerConfirm(onClick = t.onClick)
|
||||||
|
.padding(horizontal = 14.dp, vertical = 12.dp),
|
||||||
|
) {
|
||||||
|
Icon(t.icon, contentDescription = null, tint = if (hot) pal.signal else colors.onSurfaceVariant, modifier = Modifier.size(20.dp))
|
||||||
|
Text(t.title, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||||
|
Text(t.detail, fontSize = 13.sp, color = colors.onSurfaceVariant, maxLines = 2, overflow = TextOverflow.Ellipsis)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun FrameGenMenu(s: FrontEndState, a: FrontEndActions, host: MenuHost) {
|
||||||
|
FrameGenMenu(host, s.frameGenEngine, s.frameGenMultiplier, s.lsfgReady, a.onFrameGenPick)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* What shapes a launch, beside the game rather than three screens away in Setup. They are the
|
||||||
|
* app-wide settings - each card opens the same page or menu Setup does.
|
||||||
|
*/
|
||||||
|
@Composable
|
||||||
|
internal fun LaunchSettings(s: FrontEndState, a: FrontEndActions, host: MenuHost) {
|
||||||
|
// Three across, two on a narrow page; each row's cards share one height.
|
||||||
|
val columns = if (LocalNarrowPane.current) 2 else 3
|
||||||
|
val controller = a.controller
|
||||||
|
val cards = buildList<@Composable (Modifier) -> Unit> {
|
||||||
|
add { m -> SettingCard("Components", "FEX, DXVK, VKD3D", "card:components", m) { a.onComponents(true) } }
|
||||||
|
add { m ->
|
||||||
|
Box(m) {
|
||||||
|
SettingCard("Frame generation", s.frameGenLabel, "card:fg", Modifier.fillMaxSize()) {
|
||||||
|
host.open = if (host.open == "fg") null else "fg"
|
||||||
|
}
|
||||||
|
FrameGenMenu(s, a, host)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (controller != null) add { m -> SettingCard("Controls", "Button mapping", "card:controls", m, controller.onMapping) }
|
||||||
|
}
|
||||||
|
Column(verticalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.fillMaxWidth().padding(bottom = 16.dp)) {
|
||||||
|
for (row in cards.chunked(columns)) {
|
||||||
|
Row(horizontalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.fillMaxWidth().height(IntrinsicSize.Min)) {
|
||||||
|
for (card in row) card(Modifier.weight(1f).fillMaxHeight())
|
||||||
|
repeat(columns - row.size) { Spacer(Modifier.weight(1f)) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun SettingCard(label: String, value: String, id: String, modifier: Modifier, onClick: () -> Unit) {
|
||||||
|
val colors = MaterialTheme.colorScheme
|
||||||
|
val pal = LocalPalette.current
|
||||||
|
val src = remember { MutableInteractionSource() }
|
||||||
|
val hot = rememberHot(src)
|
||||||
|
val pressed by src.collectIsPressedAsState()
|
||||||
|
val scale by animateFloatAsState(if (pressed) 0.97f else 1f, Motion.sp(0.5f, Spring.StiffnessMedium), label = "cardScale")
|
||||||
|
val edge by animateColorAsState(if (hot) pal.signal else pal.line2, Motion.tw(220), label = "cardEdge")
|
||||||
|
Column(
|
||||||
|
verticalArrangement = Arrangement.spacedBy(3.dp),
|
||||||
|
modifier = modifier.paneItem(id)
|
||||||
|
.graphicsLayer { scaleX = scale; scaleY = scale }
|
||||||
|
.clip(Shape14)
|
||||||
|
.background(if (hot) pal.signal.copy(alpha = 0.10f) else colors.surface)
|
||||||
|
.border(if (hot) 2.dp else 1.dp, edge, Shape14)
|
||||||
|
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Button, onClick = onClick)
|
||||||
|
.controllerConfirm(onClick = onClick)
|
||||||
|
.padding(horizontal = 14.dp, vertical = 12.dp),
|
||||||
|
) {
|
||||||
|
Text(label, fontSize = 13.sp, color = if (hot) pal.signal else colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||||
|
Text(value, fontSize = 16.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,237 @@
|
|||||||
|
package com.droiddeck.launcher.ui
|
||||||
|
|
||||||
|
import androidx.compose.ui.layout.boundsInRoot
|
||||||
|
import androidx.compose.ui.layout.onGloballyPositioned
|
||||||
|
import androidx.compose.ui.focus.focusRequester
|
||||||
|
import androidx.compose.ui.focus.onFocusChanged
|
||||||
|
import android.provider.Settings
|
||||||
|
import androidx.compose.animation.animateColorAsState
|
||||||
|
import androidx.compose.animation.core.Animatable
|
||||||
|
import androidx.compose.animation.core.Spring
|
||||||
|
import androidx.compose.animation.core.animateFloatAsState
|
||||||
|
import androidx.compose.foundation.LocalIndication
|
||||||
|
import androidx.compose.foundation.background
|
||||||
|
import androidx.compose.foundation.border
|
||||||
|
import androidx.compose.foundation.clickable
|
||||||
|
import androidx.compose.foundation.hoverable
|
||||||
|
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||||
|
import androidx.compose.foundation.interaction.collectIsFocusedAsState
|
||||||
|
import androidx.compose.foundation.interaction.collectIsHoveredAsState
|
||||||
|
import androidx.compose.foundation.interaction.collectIsPressedAsState
|
||||||
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
|
import androidx.compose.foundation.layout.Box
|
||||||
|
import androidx.compose.foundation.layout.ExperimentalLayoutApi
|
||||||
|
import androidx.compose.foundation.layout.FlowRow
|
||||||
|
import androidx.compose.foundation.layout.Row
|
||||||
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
|
import androidx.compose.foundation.layout.height
|
||||||
|
import androidx.compose.foundation.layout.heightIn
|
||||||
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.foundation.layout.size
|
||||||
|
import androidx.compose.foundation.layout.width
|
||||||
|
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||||
|
import androidx.compose.material.icons.Icons
|
||||||
|
import androidx.compose.material.icons.filled.Settings
|
||||||
|
import androidx.compose.material.icons.filled.ChevronLeft
|
||||||
|
import androidx.compose.ui.graphics.vector.ImageVector
|
||||||
|
import androidx.compose.material3.Icon
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.DisposableEffect
|
||||||
|
import androidx.compose.runtime.LaunchedEffect
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.runtime.setValue
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.draw.alpha
|
||||||
|
import androidx.compose.ui.draw.clip
|
||||||
|
import androidx.compose.ui.draw.rotate
|
||||||
|
import androidx.compose.ui.graphics.Brush
|
||||||
|
import androidx.compose.ui.graphics.Color
|
||||||
|
import androidx.compose.ui.graphics.graphicsLayer
|
||||||
|
import androidx.compose.ui.semantics.Role
|
||||||
|
import androidx.compose.ui.semantics.contentDescription
|
||||||
|
import androidx.compose.ui.text.font.FontWeight
|
||||||
|
import androidx.compose.ui.text.style.TextOverflow
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import androidx.compose.ui.unit.sp
|
||||||
|
|
||||||
|
// Small building blocks shared by the front end's pages: text styles, chips and buttons.
|
||||||
|
|
||||||
|
internal val Shape14 = RoundedCornerShape(14.dp)
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
internal fun Eyebrow(t: String) {
|
||||||
|
val pal = LocalPalette.current
|
||||||
|
val rule = remember { Animatable(0f) }
|
||||||
|
LaunchedEffect(Unit) { rule.animateTo(1f, Motion.tw(600, 120)) }
|
||||||
|
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
|
Box(modifier = Modifier.width(18.dp).height(1.5.dp).graphicsLayer { scaleX = rule.value; transformOrigin = androidx.compose.ui.graphics.TransformOrigin(0f, 0.5f) }.background(pal.signal))
|
||||||
|
Text(t.uppercase(), fontSize = 12.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 1.5.sp, color = pal.signal)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable internal fun Title(t: String) = Text(t, fontSize = 26.sp, fontWeight = FontWeight.Bold, color = MaterialTheme.colorScheme.onBackground, modifier = Modifier.padding(top = 4.dp, bottom = 4.dp))
|
||||||
|
|
||||||
|
@Composable internal fun Lede(t: String) = Text(t, fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(bottom = 12.dp))
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
internal fun SectionTitle(t: String, detail: String?) {
|
||||||
|
val colors = MaterialTheme.colorScheme
|
||||||
|
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.fillMaxWidth().padding(top = 16.dp, bottom = 8.dp)) {
|
||||||
|
Text(t.uppercase(), fontSize = 12.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 1.5.sp, color = colors.onSurfaceVariant)
|
||||||
|
if (detail != null) Text(detail, fontSize = 12.sp, color = colors.onBackground)
|
||||||
|
Box(modifier = Modifier.weight(1f).height(1.dp).background(LocalPalette.current.line))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable internal fun Note(t: String) = Text(t, fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.fillMaxWidth().clip(Shape12).background(MaterialTheme.colorScheme.surface).border(1.dp, LocalPalette.current.line2, Shape12).padding(12.dp))
|
||||||
|
|
||||||
|
/** A page's buttons: they wrap onto a second line rather than run off a narrow page. */
|
||||||
|
@OptIn(ExperimentalLayoutApi::class)
|
||||||
|
@Composable
|
||||||
|
internal fun Actions(content: @Composable () -> Unit) = FlowRow(
|
||||||
|
horizontalArrangement = Arrangement.spacedBy(10.dp),
|
||||||
|
verticalArrangement = Arrangement.spacedBy(10.dp),
|
||||||
|
) { content() }
|
||||||
|
|
||||||
|
/** A status chip in a row of buttons, centred on their height. */
|
||||||
|
@Composable
|
||||||
|
internal fun ActionChip(t: String, ok: Boolean) = Box(contentAlignment = Alignment.Center, modifier = Modifier.heightIn(min = 44.dp)) { Chip(t, ok) }
|
||||||
|
|
||||||
|
internal val Shape16 = RoundedCornerShape(16.dp)
|
||||||
|
|
||||||
|
/** One level up, as Back and B do: a real button, big enough to hit ([compact]: for the tightest layouts). */
|
||||||
|
@Composable
|
||||||
|
internal fun BackLink(label: String, compact: Boolean = false, onClick: () -> Unit) {
|
||||||
|
val colors = MaterialTheme.colorScheme
|
||||||
|
val pal = LocalPalette.current
|
||||||
|
val src = remember { MutableInteractionSource() }
|
||||||
|
val hot = rememberHot(src)
|
||||||
|
val shape = RoundedCornerShape(22.dp)
|
||||||
|
Row(
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
modifier = Modifier.paneItem("back:$label").heightIn(min = if (compact) 44.dp else 48.dp)
|
||||||
|
.clip(shape)
|
||||||
|
.background(if (hot) pal.signal.copy(alpha = 0.14f) else Color.White.copy(alpha = 0.04f))
|
||||||
|
.border(2.dp, if (hot) pal.signal else Color.Transparent, shape)
|
||||||
|
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Button, onClick = onClick)
|
||||||
|
.controllerConfirm(onClick = onClick)
|
||||||
|
.padding(start = 8.dp, end = 16.dp),
|
||||||
|
) {
|
||||||
|
Icon(Icons.Filled.ChevronLeft, contentDescription = null, tint = if (hot) pal.signal else colors.onBackground, modifier = Modifier.size(22.dp))
|
||||||
|
Text(label, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
internal fun Chip(t: String, ok: Boolean) {
|
||||||
|
val colors = MaterialTheme.colorScheme
|
||||||
|
val pal = LocalPalette.current
|
||||||
|
Text(
|
||||||
|
t, fontSize = 12.sp, color = if (ok) pal.good else colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis,
|
||||||
|
modifier = Modifier.clip(RoundedCornerShape(99.dp)).background(colors.surfaceVariant).border(1.dp, if (ok) pal.good.copy(alpha = 0.3f) else pal.line, RoundedCornerShape(99.dp)).padding(horizontal = 9.dp, vertical = 4.dp),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
internal fun rememberHot(src: MutableInteractionSource): Boolean = src.collectIsFocusedAsState().value || src.collectIsHoveredAsState().value
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
internal fun PrimaryButton(
|
||||||
|
text: String,
|
||||||
|
enabled: Boolean = true,
|
||||||
|
main: Boolean = false,
|
||||||
|
compact: Boolean = false,
|
||||||
|
modifier: Modifier = Modifier,
|
||||||
|
/** The Steam tab's own Play: bigger than any other button on a page. */
|
||||||
|
large: Boolean = false,
|
||||||
|
icon: ImageVector? = null,
|
||||||
|
onClick: () -> Unit,
|
||||||
|
) {
|
||||||
|
val colors = MaterialTheme.colorScheme
|
||||||
|
val pal = LocalPalette.current
|
||||||
|
// The page's main button is where the pane is entered from the rail.
|
||||||
|
val frontFocus = if (main) LocalFrontFocus.current else null
|
||||||
|
if (frontFocus != null) DisposableEffect(Unit) {
|
||||||
|
frontFocus.primaryAttached++
|
||||||
|
onDispose { frontFocus.primaryAttached-- }
|
||||||
|
}
|
||||||
|
val track = (if (frontFocus == null) Modifier.paneItem("btn:$text") else Modifier).downToFirstTile()
|
||||||
|
val src = remember { MutableInteractionSource() }
|
||||||
|
val hot = rememberHot(src) && enabled
|
||||||
|
val pressed by src.collectIsPressedAsState()
|
||||||
|
val scale by animateFloatAsState(if (pressed) 0.955f else if (hot) 1.02f else 1f, Motion.sp(0.5f, Spring.StiffnessMedium), label = "btnScale")
|
||||||
|
val lift by animateFloatAsState(if (hot) 14f else 6f, Motion.tw(300), label = "btnLift")
|
||||||
|
// Where it sits, so a session it starts can grow out of it (LaunchFlood).
|
||||||
|
val placed = remember { arrayOfNulls<androidx.compose.ui.layout.LayoutCoordinates>(1) }
|
||||||
|
Row(
|
||||||
|
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||||
|
modifier = modifier.then(track)
|
||||||
|
.onGloballyPositioned { placed[0] = it }
|
||||||
|
// 48dp to touch on a handheld; compact rows keep 44.
|
||||||
|
.heightIn(min = if (compact) 44.dp else 48.dp)
|
||||||
|
.then(if (frontFocus != null) Modifier.focusRequester(frontFocus.primary).onFocusChanged { if (it.isFocused) frontFocus.last = FrontFocus.PRIMARY } else Modifier)
|
||||||
|
.graphicsLayer { alpha = if (LaunchOrigin.flooding === placed) 0f else 1f; scaleX = scale; scaleY = scale; shadowElevation = if (enabled) lift.dp.toPx() else 0f; shape = Shape12; clip = false; ambientShadowColor = pal.signal; spotShadowColor = pal.signal }
|
||||||
|
.clip(Shape12)
|
||||||
|
.background(if (enabled) Brush.linearGradient(listOf(colors.primary, pal.primary2)) else Brush.linearGradient(listOf(colors.surfaceVariant, colors.surfaceVariant)))
|
||||||
|
.shine(hot, 0.45f)
|
||||||
|
// The grow and shine alone barely show on the light fill: outline it when a
|
||||||
|
// controller is on it, as the other controls are.
|
||||||
|
.border(2.dp, if (hot) pal.signal else Color.Transparent, Shape12)
|
||||||
|
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, enabled = enabled) {
|
||||||
|
placed[0]?.takeIf { it.isAttached }?.let { LaunchOrigin.mark(it.boundsInRoot(), placed) }
|
||||||
|
onClick()
|
||||||
|
}
|
||||||
|
.padding(
|
||||||
|
start = if (large) 20.dp else if (compact) 10.dp else if (icon != null) 14.dp else 18.dp,
|
||||||
|
end = if (large) 26.dp else if (compact) 10.dp else 18.dp,
|
||||||
|
top = if (large) 16.dp else if (compact) 7.dp else 11.dp,
|
||||||
|
bottom = if (large) 16.dp else if (compact) 7.dp else 11.dp,
|
||||||
|
),
|
||||||
|
) {
|
||||||
|
val fg = if (enabled) colors.onPrimary else colors.onSurfaceVariant
|
||||||
|
if (icon != null) Icon(icon, contentDescription = null, tint = fg, modifier = Modifier.size(if (large) 20.dp else 17.dp))
|
||||||
|
Text(
|
||||||
|
text, fontSize = if (large) 17.sp else if (compact) 12.sp else 15.sp,
|
||||||
|
fontWeight = if (large) FontWeight.Bold else FontWeight.SemiBold, letterSpacing = 0.5.sp, color = fg, maxLines = 1,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
internal fun SecondaryButton(text: String, enabled: Boolean = true, compact: Boolean = false, modifier: Modifier = Modifier, onClick: () -> Unit) {
|
||||||
|
val colors = MaterialTheme.colorScheme
|
||||||
|
val src = remember { MutableInteractionSource() }
|
||||||
|
val hot = rememberHot(src) && enabled
|
||||||
|
val pressed by src.collectIsPressedAsState()
|
||||||
|
val scale by animateFloatAsState(if (pressed) 0.955f else if (hot) 1.02f else 1f, Motion.sp(0.5f, Spring.StiffnessMedium), label = "secScale")
|
||||||
|
val pal = LocalPalette.current
|
||||||
|
val edge by animateColorAsState(if (hot) pal.signal else pal.line2, Motion.tw(250), label = "secEdge")
|
||||||
|
val fill by animateColorAsState(if (hot) pal.signal.copy(alpha = 0.14f) else Color.White.copy(alpha = 0.03f), Motion.tw(250), label = "secFill")
|
||||||
|
Box(
|
||||||
|
contentAlignment = Alignment.Center,
|
||||||
|
modifier = modifier.paneItem("btn:$text").downToFirstTile().heightIn(min = if (compact) 44.dp else 48.dp).graphicsLayer { scaleX = scale; scaleY = scale }.clip(Shape12).background(fill).border(1.dp, edge, Shape12)
|
||||||
|
.alpha(if (enabled) 1f else 0.5f)
|
||||||
|
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, enabled = enabled, onClick = onClick)
|
||||||
|
.controllerConfirm(enabled = enabled, onClick = onClick)
|
||||||
|
.padding(horizontal = if (compact) 10.dp else 16.dp, vertical = if (compact) 7.dp else 11.dp),
|
||||||
|
) { Text(text, fontSize = if (compact) 12.sp else 15.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 0.5.sp, color = colors.onBackground, maxLines = 1) }
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
internal fun Cog(size: androidx.compose.ui.unit.Dp = 48.dp, onClick: () -> Unit) {
|
||||||
|
val colors = MaterialTheme.colorScheme
|
||||||
|
val src = remember { MutableInteractionSource() }
|
||||||
|
val hot = rememberHot(src)
|
||||||
|
val rot by animateFloatAsState(if (hot) 90f else 0f, Motion.sp(0.55f), label = "cog")
|
||||||
|
val pal = LocalPalette.current
|
||||||
|
val edge by animateColorAsState(if (hot) pal.signal else pal.line2, Motion.tw(250), label = "cogEdge")
|
||||||
|
Box(
|
||||||
|
contentAlignment = Alignment.Center,
|
||||||
|
modifier = Modifier.paneItem("cog").downToFirstTile().size(size).clip(if (size > 48.dp) Shape14 else Shape12).background(Color.White.copy(alpha = 0.03f)).border(1.dp, edge, if (size > 48.dp) Shape14 else Shape12)
|
||||||
|
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, onClick = onClick),
|
||||||
|
) { Icon(Icons.Filled.Settings, "Settings", tint = if (hot) pal.signal else colors.onBackground, modifier = Modifier.size(if (size > 48.dp) 20.dp else 18.dp).rotate(rot)) }
|
||||||
|
}
|
||||||
@@ -0,0 +1,174 @@
|
|||||||
|
package com.droiddeck.launcher.ui
|
||||||
|
|
||||||
|
import android.os.SystemClock
|
||||||
|
import androidx.compose.animation.core.Animatable
|
||||||
|
import androidx.compose.animation.core.CubicBezierEasing
|
||||||
|
import androidx.compose.animation.core.tween
|
||||||
|
import androidx.compose.foundation.Canvas
|
||||||
|
import androidx.compose.foundation.gestures.awaitEachGesture
|
||||||
|
import androidx.compose.foundation.layout.Box
|
||||||
|
import androidx.compose.foundation.layout.fillMaxSize
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.LaunchedEffect
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.mutableStateOf
|
||||||
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.runtime.rememberUpdatedState
|
||||||
|
import androidx.compose.runtime.setValue
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.geometry.CornerRadius
|
||||||
|
import androidx.compose.ui.geometry.Offset
|
||||||
|
import androidx.compose.ui.geometry.Rect
|
||||||
|
import androidx.compose.ui.geometry.Size
|
||||||
|
import androidx.compose.ui.graphics.Brush
|
||||||
|
import androidx.compose.ui.graphics.Color
|
||||||
|
import androidx.compose.ui.graphics.graphicsLayer
|
||||||
|
import androidx.compose.ui.graphics.lerp
|
||||||
|
import androidx.compose.ui.input.pointer.pointerInput
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import androidx.compose.ui.util.lerp
|
||||||
|
import kotlin.math.hypot
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import kotlinx.coroutines.flow.first
|
||||||
|
import kotlinx.coroutines.delay
|
||||||
|
import kotlinx.coroutines.coroutineScope
|
||||||
|
import androidx.compose.ui.layout.onSizeChanged
|
||||||
|
import androidx.compose.runtime.snapshotFlow
|
||||||
|
import androidx.compose.animation.core.spring
|
||||||
|
|
||||||
|
// Starting a session from a blue button: the button grows until the page is its blue, and the
|
||||||
|
// loading screen opens on that blue and gathers it into the ball of the throbber.
|
||||||
|
|
||||||
|
/** Carries the flood's colour to the session, which opens on it. */
|
||||||
|
const val EXTRA_FLOOD = "com.droiddeck.launcher.FLOOD"
|
||||||
|
|
||||||
|
/** Where the last pressed blue button sat, so a session started by it can grow out of it. */
|
||||||
|
internal object LaunchOrigin {
|
||||||
|
private var bounds: Rect? = null
|
||||||
|
private var button: Any? = null
|
||||||
|
private var at = 0L
|
||||||
|
|
||||||
|
/** The button a flood is growing out of: it steps aside so only the flood shows. */
|
||||||
|
var flooding by mutableStateOf<Any?>(null)
|
||||||
|
|
||||||
|
fun mark(r: Rect, key: Any) {
|
||||||
|
bounds = r
|
||||||
|
button = key
|
||||||
|
at = SystemClock.uptimeMillis()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The button behind a launch starting now, if one was pressed just before; it hides for the flood. */
|
||||||
|
fun take(): Rect? {
|
||||||
|
val b = bounds?.takeIf { SystemClock.uptimeMillis() - at < 1_500 }
|
||||||
|
if (b != null) flooding = button
|
||||||
|
bounds = null
|
||||||
|
button = null
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The page a flood grows over, sinking back a touch as it is covered; [progress] is the flood's. */
|
||||||
|
@Composable
|
||||||
|
internal fun FloodBehind(progress: () -> Float, content: @Composable () -> Unit) {
|
||||||
|
Box(Modifier.fillMaxSize().graphicsLayer { val k = sinkScale(progress()); scaleX = k; scaleY = k }) { content() }
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun sinkScale(progress: Float) = 1f - 0.04f * progress
|
||||||
|
|
||||||
|
private val Gather = CubicBezierEasing(0.6f, 0f, 0.15f, 1f)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The pressed button, [from] in root px, stretching out to cover the page. Each edge rides its own
|
||||||
|
* loose spring: the ones with furthest to go set off first and quickest, the ones near the page's
|
||||||
|
* edge lag and then snap after them, so it pulls like something elastic rather than zooming. It
|
||||||
|
* goes blobby in flight, its gradient settles into the flat blue of the ball, and [onProgress]
|
||||||
|
* (0 to 1) lets the page behind sink a little. Calls [onCovered] once nothing but blue shows.
|
||||||
|
* Swallows touches while it runs.
|
||||||
|
*/
|
||||||
|
@Composable
|
||||||
|
internal fun LaunchFlood(from: Rect, onProgress: (Float) -> Unit, onCovered: () -> Unit) {
|
||||||
|
val colors = MaterialTheme.colorScheme
|
||||||
|
val pal = LocalPalette.current
|
||||||
|
// Left, top, right, bottom: 0 on the button, 1 on the page's edge. Springs overshoot past the
|
||||||
|
// edge, off the page, so the wobble is felt in the pull and never seen as a shrink.
|
||||||
|
val edges = remember { List(4) { Animatable(0f) } }
|
||||||
|
val covered by rememberUpdatedState(onCovered)
|
||||||
|
val progress by rememberUpdatedState(onProgress)
|
||||||
|
var page by remember { mutableStateOf(Size.Zero) }
|
||||||
|
LaunchedEffect(page != Size.Zero) {
|
||||||
|
if (page == Size.Zero) return@LaunchedEffect
|
||||||
|
val travel = listOf(from.left, from.top, page.width - from.right, page.height - from.bottom).map { it.coerceAtLeast(0f) }
|
||||||
|
val far = travel.max().coerceAtLeast(1f)
|
||||||
|
coroutineScope {
|
||||||
|
val runs = edges.mapIndexed { i, edge ->
|
||||||
|
val lead = travel[i] / far
|
||||||
|
launch {
|
||||||
|
delay(Motion.ms((180 * (1f - lead)).toInt()).toLong())
|
||||||
|
edge.animateTo(1f, spring(dampingRatio = 0.48f, stiffness = lerp(110f, 190f, lead))) {
|
||||||
|
progress(edges.sumOf { it.value.coerceIn(0f, 1f).toDouble() }.toFloat() / 4f)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Covered once every edge has reached the page's, the first time round.
|
||||||
|
snapshotFlow { edges.all { it.value >= 0.995f } }.first { it }
|
||||||
|
covered()
|
||||||
|
runs.forEach { it.join() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Canvas(Modifier.fillMaxSize().onSizeChanged { page = Size(it.width.toFloat(), it.height.toFloat()) }.pointerInput(Unit) { awaitEachGesture { while (true) awaitPointerEvent().changes.forEach { it.consume() } } }) {
|
||||||
|
val (l, t, r, b) = edges.map { it.value }
|
||||||
|
val mean = edges.sumOf { it.value.coerceIn(0f, 1f).toDouble() }.toFloat() / 4f
|
||||||
|
// The button sinks with the page behind (FloodBehind), so the flood leaves from where it is now.
|
||||||
|
val k = sinkScale(mean)
|
||||||
|
val cx = size.width / 2f
|
||||||
|
val cy = size.height / 2f
|
||||||
|
val left = lerp(cx + (from.left - cx) * k, 0f, l)
|
||||||
|
val top = lerp(cy + (from.top - cy) * k, 0f, t)
|
||||||
|
val right = lerp(cx + (from.right - cx) * k, size.width, r)
|
||||||
|
val bottom = lerp(cy + (from.bottom - cy) * k, size.height, b)
|
||||||
|
val w = (right - left).coerceAtLeast(0f)
|
||||||
|
val h = (bottom - top).coerceAtLeast(0f)
|
||||||
|
// A button's corners at rest, a blob in flight, square once it fills the page.
|
||||||
|
val blob = kotlin.math.sin(Math.PI * mean).toFloat().coerceAtLeast(0f)
|
||||||
|
val corner = lerp(12.dp.toPx() * (1f - mean), minOf(w, h) * 0.42f, blob)
|
||||||
|
// The button's gradient gives way to the ball's flat blue in the first half.
|
||||||
|
val mix = (mean * 2f).coerceAtMost(1f)
|
||||||
|
drawRoundRect(
|
||||||
|
Brush.linearGradient(
|
||||||
|
listOf(lerp(colors.primary, pal.signal, mix), lerp(pal.primary2, pal.signal, mix)),
|
||||||
|
start = Offset(left, top), end = Offset(right, bottom),
|
||||||
|
),
|
||||||
|
topLeft = Offset(left, top), size = Size(w, h), cornerRadius = CornerRadius(corner),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The session's first frames: the page in [flood], drawing in to a circle over [ball] (centre and
|
||||||
|
* radius in root px, once the throbber is laid out) that lands the size of it. Calls [onLanded] then.
|
||||||
|
*/
|
||||||
|
@Composable
|
||||||
|
internal fun FloodGather(flood: Color, ball: Pair<Offset, Float>?, onLanded: () -> Unit) {
|
||||||
|
val gather = remember { Animatable(0f) }
|
||||||
|
var started by remember { mutableStateOf(false) }
|
||||||
|
val landed by rememberUpdatedState(onLanded)
|
||||||
|
LaunchedEffect(ball != null) {
|
||||||
|
if (ball == null || started) return@LaunchedEffect
|
||||||
|
started = true
|
||||||
|
// A beat of plain blue first, so the change of screen does not read as a cut.
|
||||||
|
delay(Motion.ms(90).toLong())
|
||||||
|
gather.animateTo(1f, tween(Motion.ms(640).coerceAtLeast(1), easing = Gather))
|
||||||
|
landed()
|
||||||
|
}
|
||||||
|
Canvas(Modifier.fillMaxSize().pointerInput(Unit) { awaitEachGesture { while (true) awaitPointerEvent().changes.forEach { it.consume() } } }) {
|
||||||
|
val b = ball
|
||||||
|
if (b == null) {
|
||||||
|
drawRect(flood)
|
||||||
|
return@Canvas
|
||||||
|
}
|
||||||
|
val (c, r) = b
|
||||||
|
val far = maxOf(hypot(c.x, c.y), hypot(size.width - c.x, c.y), hypot(c.x, size.height - c.y), hypot(size.width - c.x, size.height - c.y))
|
||||||
|
drawCircle(flood, radius = lerp(far, r, gather.value), center = c)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -94,7 +94,7 @@ private fun CompactGateInstructions(
|
|||||||
)
|
)
|
||||||
Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) {
|
Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||||
PrimaryButton("Open Developer options", compact = true, onClick = onOpenDeveloperOptions)
|
PrimaryButton("Open Developer options", compact = true, onClick = onOpenDeveloperOptions)
|
||||||
SecondaryButton("Use on-device ADB", compact = true, onClick = onSetUpWirelessAdb)
|
SecondaryButton("Use Wireless debugging", compact = true, onClick = onSetUpWirelessAdb)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -133,7 +133,7 @@ private fun GateInstructions(
|
|||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
)
|
)
|
||||||
PrimaryButton("Open Developer options", onClick = onOpenDeveloperOptions)
|
PrimaryButton("Open Developer options", onClick = onOpenDeveloperOptions)
|
||||||
SecondaryButton("Use on-device ADB", onClick = onSetUpWirelessAdb)
|
SecondaryButton("Use Wireless debugging", onClick = onSetUpWirelessAdb)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -33,7 +33,7 @@ fun ProtonPage(
|
|||||||
val colors = MaterialTheme.colorScheme
|
val colors = MaterialTheme.colorScheme
|
||||||
SettingsPage(
|
SettingsPage(
|
||||||
host,
|
host,
|
||||||
title = "Compatibility tools",
|
title = "Proton versions",
|
||||||
eyebrow = "Setup",
|
eyebrow = "Setup",
|
||||||
lede = "Download and install an ARM64 Proton build now, then select it per game in Steam > Properties > Compatibility.",
|
lede = "Download and install an ARM64 Proton build now, then select it per game in Steam > Properties > Compatibility.",
|
||||||
onBack = onBack,
|
onBack = onBack,
|
||||||
|
|||||||
@@ -0,0 +1,313 @@
|
|||||||
|
package com.droiddeck.launcher.ui
|
||||||
|
|
||||||
|
import androidx.compose.animation.core.animateFloat
|
||||||
|
import androidx.compose.animation.core.infiniteRepeatable
|
||||||
|
import androidx.compose.animation.core.rememberInfiniteTransition
|
||||||
|
import androidx.compose.runtime.produceState
|
||||||
|
import androidx.compose.runtime.key
|
||||||
|
import androidx.compose.ui.layout.boundsInRoot
|
||||||
|
import androidx.compose.ui.layout.onGloballyPositioned
|
||||||
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.ui.draw.alpha
|
||||||
|
import androidx.compose.ui.draw.drawBehind
|
||||||
|
import androidx.compose.ui.geometry.Offset
|
||||||
|
import androidx.compose.ui.geometry.Size
|
||||||
|
import androidx.compose.ui.platform.LocalContext
|
||||||
|
import androidx.compose.ui.semantics.Role
|
||||||
|
import com.droiddeck.launcher.frontend.Library
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
|
import androidx.compose.animation.core.FastOutSlowInEasing
|
||||||
|
import androidx.compose.animation.core.tween
|
||||||
|
import androidx.compose.material.icons.Icons
|
||||||
|
import androidx.compose.foundation.layout.heightIn
|
||||||
|
import androidx.compose.material.icons.filled.Pause
|
||||||
|
import androidx.compose.foundation.rememberScrollState
|
||||||
|
import androidx.compose.material3.Icon
|
||||||
|
import androidx.compose.foundation.background
|
||||||
|
import androidx.compose.foundation.clickable
|
||||||
|
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||||
|
import androidx.compose.foundation.layout.Box
|
||||||
|
import androidx.compose.foundation.layout.Column
|
||||||
|
import androidx.compose.foundation.layout.Row
|
||||||
|
import androidx.compose.foundation.layout.Spacer
|
||||||
|
import androidx.compose.foundation.layout.fillMaxSize
|
||||||
|
import androidx.compose.foundation.layout.height
|
||||||
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.foundation.layout.size
|
||||||
|
import androidx.compose.foundation.layout.width
|
||||||
|
import androidx.compose.foundation.layout.widthIn
|
||||||
|
import androidx.compose.foundation.verticalScroll
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.LaunchedEffect
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.graphics.Color
|
||||||
|
import androidx.compose.ui.text.font.FontFamily
|
||||||
|
import androidx.compose.ui.text.style.TextAlign
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import androidx.compose.ui.unit.sp
|
||||||
|
import androidx.compose.foundation.LocalIndication
|
||||||
|
import androidx.compose.foundation.border
|
||||||
|
import androidx.compose.foundation.hoverable
|
||||||
|
import androidx.compose.foundation.interaction.collectIsFocusedAsState
|
||||||
|
import androidx.compose.foundation.interaction.collectIsHoveredAsState
|
||||||
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
|
import androidx.compose.foundation.shape.CircleShape
|
||||||
|
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.mutableStateOf
|
||||||
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.runtime.setValue
|
||||||
|
import androidx.compose.ui.draw.clip
|
||||||
|
import androidx.compose.ui.focus.FocusRequester
|
||||||
|
import androidx.compose.ui.focus.focusRequester
|
||||||
|
import androidx.compose.ui.graphics.Brush
|
||||||
|
import androidx.compose.ui.semantics.contentDescription
|
||||||
|
import androidx.compose.ui.semantics.semantics
|
||||||
|
import androidx.compose.ui.text.font.FontWeight
|
||||||
|
import androidx.compose.ui.text.style.TextOverflow
|
||||||
|
|
||||||
|
// The session's loading screen, its paused screen and the HUD text style.
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
fun HudText(text: String) {
|
||||||
|
Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.TopEnd) {
|
||||||
|
Text(
|
||||||
|
text,
|
||||||
|
fontFamily = FontFamily.Monospace,
|
||||||
|
fontSize = 12.sp,
|
||||||
|
color = Color.White,
|
||||||
|
modifier = Modifier
|
||||||
|
.padding(12.dp)
|
||||||
|
.background(Color(0x8C000000))
|
||||||
|
.padding(horizontal = 8.dp, vertical = 3.dp),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One line of the loading screen's checklist; [detail] is what it says while it is the one running. */
|
||||||
|
private class LoadStage(val label: String, val detail: String)
|
||||||
|
|
||||||
|
private fun loadStages(steam: Boolean): List<LoadStage> = if (steam) listOf(
|
||||||
|
LoadStage("Linux runtime", "Getting the Linux runtime ready"),
|
||||||
|
LoadStage("Session", "Starting the display and audio"),
|
||||||
|
LoadStage("Steam client", "Checking the Steam client and its compatibility tools"),
|
||||||
|
LoadStage("Opening Steam", "Waiting for Steam's first frame"),
|
||||||
|
) else listOf(
|
||||||
|
LoadStage("Linux runtime", "Getting the Linux runtime ready"),
|
||||||
|
LoadStage("Desktop", "Getting the desktop ready"),
|
||||||
|
LoadStage("Opening", "Waiting for the first frame"),
|
||||||
|
)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The checklist stage a loading line belongs to, -1 when it says nothing about the stage. The lines
|
||||||
|
* are the session script's "== STEP" milestones and the installer's own progress; they arrive in
|
||||||
|
* order, and the screen never steps back.
|
||||||
|
*/
|
||||||
|
private fun stageOf(step: String, steam: Boolean): Int {
|
||||||
|
val t = step.lowercase()
|
||||||
|
return when {
|
||||||
|
"linux runtime" in t -> 0
|
||||||
|
"starting the session" in t -> 1
|
||||||
|
!steam && "desktop" in t -> 1
|
||||||
|
steam && "starting the steam client" in t -> 3
|
||||||
|
steam && ("steam" in t || "client" in t || "proton" in t || "library" in t || "compatibility" in t) -> 2
|
||||||
|
else -> -1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Download and install lines are worth reading as they are; the script's own notes are not. */
|
||||||
|
private fun readableStep(step: String): Boolean {
|
||||||
|
val t = step.lowercase()
|
||||||
|
return t.startsWith("download") || t.startsWith("checking the linux") || t.startsWith("unpacking") || t.startsWith("installing")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
fun LoadingOverlay(
|
||||||
|
step: String, percent: Int, elapsed: String, hint: String, ended: Boolean,
|
||||||
|
title: String = "Starting Steam", steam: Boolean = true, onCancel: (() -> Unit)? = null,
|
||||||
|
/** An ended session's exit status and log path, shown small under the advice. */
|
||||||
|
endedDetail: String? = null,
|
||||||
|
onRetry: (() -> Unit)? = null,
|
||||||
|
onShareLogs: (() -> Unit)? = null,
|
||||||
|
onClose: (() -> Unit)? = null,
|
||||||
|
/** The blue the page opens on when a button flooded to it, gathered into the throbber's ball. */
|
||||||
|
flood: Color? = null,
|
||||||
|
onFlooded: () -> Unit = {},
|
||||||
|
) {
|
||||||
|
val colors = MaterialTheme.colorScheme
|
||||||
|
var ball by remember { mutableStateOf<Pair<Offset, Float>?>(null) }
|
||||||
|
val stages = remember(steam) { loadStages(steam) }
|
||||||
|
var reached by remember { mutableStateOf(0) }
|
||||||
|
LaunchedEffect(step, steam) {
|
||||||
|
val at = stageOf(step, steam)
|
||||||
|
if (at > reached) reached = at
|
||||||
|
}
|
||||||
|
val active = reached.coerceAtMost(stages.lastIndex)
|
||||||
|
val detail = if (percent >= 0 || readableStep(step)) step.replaceFirstChar { it.uppercase() } else stages[active].detail
|
||||||
|
val context = LocalContext.current
|
||||||
|
// The Steam tab's wall behind it, dimmed and slowed: starting Steam reads as the same place settling in.
|
||||||
|
val games by produceState(emptyList<Library.SteamGame>()) {
|
||||||
|
value = withContext(Dispatchers.IO) { runCatching { Library.steamGames(context).sortedByDescending { it.lastPlayed } }.getOrDefault(emptyList()) }
|
||||||
|
}
|
||||||
|
Box(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxSize()
|
||||||
|
.background(colors.background)
|
||||||
|
.clickable(interactionSource = remember { MutableInteractionSource() }, indication = null) {},
|
||||||
|
) {
|
||||||
|
CapsuleWall(games, driftMs = 65_000, modifier = Modifier.alpha(0.3f))
|
||||||
|
Box(
|
||||||
|
Modifier.fillMaxSize().drawBehind {
|
||||||
|
drawRect(
|
||||||
|
Brush.radialGradient(
|
||||||
|
0f to colors.background.copy(alpha = 0.94f),
|
||||||
|
0.6f to colors.background.copy(alpha = 0.72f),
|
||||||
|
1f to colors.background.copy(alpha = 0.55f),
|
||||||
|
center = Offset(size.width / 2f, size.height * 0.46f), radius = maxOf(size.width, size.height) * 0.55f,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
},
|
||||||
|
)
|
||||||
|
Box(Modifier.fillMaxSize().background(Brush.verticalGradient(0.7f to Color.Transparent, 1f to colors.background.copy(alpha = 0.95f))))
|
||||||
|
Column(
|
||||||
|
horizontalAlignment = Alignment.CenterHorizontally,
|
||||||
|
modifier = Modifier.align(Alignment.Center).verticalScroll(rememberScrollState()).padding(horizontal = 32.dp, vertical = 24.dp),
|
||||||
|
) {
|
||||||
|
// Held on the plain D while the flood gathers, and started fresh when it lands.
|
||||||
|
key(flood == null) {
|
||||||
|
LogoThrobber(
|
||||||
|
Modifier.width(if (ended) 88.dp else 110.dp).onGloballyPositioned { ball = throbberBall(it.boundsInRoot()) },
|
||||||
|
running = !ended && flood == null,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
Spacer(Modifier.height(30.dp))
|
||||||
|
Text(
|
||||||
|
if (ended) "The session ended" else title, fontSize = 20.sp, fontWeight = FontWeight.SemiBold,
|
||||||
|
color = colors.onBackground, textAlign = TextAlign.Center, maxLines = 2, overflow = TextOverflow.Ellipsis,
|
||||||
|
)
|
||||||
|
Text(
|
||||||
|
if (ended) step else detail, fontSize = 14.sp, lineHeight = 20.sp, color = colors.onSurfaceVariant, textAlign = TextAlign.Center,
|
||||||
|
maxLines = if (ended) 12 else 2, overflow = TextOverflow.Ellipsis,
|
||||||
|
modifier = Modifier.padding(top = 6.dp).widthIn(max = 520.dp),
|
||||||
|
)
|
||||||
|
if (!ended) LoadSegments(stages.size, active, percent, Modifier.padding(top = 18.dp))
|
||||||
|
if (ended && endedDetail != null) Text(
|
||||||
|
endedDetail, fontSize = 12.sp, fontFamily = FontFamily.Monospace, color = colors.onSurfaceVariant.copy(alpha = 0.8f),
|
||||||
|
textAlign = TextAlign.Center, maxLines = 3, overflow = TextOverflow.Ellipsis,
|
||||||
|
modifier = Modifier.padding(top = 12.dp).widthIn(max = 520.dp),
|
||||||
|
)
|
||||||
|
if (ended) EndedActions(onRetry, onShareLogs, onClose)
|
||||||
|
}
|
||||||
|
if (!ended && hint.isNotEmpty()) Text(
|
||||||
|
hint, fontSize = 13.sp, lineHeight = 18.sp, color = colors.onSurfaceVariant.copy(alpha = 0.8f), textAlign = TextAlign.Center,
|
||||||
|
maxLines = 3, overflow = TextOverflow.Ellipsis,
|
||||||
|
modifier = Modifier.align(Alignment.BottomCenter).padding(start = 120.dp, end = 120.dp, bottom = 28.dp),
|
||||||
|
)
|
||||||
|
if (!ended && onCancel != null) CancelHint(onCancel, Modifier.align(Alignment.BottomEnd).padding(end = 16.dp, bottom = 16.dp))
|
||||||
|
if (flood != null) FloodGather(flood, ball, onFlooded)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** What to do about an ended session: nothing leaves on a timer, and the pad starts on Try again. */
|
||||||
|
@Composable
|
||||||
|
private fun EndedActions(onRetry: (() -> Unit)?, onShareLogs: (() -> Unit)?, onClose: (() -> Unit)?) {
|
||||||
|
val first = remember { FocusRequester() }
|
||||||
|
LaunchedEffect(Unit) {
|
||||||
|
androidx.compose.runtime.withFrameNanos { }
|
||||||
|
runCatching { first.requestFocus() }
|
||||||
|
}
|
||||||
|
Row(horizontalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.padding(top = 22.dp)) {
|
||||||
|
var firstUsed = false
|
||||||
|
fun claim(): Modifier = if (firstUsed) Modifier else { firstUsed = true; Modifier.focusRequester(first) }
|
||||||
|
if (onRetry != null) PrimaryButton("Try again", modifier = claim(), onClick = onRetry)
|
||||||
|
if (onShareLogs != null) SecondaryButton("Share logs", modifier = claim(), onClick = onShareLogs)
|
||||||
|
if (onClose != null) SecondaryButton("Back", modifier = claim(), onClick = onClose)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One segment per stage: done ones filled, the current one filling (or running, with no percent). */
|
||||||
|
@Composable
|
||||||
|
private fun LoadSegments(count: Int, active: Int, percent: Int, modifier: Modifier = Modifier) {
|
||||||
|
val pal = LocalPalette.current
|
||||||
|
val track = MaterialTheme.colorScheme.onBackground.copy(alpha = 0.12f)
|
||||||
|
val run = rememberInfiniteTransition(label = "segment")
|
||||||
|
.animateFloat(-0.4f, 1f, infiniteRepeatable(tween(Motion.ms(1300).coerceAtLeast(1), easing = FastOutSlowInEasing)), label = "run")
|
||||||
|
val still = Motion.scale == 0f
|
||||||
|
Row(
|
||||||
|
horizontalArrangement = Arrangement.spacedBy(6.dp),
|
||||||
|
modifier = modifier.semantics { contentDescription = "Step ${active + 1} of $count" },
|
||||||
|
) {
|
||||||
|
repeat(count) { i ->
|
||||||
|
Box(
|
||||||
|
Modifier.width(44.dp).height(3.dp).clip(RoundedCornerShape(2.dp))
|
||||||
|
.background(if (i < active) pal.signal else track)
|
||||||
|
.drawBehind {
|
||||||
|
if (i != active) return@drawBehind
|
||||||
|
if (percent >= 0) drawRect(pal.signal, size = Size(size.width * percent.coerceIn(0, 100) / 100f, size.height))
|
||||||
|
else if (still) drawRect(pal.signal.copy(alpha = 0.5f))
|
||||||
|
else drawRect(pal.signal, topLeft = Offset(size.width * run.value, 0f), size = Size(size.width * 0.4f, size.height))
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Cancel as the pad's B, in the corner; a tap works too. */
|
||||||
|
@Composable
|
||||||
|
private fun CancelHint(onCancel: () -> Unit, modifier: Modifier = Modifier) {
|
||||||
|
val colors = MaterialTheme.colorScheme
|
||||||
|
val src = remember { MutableInteractionSource() }
|
||||||
|
val hot = src.collectIsHoveredAsState().value || src.collectIsFocusedAsState().value
|
||||||
|
Row(
|
||||||
|
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||||
|
modifier = modifier.heightIn(min = 44.dp).clip(RoundedCornerShape(22.dp))
|
||||||
|
.background(if (hot) colors.onBackground.copy(alpha = 0.08f) else Color.Transparent)
|
||||||
|
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Button, onClick = onCancel)
|
||||||
|
.padding(horizontal = 12.dp),
|
||||||
|
) {
|
||||||
|
Box(contentAlignment = Alignment.Center, modifier = Modifier.size(20.dp).clip(CircleShape).background(colors.onBackground)) {
|
||||||
|
Text("B", fontSize = 12.sp, fontWeight = FontWeight.Bold, color = colors.background)
|
||||||
|
}
|
||||||
|
Text("Cancel", fontSize = 13.sp, color = colors.onSurfaceVariant)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A session paused in the background, ready to pick up where it left off. */
|
||||||
|
@Composable
|
||||||
|
fun SessionPausedOverlay(title: String = "Steam is paused", onResume: () -> Unit) {
|
||||||
|
val colors = MaterialTheme.colorScheme
|
||||||
|
val pal = LocalPalette.current
|
||||||
|
val interactionSource = remember { MutableInteractionSource() }
|
||||||
|
val resumeFocus = remember { FocusRequester() }
|
||||||
|
LaunchedEffect(Unit) {
|
||||||
|
androidx.compose.runtime.withFrameNanos { }
|
||||||
|
runCatching { resumeFocus.requestFocus() }
|
||||||
|
}
|
||||||
|
Box(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxSize()
|
||||||
|
.background(pal.background.copy(alpha = 0.94f))
|
||||||
|
.clickable(interactionSource = interactionSource, indication = null) {},
|
||||||
|
contentAlignment = Alignment.Center,
|
||||||
|
) {
|
||||||
|
Column(
|
||||||
|
horizontalAlignment = Alignment.CenterHorizontally,
|
||||||
|
verticalArrangement = Arrangement.spacedBy(10.dp),
|
||||||
|
modifier = Modifier.widthIn(max = 440.dp).padding(32.dp),
|
||||||
|
) {
|
||||||
|
Box(contentAlignment = Alignment.Center, modifier = Modifier.padding(bottom = 6.dp).size(64.dp).border(2.dp, pal.line2, CircleShape)) {
|
||||||
|
Icon(Icons.Filled.Pause, contentDescription = null, tint = colors.onBackground, modifier = Modifier.size(30.dp))
|
||||||
|
}
|
||||||
|
Text(title, fontSize = 28.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, textAlign = TextAlign.Center)
|
||||||
|
PrimaryButton(
|
||||||
|
"Resume",
|
||||||
|
modifier = Modifier.padding(top = 14.dp).focusRequester(resumeFocus).controllerConfirm(onClick = onResume),
|
||||||
|
onClick = onResume,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,31 +1,15 @@
|
|||||||
package com.droiddeck.launcher.ui
|
package com.droiddeck.launcher.ui
|
||||||
|
|
||||||
import androidx.compose.animation.core.animateFloat
|
|
||||||
import androidx.compose.animation.core.infiniteRepeatable
|
|
||||||
import androidx.compose.animation.core.rememberInfiniteTransition
|
|
||||||
import androidx.compose.runtime.produceState
|
|
||||||
import androidx.compose.ui.draw.alpha
|
import androidx.compose.ui.draw.alpha
|
||||||
import androidx.compose.ui.draw.drawBehind
|
|
||||||
import androidx.compose.ui.geometry.Offset
|
|
||||||
import androidx.compose.ui.geometry.Size
|
|
||||||
import androidx.compose.ui.platform.LocalContext
|
|
||||||
import androidx.compose.ui.semantics.Role
|
|
||||||
import com.droiddeck.launcher.frontend.Library
|
|
||||||
import kotlinx.coroutines.Dispatchers
|
|
||||||
import kotlinx.coroutines.withContext
|
|
||||||
import androidx.compose.animation.core.FastOutSlowInEasing
|
import androidx.compose.animation.core.FastOutSlowInEasing
|
||||||
import androidx.compose.animation.core.tween
|
import androidx.compose.animation.core.tween
|
||||||
import androidx.compose.foundation.layout.offset
|
import androidx.compose.foundation.layout.offset
|
||||||
import androidx.compose.material.icons.Icons
|
import androidx.compose.material.icons.Icons
|
||||||
import androidx.compose.foundation.layout.heightIn
|
import androidx.compose.foundation.layout.heightIn
|
||||||
import androidx.compose.material.icons.filled.Pause
|
|
||||||
import androidx.compose.material.icons.outlined.Menu
|
import androidx.compose.material.icons.outlined.Menu
|
||||||
import androidx.compose.material.icons.outlined.MoreHoriz
|
import androidx.compose.material.icons.outlined.MoreHoriz
|
||||||
import androidx.compose.material.icons.outlined.PowerSettingsNew
|
import androidx.compose.material.icons.outlined.PowerSettingsNew
|
||||||
import androidx.compose.runtime.CompositionLocalProvider
|
import androidx.compose.runtime.CompositionLocalProvider
|
||||||
import androidx.compose.material.icons.filled.Check
|
|
||||||
import androidx.compose.material3.CircularProgressIndicator
|
|
||||||
import androidx.compose.foundation.rememberScrollState
|
|
||||||
import androidx.compose.material.icons.outlined.DesktopWindows
|
import androidx.compose.material.icons.outlined.DesktopWindows
|
||||||
import androidx.compose.material.icons.outlined.Layers
|
import androidx.compose.material.icons.outlined.Layers
|
||||||
import androidx.compose.material.icons.outlined.Settings
|
import androidx.compose.material.icons.outlined.Settings
|
||||||
@@ -54,10 +38,8 @@ import androidx.compose.foundation.layout.height
|
|||||||
import androidx.compose.foundation.layout.padding
|
import androidx.compose.foundation.layout.padding
|
||||||
import androidx.compose.foundation.layout.size
|
import androidx.compose.foundation.layout.size
|
||||||
import androidx.compose.foundation.layout.width
|
import androidx.compose.foundation.layout.width
|
||||||
import androidx.compose.foundation.layout.widthIn
|
|
||||||
import androidx.compose.foundation.ScrollState
|
import androidx.compose.foundation.ScrollState
|
||||||
import androidx.compose.foundation.verticalScroll
|
import androidx.compose.foundation.verticalScroll
|
||||||
import androidx.compose.material3.LinearProgressIndicator
|
|
||||||
import androidx.compose.material3.MaterialTheme
|
import androidx.compose.material3.MaterialTheme
|
||||||
import androidx.compose.material3.OutlinedButton
|
import androidx.compose.material3.OutlinedButton
|
||||||
import androidx.compose.material3.AlertDialog
|
import androidx.compose.material3.AlertDialog
|
||||||
@@ -70,12 +52,8 @@ import androidx.compose.ui.ExperimentalComposeUiApi
|
|||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
import androidx.compose.ui.graphics.Color
|
import androidx.compose.ui.graphics.Color
|
||||||
import androidx.compose.ui.graphics.asImageBitmap
|
import androidx.compose.ui.graphics.asImageBitmap
|
||||||
import androidx.compose.ui.res.painterResource
|
|
||||||
import androidx.compose.ui.text.font.FontFamily
|
|
||||||
import androidx.compose.ui.text.style.TextAlign
|
|
||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
import androidx.compose.ui.unit.sp
|
import androidx.compose.ui.unit.sp
|
||||||
import com.droiddeck.launcher.R
|
|
||||||
import com.droiddeck.launcher.HomeApp
|
import com.droiddeck.launcher.HomeApp
|
||||||
import androidx.compose.animation.AnimatedVisibility
|
import androidx.compose.animation.AnimatedVisibility
|
||||||
import androidx.compose.animation.animateColorAsState
|
import androidx.compose.animation.animateColorAsState
|
||||||
@@ -92,7 +70,6 @@ import androidx.compose.foundation.hoverable
|
|||||||
import androidx.compose.foundation.interaction.collectIsFocusedAsState
|
import androidx.compose.foundation.interaction.collectIsFocusedAsState
|
||||||
import androidx.compose.foundation.interaction.collectIsHoveredAsState
|
import androidx.compose.foundation.interaction.collectIsHoveredAsState
|
||||||
import androidx.compose.foundation.layout.Arrangement
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
import androidx.compose.foundation.shape.CircleShape
|
|
||||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||||
import androidx.compose.runtime.getValue
|
import androidx.compose.runtime.getValue
|
||||||
import androidx.compose.runtime.mutableStateOf
|
import androidx.compose.runtime.mutableStateOf
|
||||||
@@ -121,8 +98,10 @@ import com.droiddeck.launcher.input.SecondScreenMode
|
|||||||
import kotlinx.coroutines.flow.collect
|
import kotlinx.coroutines.flow.collect
|
||||||
|
|
||||||
private val drawerPageTitles = listOf("Display", "Controls", "Components", "Settings")
|
private val drawerPageTitles = listOf("Display", "Controls", "Components", "Settings")
|
||||||
|
|
||||||
/** One icon per drawer page, in page order (QAM-style tabs). */
|
/** One icon per drawer page, in page order (QAM-style tabs). */
|
||||||
private val drawerPageIcons = listOf(Icons.Outlined.DesktopWindows, Icons.Outlined.SportsEsports, Icons.Outlined.Layers, Icons.Outlined.Settings)
|
private val drawerPageIcons = listOf(Icons.Outlined.DesktopWindows, Icons.Outlined.SportsEsports, Icons.Outlined.Layers, Icons.Outlined.Settings)
|
||||||
|
|
||||||
private val drawerPageEntries = listOf("hud", "touch", "cmp-proton", "suspend")
|
private val drawerPageEntries = listOf("hud", "touch", "cmp-proton", "suspend")
|
||||||
|
|
||||||
private class DrawerFocus {
|
private class DrawerFocus {
|
||||||
@@ -145,205 +124,6 @@ private class DrawerFocus {
|
|||||||
fun forget(page: Int) { last[page] = null }
|
fun forget(page: Int) { last[page] = null }
|
||||||
}
|
}
|
||||||
|
|
||||||
@Composable
|
|
||||||
fun HudText(text: String) {
|
|
||||||
Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.TopEnd) {
|
|
||||||
Text(
|
|
||||||
text,
|
|
||||||
fontFamily = FontFamily.Monospace,
|
|
||||||
fontSize = 12.sp,
|
|
||||||
color = Color.White,
|
|
||||||
modifier = Modifier
|
|
||||||
.padding(12.dp)
|
|
||||||
.background(Color(0x8C000000))
|
|
||||||
.padding(horizontal = 8.dp, vertical = 3.dp),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** One line of the loading screen's checklist; [detail] is what it says while it is the one running. */
|
|
||||||
private class LoadStage(val label: String, val detail: String)
|
|
||||||
|
|
||||||
private fun loadStages(steam: Boolean): List<LoadStage> = if (steam) listOf(
|
|
||||||
LoadStage("Linux runtime", "Getting the Linux runtime ready"),
|
|
||||||
LoadStage("Session", "Starting the display and audio"),
|
|
||||||
LoadStage("Steam client", "Checking the Steam client and its compatibility tools"),
|
|
||||||
LoadStage("Opening Steam", "Waiting for Steam's first frame"),
|
|
||||||
) else listOf(
|
|
||||||
LoadStage("Linux runtime", "Getting the Linux runtime ready"),
|
|
||||||
LoadStage("Desktop", "Getting the desktop ready"),
|
|
||||||
LoadStage("Opening", "Waiting for the first frame"),
|
|
||||||
)
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The checklist stage a loading line belongs to, -1 when it says nothing about the stage. The lines
|
|
||||||
* are the session script's "== STEP" milestones and the installer's own progress; they arrive in
|
|
||||||
* order, and the screen never steps back.
|
|
||||||
*/
|
|
||||||
private fun stageOf(step: String, steam: Boolean): Int {
|
|
||||||
val t = step.lowercase()
|
|
||||||
return when {
|
|
||||||
"linux runtime" in t -> 0
|
|
||||||
"starting the session" in t -> 1
|
|
||||||
!steam && "desktop" in t -> 1
|
|
||||||
steam && "starting the steam client" in t -> 3
|
|
||||||
steam && ("steam" in t || "client" in t || "proton" in t || "library" in t || "compatibility" in t) -> 2
|
|
||||||
else -> -1
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Download and install lines are worth reading as they are; the script's own notes are not. */
|
|
||||||
private fun readableStep(step: String): Boolean {
|
|
||||||
val t = step.lowercase()
|
|
||||||
return t.startsWith("download") || t.startsWith("checking the linux") || t.startsWith("unpacking") || t.startsWith("installing")
|
|
||||||
}
|
|
||||||
|
|
||||||
@Composable
|
|
||||||
fun LoadingOverlay(
|
|
||||||
step: String, percent: Int, elapsed: String, hint: String, ended: Boolean,
|
|
||||||
title: String = "Starting Steam", steam: Boolean = true, onCancel: (() -> Unit)? = null,
|
|
||||||
) {
|
|
||||||
val colors = MaterialTheme.colorScheme
|
|
||||||
val stages = remember(steam) { loadStages(steam) }
|
|
||||||
var reached by remember { mutableStateOf(0) }
|
|
||||||
LaunchedEffect(step, steam) {
|
|
||||||
val at = stageOf(step, steam)
|
|
||||||
if (at > reached) reached = at
|
|
||||||
}
|
|
||||||
val active = reached.coerceAtMost(stages.lastIndex)
|
|
||||||
val detail = if (percent >= 0 || readableStep(step)) step.replaceFirstChar { it.uppercase() } else stages[active].detail
|
|
||||||
val context = LocalContext.current
|
|
||||||
// The Steam tab's wall behind it, dimmed and slowed: starting Steam reads as the same place settling in.
|
|
||||||
val games by produceState(emptyList<Library.SteamGame>()) {
|
|
||||||
value = withContext(Dispatchers.IO) { runCatching { Library.steamGames(context).sortedByDescending { it.lastPlayed } }.getOrDefault(emptyList()) }
|
|
||||||
}
|
|
||||||
Box(
|
|
||||||
modifier = Modifier
|
|
||||||
.fillMaxSize()
|
|
||||||
.background(colors.background)
|
|
||||||
.clickable(interactionSource = remember { MutableInteractionSource() }, indication = null) {},
|
|
||||||
) {
|
|
||||||
CapsuleWall(games, driftMs = 65_000, modifier = Modifier.alpha(0.3f))
|
|
||||||
Box(
|
|
||||||
Modifier.fillMaxSize().drawBehind {
|
|
||||||
drawRect(
|
|
||||||
Brush.radialGradient(
|
|
||||||
0f to colors.background.copy(alpha = 0.94f),
|
|
||||||
0.6f to colors.background.copy(alpha = 0.72f),
|
|
||||||
1f to colors.background.copy(alpha = 0.55f),
|
|
||||||
center = Offset(size.width / 2f, size.height * 0.46f), radius = maxOf(size.width, size.height) * 0.55f,
|
|
||||||
),
|
|
||||||
)
|
|
||||||
},
|
|
||||||
)
|
|
||||||
Box(Modifier.fillMaxSize().background(Brush.verticalGradient(0.7f to Color.Transparent, 1f to colors.background.copy(alpha = 0.95f))))
|
|
||||||
Column(
|
|
||||||
horizontalAlignment = Alignment.CenterHorizontally,
|
|
||||||
modifier = Modifier.align(Alignment.Center).verticalScroll(rememberScrollState()).padding(horizontal = 32.dp, vertical = 24.dp),
|
|
||||||
) {
|
|
||||||
LogoThrobber(Modifier.width(if (ended) 88.dp else 110.dp), running = !ended)
|
|
||||||
Spacer(Modifier.height(30.dp))
|
|
||||||
Text(
|
|
||||||
if (ended) "The session ended" else title, fontSize = 20.sp, fontWeight = FontWeight.SemiBold,
|
|
||||||
color = colors.onBackground, textAlign = TextAlign.Center, maxLines = 2, overflow = TextOverflow.Ellipsis,
|
|
||||||
)
|
|
||||||
Text(
|
|
||||||
if (ended) step else detail, fontSize = 14.sp, lineHeight = 20.sp, color = colors.onSurfaceVariant, textAlign = TextAlign.Center,
|
|
||||||
maxLines = if (ended) 12 else 2, overflow = TextOverflow.Ellipsis,
|
|
||||||
modifier = Modifier.padding(top = 6.dp).widthIn(max = 520.dp),
|
|
||||||
)
|
|
||||||
if (!ended) LoadSegments(stages.size, active, percent, Modifier.padding(top = 18.dp))
|
|
||||||
}
|
|
||||||
if (!ended && hint.isNotEmpty()) Text(
|
|
||||||
hint, fontSize = 13.sp, lineHeight = 18.sp, color = colors.onSurfaceVariant.copy(alpha = 0.8f), textAlign = TextAlign.Center,
|
|
||||||
maxLines = 3, overflow = TextOverflow.Ellipsis,
|
|
||||||
modifier = Modifier.align(Alignment.BottomCenter).padding(start = 120.dp, end = 120.dp, bottom = 28.dp),
|
|
||||||
)
|
|
||||||
if (!ended && onCancel != null) CancelHint(onCancel, Modifier.align(Alignment.BottomEnd).padding(end = 16.dp, bottom = 16.dp))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** One segment per stage: done ones filled, the current one filling (or running, with no percent). */
|
|
||||||
@Composable
|
|
||||||
private fun LoadSegments(count: Int, active: Int, percent: Int, modifier: Modifier = Modifier) {
|
|
||||||
val pal = LocalPalette.current
|
|
||||||
val track = MaterialTheme.colorScheme.onBackground.copy(alpha = 0.12f)
|
|
||||||
val run = rememberInfiniteTransition(label = "segment")
|
|
||||||
.animateFloat(-0.4f, 1f, infiniteRepeatable(tween(1300, easing = FastOutSlowInEasing)), label = "run")
|
|
||||||
Row(
|
|
||||||
horizontalArrangement = Arrangement.spacedBy(6.dp),
|
|
||||||
modifier = modifier.semantics { contentDescription = "Step ${active + 1} of $count" },
|
|
||||||
) {
|
|
||||||
repeat(count) { i ->
|
|
||||||
Box(
|
|
||||||
Modifier.width(44.dp).height(3.dp).clip(RoundedCornerShape(2.dp))
|
|
||||||
.background(if (i < active) pal.signal else track)
|
|
||||||
.drawBehind {
|
|
||||||
if (i != active) return@drawBehind
|
|
||||||
if (percent >= 0) drawRect(pal.signal, size = Size(size.width * percent.coerceIn(0, 100) / 100f, size.height))
|
|
||||||
else drawRect(pal.signal, topLeft = Offset(size.width * run.value, 0f), size = Size(size.width * 0.4f, size.height))
|
|
||||||
},
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Cancel as the pad's B, in the corner; a tap works too. */
|
|
||||||
@Composable
|
|
||||||
private fun CancelHint(onCancel: () -> Unit, modifier: Modifier = Modifier) {
|
|
||||||
val colors = MaterialTheme.colorScheme
|
|
||||||
val src = remember { MutableInteractionSource() }
|
|
||||||
val hot = src.collectIsHoveredAsState().value || src.collectIsFocusedAsState().value
|
|
||||||
Row(
|
|
||||||
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp),
|
|
||||||
modifier = modifier.heightIn(min = 44.dp).clip(RoundedCornerShape(22.dp))
|
|
||||||
.background(if (hot) colors.onBackground.copy(alpha = 0.08f) else Color.Transparent)
|
|
||||||
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Button, onClick = onCancel)
|
|
||||||
.padding(horizontal = 12.dp),
|
|
||||||
) {
|
|
||||||
Box(contentAlignment = Alignment.Center, modifier = Modifier.size(20.dp).clip(CircleShape).background(colors.onBackground)) {
|
|
||||||
Text("B", fontSize = 12.sp, fontWeight = FontWeight.Bold, color = colors.background)
|
|
||||||
}
|
|
||||||
Text("Cancel", fontSize = 13.sp, color = colors.onSurfaceVariant)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** A session paused in the background, ready to pick up where it left off. */
|
|
||||||
@Composable
|
|
||||||
fun SessionPausedOverlay(title: String = "Steam is paused", onResume: () -> Unit) {
|
|
||||||
val colors = MaterialTheme.colorScheme
|
|
||||||
val pal = LocalPalette.current
|
|
||||||
val interactionSource = remember { MutableInteractionSource() }
|
|
||||||
val resumeFocus = remember { FocusRequester() }
|
|
||||||
LaunchedEffect(Unit) {
|
|
||||||
androidx.compose.runtime.withFrameNanos { }
|
|
||||||
runCatching { resumeFocus.requestFocus() }
|
|
||||||
}
|
|
||||||
Box(
|
|
||||||
modifier = Modifier
|
|
||||||
.fillMaxSize()
|
|
||||||
.background(pal.background.copy(alpha = 0.94f))
|
|
||||||
.clickable(interactionSource = interactionSource, indication = null) {},
|
|
||||||
contentAlignment = Alignment.Center,
|
|
||||||
) {
|
|
||||||
Column(
|
|
||||||
horizontalAlignment = Alignment.CenterHorizontally,
|
|
||||||
verticalArrangement = Arrangement.spacedBy(10.dp),
|
|
||||||
modifier = Modifier.widthIn(max = 440.dp).padding(32.dp),
|
|
||||||
) {
|
|
||||||
Box(contentAlignment = Alignment.Center, modifier = Modifier.padding(bottom = 6.dp).size(64.dp).border(2.dp, pal.line2, CircleShape)) {
|
|
||||||
Icon(Icons.Filled.Pause, contentDescription = null, tint = colors.onBackground, modifier = Modifier.size(30.dp))
|
|
||||||
}
|
|
||||||
Text(title, fontSize = 28.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, textAlign = TextAlign.Center)
|
|
||||||
PrimaryButton(
|
|
||||||
"Resume",
|
|
||||||
modifier = Modifier.padding(top = 14.dp).focusRequester(resumeFocus).controllerConfirm(onClick = onResume),
|
|
||||||
onClick = onResume,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Everything the drawer shows and does. */
|
/** Everything the drawer shows and does. */
|
||||||
class DrawerActions(
|
class DrawerActions(
|
||||||
val steam: Boolean,
|
val steam: Boolean,
|
||||||
@@ -536,20 +316,11 @@ fun SessionDrawer(open: Boolean, page: Int, controllerActive: Boolean, onPageCha
|
|||||||
chipModifier = focus.track(page, "fill"), onChange = a.onFillScreen,
|
chipModifier = focus.track(page, "fill"), onChange = a.onFillScreen,
|
||||||
)
|
)
|
||||||
val fgOpen = host.open == "fg"
|
val fgOpen = host.open == "fg"
|
||||||
val fgLabel = when (a.frameGenEngine) {
|
val fgLabel = FrameGen.label(a.frameGenEngine, a.frameGenMultiplier)
|
||||||
FrameGen.ENGINE_WINFG -> "Win-FG ${a.frameGenMultiplier}×"
|
|
||||||
FrameGen.ENGINE_LSFG -> "LSFG ${a.frameGenMultiplier}×"
|
|
||||||
else -> "Off"
|
|
||||||
}
|
|
||||||
SettingsRow("Frame generation", null, highlighted = fgOpen) {
|
SettingsRow("Frame generation", null, highlighted = fgOpen) {
|
||||||
Box {
|
Box {
|
||||||
ValueChip(fgLabel, fgOpen, modifier = focus.track(page, "fg")) { host.open = if (fgOpen) null else "fg" }
|
ValueChip(fgLabel, fgOpen, modifier = focus.track(page, "fg")) { host.open = if (fgOpen) null else "fg" }
|
||||||
AnchoredMenu(fgOpen, onDismiss = { if (host.open == "fg") host.open = null }, title = "Frame generation") { firstItemFocus ->
|
FrameGenMenu(host, a.frameGenEngine, a.frameGenMultiplier, a.lsfgReady, a.onFrameGenPick)
|
||||||
val need = if (a.lsfgReady) null else "Requires Lossless Scaling"
|
|
||||||
MenuItem("Off", checked = a.frameGenEngine == FrameGen.ENGINE_OFF, focusRequester = firstItemFocus) { a.onFrameGenPick(FrameGen.ENGINE_OFF, 2); host.open = null }
|
|
||||||
for (m in 2..4) MenuItem("Win-FG ${m}×", checked = a.frameGenEngine == FrameGen.ENGINE_WINFG && a.frameGenMultiplier == m) { a.onFrameGenPick(FrameGen.ENGINE_WINFG, m); host.open = null }
|
|
||||||
for (m in 2..4) MenuItem("LSFG ${m}×", checked = a.frameGenEngine == FrameGen.ENGINE_LSFG && a.frameGenMultiplier == m, enabled = a.lsfgReady, detail = need) { a.onFrameGenPick(FrameGen.ENGINE_LSFG, m); host.open = null }
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -569,16 +340,16 @@ fun SessionDrawer(open: Boolean, page: Int, controllerActive: Boolean, onPageCha
|
|||||||
}
|
}
|
||||||
SettingsGroup("Keyboard") {
|
SettingsGroup("Keyboard") {
|
||||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth().padding(8.dp)) {
|
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth().padding(8.dp)) {
|
||||||
DrawerOutlineButton("Hardware", modifier = Modifier.weight(1f).height(42.dp).then(focus.track(page, "hardware"))) {
|
DrawerOutlineButton("PC keyboard", modifier = Modifier.weight(1f).height(48.dp).then(focus.track(page, "hardware"))) {
|
||||||
host.open = null; a.onHardwareKeyboard()
|
host.open = null; a.onHardwareKeyboard()
|
||||||
}
|
}
|
||||||
DrawerOutlineButton("Android", modifier = Modifier.weight(1f).height(42.dp).then(focus.track(page, "android"))) {
|
DrawerOutlineButton("Android", modifier = Modifier.weight(1f).height(48.dp).then(focus.track(page, "android"))) {
|
||||||
host.open = null; a.onKeyboard()
|
host.open = null; a.onKeyboard()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (a.steam && a.secondScreenDisplays.isNotEmpty()) SettingsGroup("Second screen") {
|
if (a.steam && a.secondScreenDisplays.isNotEmpty()) SettingsGroup("Second screen") {
|
||||||
ChoiceRow(host, "second-screen-mode", "Controls", null,
|
ChoiceRow(host, "second-screen-mode", "Shows", null,
|
||||||
listOf(SecondScreenMode.NONE, SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.TERMINAL).map { it to it.label },
|
listOf(SecondScreenMode.NONE, SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.TERMINAL).map { it to it.label },
|
||||||
a.secondScreenMode, chipModifier = focus.track(page, "second-screen-mode"), onPick = a.onSecondScreenMode)
|
a.secondScreenMode, chipModifier = focus.track(page, "second-screen-mode"), onPick = a.onSecondScreenMode)
|
||||||
if (a.secondScreenDisplays.size > 1) ChoiceRow(host, "second-screen-display", "Display", null,
|
if (a.secondScreenDisplays.size > 1) ChoiceRow(host, "second-screen-display", "Display", null,
|
||||||
@@ -640,7 +411,7 @@ fun SessionDrawer(open: Boolean, page: Int, controllerActive: Boolean, onPageCha
|
|||||||
}
|
}
|
||||||
SettingsGroup("Support") {
|
SettingsGroup("Support") {
|
||||||
SettingsRow("Session logs", "Send this session's logs with a bug report") {
|
SettingsRow("Session logs", "Send this session's logs with a bug report") {
|
||||||
DrawerOutlineButton("Send logs", modifier = focus.track(page, "share-logs")) {
|
DrawerOutlineButton("Share logs", modifier = focus.track(page, "share-logs")) {
|
||||||
host.open = null
|
host.open = null
|
||||||
a.onShareLogs()
|
a.onShareLogs()
|
||||||
}
|
}
|
||||||
@@ -729,7 +500,7 @@ private fun StopSessionButton(modifier: Modifier = Modifier, onClick: () -> Unit
|
|||||||
val shape = RoundedCornerShape(20.dp)
|
val shape = RoundedCornerShape(20.dp)
|
||||||
Row(
|
Row(
|
||||||
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp),
|
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp),
|
||||||
modifier = modifier.heightIn(min = 40.dp).semantics { contentDescription = "Stop session" }
|
modifier = modifier.heightIn(min = 44.dp).semantics { contentDescription = "Stop session" }
|
||||||
.clip(shape).background(fill).border(if (hot) 2.dp else 1.dp, colors.error.copy(alpha = if (hot) 0.9f else 0.55f), shape)
|
.clip(shape).background(fill).border(if (hot) 2.dp else 1.dp, colors.error.copy(alpha = if (hot) 0.9f else 0.55f), shape)
|
||||||
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, onClick = onClick)
|
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, onClick = onClick)
|
||||||
.controllerConfirm(onClick = onClick)
|
.controllerConfirm(onClick = onClick)
|
||||||
@@ -859,6 +630,7 @@ private fun DrawerPageTabs(page: Int, modifier: Modifier = Modifier, compact: Bo
|
|||||||
|
|
||||||
/** Display, Controls, Components, Settings. */
|
/** Display, Controls, Components, Settings. */
|
||||||
const val DRAWER_PAGES = 4
|
const val DRAWER_PAGES = 4
|
||||||
|
|
||||||
private const val DRAWER_PAGE_COMPONENTS = 2
|
private const val DRAWER_PAGE_COMPONENTS = 2
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -987,6 +759,9 @@ private fun <T> DrawerStackedChoice(
|
|||||||
|
|
||||||
/** The tab row's measure, from the approved mock: side tabs at half size, a little faded. */
|
/** The tab row's measure, from the approved mock: side tabs at half size, a little faded. */
|
||||||
private const val DRAWER_TAB_SPACING_DP = 64f
|
private const val DRAWER_TAB_SPACING_DP = 64f
|
||||||
|
|
||||||
private const val DRAWER_TAB_LEAN_DP = 12f
|
private const val DRAWER_TAB_LEAN_DP = 12f
|
||||||
|
|
||||||
private const val DRAWER_TAB_SIDE_SCALE = 0.5f
|
private const val DRAWER_TAB_SIDE_SCALE = 0.5f
|
||||||
|
|
||||||
private const val DRAWER_TAB_SIDE_ALPHA = 0.7f
|
private const val DRAWER_TAB_SIDE_ALPHA = 0.7f
|
||||||
@@ -19,6 +19,8 @@ import androidx.compose.foundation.layout.size
|
|||||||
import androidx.compose.ui.focus.focusProperties
|
import androidx.compose.ui.focus.focusProperties
|
||||||
import androidx.compose.ui.semantics.Role
|
import androidx.compose.ui.semantics.Role
|
||||||
import androidx.compose.ui.semantics.contentDescription
|
import androidx.compose.ui.semantics.contentDescription
|
||||||
|
import androidx.compose.ui.semantics.stateDescription
|
||||||
|
import androidx.compose.foundation.shape.CircleShape
|
||||||
import androidx.compose.ui.semantics.semantics
|
import androidx.compose.ui.semantics.semantics
|
||||||
import androidx.compose.foundation.background
|
import androidx.compose.foundation.background
|
||||||
import androidx.compose.foundation.border
|
import androidx.compose.foundation.border
|
||||||
@@ -149,7 +151,7 @@ internal fun TabStrip(
|
|||||||
.border(2.dp, if (!hot) Color.Transparent else if (on) colors.onBackground else pal.signal, tabShape)
|
.border(2.dp, if (!hot) Color.Transparent else if (on) colors.onBackground else pal.signal, tabShape)
|
||||||
.hoverable(src).clickable(interactionSource = src, indication = null, role = Role.Tab, onClick = pick)
|
.hoverable(src).clickable(interactionSource = src, indication = null, role = Role.Tab, onClick = pick)
|
||||||
.controllerConfirm(onClick = pick)
|
.controllerConfirm(onClick = pick)
|
||||||
.padding(horizontal = 16.dp, vertical = 9.dp),
|
.padding(horizontal = 16.dp, vertical = 12.dp),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -301,6 +303,7 @@ fun ValueChip(text: String, open: Boolean, enabled: Boolean = true, modifier: Mo
|
|||||||
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceBetween,
|
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceBetween,
|
||||||
modifier = modifier
|
modifier = modifier
|
||||||
.widthIn(min = LocalChipMinWidth.current)
|
.widthIn(min = LocalChipMinWidth.current)
|
||||||
|
.heightIn(min = 44.dp)
|
||||||
.clip(RoundedCornerShape(10.dp))
|
.clip(RoundedCornerShape(10.dp))
|
||||||
.background(colors.surfaceVariant)
|
.background(colors.surfaceVariant)
|
||||||
.border(1.dp, edge, RoundedCornerShape(10.dp))
|
.border(1.dp, edge, RoundedCornerShape(10.dp))
|
||||||
@@ -385,7 +388,46 @@ fun <T> ChoiceRow(
|
|||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
fun ToggleRow(host: MenuHost, key: String, label: String, hint: String?, checked: Boolean, enabled: Boolean = true, chipModifier: Modifier = Modifier, onChange: (Boolean) -> Unit) =
|
fun ToggleRow(host: MenuHost, key: String, label: String, hint: String?, checked: Boolean, enabled: Boolean = true, chipModifier: Modifier = Modifier, onChange: (Boolean) -> Unit) =
|
||||||
ChoiceRow(host, key, label, hint, listOf(true to "On", false to "Off"), checked, enabled, chipModifier = chipModifier, onPick = onChange)
|
SettingsRow(label, hint) {
|
||||||
|
ToggleSwitch(checked, enabled, label, chipModifier) { host.open = null; onChange(it) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** An on/off switch: one tap or one A press flips it, where a menu of On and Off took three. */
|
||||||
|
@Composable
|
||||||
|
fun ToggleSwitch(checked: Boolean, enabled: Boolean = true, label: String? = null, modifier: Modifier = Modifier, onChange: (Boolean) -> Unit) {
|
||||||
|
val colors = MaterialTheme.colorScheme
|
||||||
|
val pal = LocalPalette.current
|
||||||
|
val src = remember { MutableInteractionSource() }
|
||||||
|
val hot = src.collectIsFocusedAsState().value || src.collectIsHoveredAsState().value
|
||||||
|
val track by animateColorAsState(if (checked) pal.signal else colors.surfaceVariant, Motion.tw(180), label = "switchTrack")
|
||||||
|
val edge by animateColorAsState(if (hot) pal.signal else if (checked) pal.signal else pal.line2, Motion.tw(180), label = "switchEdge")
|
||||||
|
val knob by animateFloatAsState(if (checked) 1f else 0f, Motion.sp(0.7f), label = "switchKnob")
|
||||||
|
val flip = { onChange(!checked) }
|
||||||
|
val shape = RoundedCornerShape(99.dp)
|
||||||
|
// 48dp tall to touch; the visible track sits inside it.
|
||||||
|
Box(
|
||||||
|
contentAlignment = Alignment.Center,
|
||||||
|
modifier = modifier
|
||||||
|
.heightIn(min = 48.dp).widthIn(min = 64.dp)
|
||||||
|
.alpha(if (enabled) 1f else 0.5f)
|
||||||
|
.hoverable(src)
|
||||||
|
.clickable(interactionSource = src, indication = null, enabled = enabled, role = Role.Switch, onClick = flip)
|
||||||
|
.controllerConfirm(enabled = enabled, onClick = flip)
|
||||||
|
.semantics { stateDescription = if (checked) "On" else "Off"; if (label != null) contentDescription = label },
|
||||||
|
) {
|
||||||
|
Box(
|
||||||
|
Modifier.size(width = 52.dp, height = 30.dp).clip(shape).background(track)
|
||||||
|
.border(if (hot) 2.dp else 1.dp, if (hot && checked) colors.onBackground else edge, shape),
|
||||||
|
) {
|
||||||
|
Box(
|
||||||
|
Modifier.padding(4.dp).size(22.dp)
|
||||||
|
.graphicsLayer { translationX = knob * 22.dp.toPx() }
|
||||||
|
.clip(CircleShape)
|
||||||
|
.background(if (checked) pal.onSignal else colors.onSurfaceVariant),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
fun MultiRow(
|
fun MultiRow(
|
||||||
|
|||||||
@@ -133,8 +133,12 @@ internal fun CapsuleWall(
|
|||||||
// Animations off in the system settings: a still wall.
|
// Animations off in the system settings: a still wall.
|
||||||
val still = Motion.scale == 0f
|
val still = Motion.scale == 0f
|
||||||
BoxWithConstraints(modifier.fillMaxSize()) {
|
BoxWithConstraints(modifier.fillMaxSize()) {
|
||||||
val wallW = maxWidth * 1.3f
|
// Centred on the page and big enough that, once tilted, it still covers every corner.
|
||||||
val wallH = maxHeight * 2.4f
|
val tilt = Math.toRadians(13.0)
|
||||||
|
val cos = kotlin.math.cos(tilt).toFloat()
|
||||||
|
val sin = kotlin.math.sin(tilt).toFloat()
|
||||||
|
val wallW = (maxWidth * cos + maxHeight * sin) * 1.1f
|
||||||
|
val wallH = maxOf(maxHeight * 2.4f, (maxWidth * sin + maxHeight * cos) * 1.1f)
|
||||||
val columns = ((wallW + gap) / (capW + gap)).toInt() + 1
|
val columns = ((wallW + gap) / (capW + gap)).toInt() + 1
|
||||||
val perRun = ((wallH + gap) / (capH + gap)).toInt() + 1
|
val perRun = ((wallH + gap) / (capH + gap)).toInt() + 1
|
||||||
val run = (capH + gap) * perRun
|
val run = (capH + gap) * perRun
|
||||||
@@ -142,7 +146,7 @@ internal fun CapsuleWall(
|
|||||||
horizontalArrangement = Arrangement.spacedBy(gap),
|
horizontalArrangement = Arrangement.spacedBy(gap),
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.wrapContentSize(Alignment.TopStart, unbounded = true)
|
.wrapContentSize(Alignment.TopStart, unbounded = true)
|
||||||
.offset(x = maxWidth * 0.16f, y = -(wallH - maxHeight) / 2)
|
.offset(x = -(wallW - maxWidth) / 2, y = -(wallH - maxHeight) / 2)
|
||||||
.requiredSize(wallW, wallH)
|
.requiredSize(wallW, wallH)
|
||||||
.graphicsLayer { rotationZ = -13f },
|
.graphicsLayer { rotationZ = -13f },
|
||||||
) {
|
) {
|
||||||
|
|||||||
@@ -64,6 +64,12 @@ internal fun LogoThrobber(modifier: Modifier = Modifier, running: Boolean = true
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** The ball of a throbber laid out in [bounds]: its centre and its radius, at rest. */
|
||||||
|
internal fun throbberBall(bounds: androidx.compose.ui.geometry.Rect): Pair<Offset, Float> {
|
||||||
|
val s = bounds.width / LogoShape.WIDTH
|
||||||
|
return Offset(bounds.left + (LogoShape.CX - LogoShape.LEFT) * s, bounds.top + LogoShape.CY * s) to LogoShape.BALL * s
|
||||||
|
}
|
||||||
|
|
||||||
private const val LOOP_MS = 1900
|
private const val LOOP_MS = 1900
|
||||||
private val Settle = CubicBezierEasing(0.5f, 0f, 0.3f, 1f)
|
private val Settle = CubicBezierEasing(0.5f, 0f, 0.3f, 1f)
|
||||||
private val Turn = CubicBezierEasing(0.65f, 0f, 0.35f, 1f)
|
private val Turn = CubicBezierEasing(0.65f, 0f, 0.35f, 1f)
|
||||||
|
|||||||
@@ -172,9 +172,9 @@ fun WirelessAdbFixPage(
|
|||||||
SettingsPage(
|
SettingsPage(
|
||||||
host = rememberMenuHost(),
|
host = rememberMenuHost(),
|
||||||
title = when {
|
title = when {
|
||||||
compactSplit && step < 2 -> "Wireless ADB"
|
compactSplit && step < 2 -> "Wireless debugging"
|
||||||
step == 2 -> "Wireless ADB ready"
|
step == 2 -> "Child-process limit updated"
|
||||||
else -> "Set up on-device ADB"
|
else -> "Change the child-process limit"
|
||||||
},
|
},
|
||||||
eyebrow = "Setup",
|
eyebrow = "Setup",
|
||||||
lede = when {
|
lede = when {
|
||||||
@@ -201,7 +201,7 @@ fun WirelessAdbFixPage(
|
|||||||
) {
|
) {
|
||||||
SettingsGroup("Child-process limit", compact = compactSplit) {
|
SettingsGroup("Child-process limit", compact = compactSplit) {
|
||||||
Text(
|
Text(
|
||||||
"Android confirmed the limit is ${if (desiredEnabled) "enabled" else "disabled"}.",
|
"Android confirmed the limit is ${if (desiredEnabled) "on" else "off"}.",
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
modifier = Modifier.padding(14.dp),
|
modifier = Modifier.padding(14.dp),
|
||||||
)
|
)
|
||||||
@@ -332,7 +332,7 @@ private fun WirelessStepForm(
|
|||||||
StatusMessage(busy, message, Modifier.weight(1f), isError = messageIsError)
|
StatusMessage(busy, message, Modifier.weight(1f), isError = messageIsError)
|
||||||
SecondaryButton("Pair again", compact = compact, enabled = !busy, onClick = onPairAgain)
|
SecondaryButton("Pair again", compact = compact, enabled = !busy, onClick = onPairAgain)
|
||||||
PrimaryButton(
|
PrimaryButton(
|
||||||
if (desiredEnabled) "Enable limit" else "Disable limit",
|
if (desiredEnabled) "Turn limit on" else "Turn limit off",
|
||||||
compact = compact,
|
compact = compact,
|
||||||
enabled = !busy && parseAdbAddress(connectionAddress) != null,
|
enabled = !busy && parseAdbAddress(connectionAddress) != null,
|
||||||
onClick = onApply,
|
onClick = onApply,
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ class HdrProbe(
|
|||||||
) {
|
) {
|
||||||
/** Why HDR cannot be offered, or null when it can. */
|
/** Why HDR cannot be offered, or null when it can. */
|
||||||
val reason: String? = when {
|
val reason: String? = when {
|
||||||
Build.VERSION.SDK_INT < 29 -> "needs Android 10 or newer (display layers with a colour space)"
|
Build.VERSION.SDK_INT < 29 -> "needs Android 10 or newer (display layers with a color space)"
|
||||||
!hdr10 -> if (formats.isEmpty()) "this display reports no HDR support" else "this display supports $formats, not HDR10"
|
!hdr10 -> if (formats.isEmpty()) "this display reports no HDR support" else "this display supports $formats, not HDR10"
|
||||||
else -> null
|
else -> null
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -26,6 +26,10 @@ public final class WaylandCompositor {
|
|||||||
* listener must marshal to the UI thread itself. */
|
* listener must marshal to the UI thread itself. */
|
||||||
public static void setFirstFrameListener(Runnable r) { firstFrameListener = r; }
|
public static void setFirstFrameListener(Runnable r) { firstFrameListener = r; }
|
||||||
|
|
||||||
|
public static synchronized void clearFirstFrameListener(Runnable r) {
|
||||||
|
if (firstFrameListener == r) firstFrameListener = null;
|
||||||
|
}
|
||||||
|
|
||||||
/** Invoked from native (banner_on_first_frame) on the first present. */
|
/** Invoked from native (banner_on_first_frame) on the first present. */
|
||||||
@SuppressWarnings("unused")
|
@SuppressWarnings("unused")
|
||||||
static void onFirstFramePresented() {
|
static void onFirstFramePresented() {
|
||||||
@@ -52,6 +56,10 @@ public final class WaylandCompositor {
|
|||||||
|
|
||||||
public static void setGameListener(GameListener l) { gameListener = l; }
|
public static void setGameListener(GameListener l) { gameListener = l; }
|
||||||
|
|
||||||
|
public static synchronized void clearGameListener(GameListener l) {
|
||||||
|
if (gameListener == l) gameListener = null;
|
||||||
|
}
|
||||||
|
|
||||||
/** Invoked from native (banner_on_game_surface). */
|
/** Invoked from native (banner_on_game_surface). */
|
||||||
@SuppressWarnings("unused")
|
@SuppressWarnings("unused")
|
||||||
static void onGameSurface(String window, String gpuName) {
|
static void onGameSurface(String window, String gpuName) {
|
||||||
|
|||||||
@@ -6,6 +6,12 @@
|
|||||||
<item>By default, leaving the app pauses Steam; it picks up where it left off when you come back.</item>
|
<item>By default, leaving the app pauses Steam; it picks up where it left off when you come back.</item>
|
||||||
<item>Your controller appears as an Xbox 360 pad. Otherwise, use the on-screen controls.</item>
|
<item>Your controller appears as an Xbox 360 pad. Otherwise, use the on-screen controls.</item>
|
||||||
</string-array>
|
</string-array>
|
||||||
|
<string-array name="loading_hints_desktop">
|
||||||
|
<item>First run sets up the desktop. This may take a few minutes.</item>
|
||||||
|
<item>By default, leaving the app pauses the session; it picks up where it left off when you come back.</item>
|
||||||
|
<item>Touch works as a touchpad: drag to move the pointer, tap to click.</item>
|
||||||
|
<item>Your controller appears as an Xbox 360 pad. Otherwise, use the on-screen controls.</item>
|
||||||
|
</string-array>
|
||||||
<string name="session_channel">Session</string>
|
<string name="session_channel">Session</string>
|
||||||
<string name="session_channel_description">Shows while a Steam or desktop session is open</string>
|
<string name="session_channel_description">Shows while a Steam or desktop session is open</string>
|
||||||
<string name="session_notification">Steam is running</string>
|
<string name="session_notification">Steam is running</string>
|
||||||
|
|||||||
@@ -0,0 +1,46 @@
|
|||||||
|
package com.droiddeck.launcher.core
|
||||||
|
|
||||||
|
import java.io.File
|
||||||
|
import java.nio.file.Files
|
||||||
|
import org.junit.After
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Assert.assertNull
|
||||||
|
import org.junit.Before
|
||||||
|
import org.junit.Test
|
||||||
|
|
||||||
|
class ArchivePathsTest {
|
||||||
|
private lateinit var root: File
|
||||||
|
private lateinit var dest: File
|
||||||
|
|
||||||
|
@Before fun setUp() {
|
||||||
|
root = Files.createTempDirectory("archive-paths").toFile()
|
||||||
|
dest = File(root, "dest").apply { mkdirs() }
|
||||||
|
}
|
||||||
|
|
||||||
|
@After fun tearDown() {
|
||||||
|
root.deleteRecursively()
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun plainEntryLandsInside() {
|
||||||
|
assertEquals(File(dest, "usr/bin/sh").canonicalPath, ArchivePaths.inside(dest, "usr/bin/sh")!!.canonicalPath)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun dotEntryIsTheDestination() {
|
||||||
|
assertEquals(dest.canonicalPath, ArchivePaths.inside(dest, "./")!!.canonicalPath)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun parentTraversalIsRefused() {
|
||||||
|
assertNull(ArchivePaths.inside(dest, "../escape"))
|
||||||
|
assertNull(ArchivePaths.inside(dest, "usr/../../escape"))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun siblingWithSharedPrefixIsRefused() {
|
||||||
|
File(root, "dest-other").mkdirs()
|
||||||
|
assertNull(ArchivePaths.inside(dest, "../dest-other/x"))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun symlinkOutOfTheTreeIsRefused() {
|
||||||
|
Files.createSymbolicLink(File(dest, "link").toPath(), root.toPath())
|
||||||
|
assertNull(ArchivePaths.inside(dest, "link/escape"))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
package com.droiddeck.launcher.core
|
||||||
|
|
||||||
|
import java.io.File
|
||||||
|
import java.nio.file.Files
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Assert.assertFalse
|
||||||
|
import org.junit.Assert.assertNull
|
||||||
|
import org.junit.Assert.assertTrue
|
||||||
|
import org.junit.Test
|
||||||
|
|
||||||
|
class HashesTest {
|
||||||
|
private fun file(text: String): File =
|
||||||
|
Files.createTempFile("hashes", ".bin").toFile().apply { writeText(text); deleteOnExit() }
|
||||||
|
|
||||||
|
@Test fun sha256OfKnownInput() {
|
||||||
|
assertEquals("ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad", Hashes.sha256(file("abc")))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun sha512OfKnownInput() {
|
||||||
|
assertEquals(
|
||||||
|
"ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a" +
|
||||||
|
"2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f",
|
||||||
|
Hashes.sha512(file("abc")),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun githubDigestIsRecognised() {
|
||||||
|
val hex = "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
|
||||||
|
assertTrue(Hashes.isGithubSha256("sha256:$hex"))
|
||||||
|
assertEquals(hex, Hashes.githubSha256("sha256:$hex"))
|
||||||
|
assertEquals(hex.uppercase(), Hashes.githubSha256("SHA256:${hex.uppercase()}"))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun anythingElseIsNotADigest() {
|
||||||
|
assertFalse(Hashes.isGithubSha256(null))
|
||||||
|
assertFalse(Hashes.isGithubSha256(""))
|
||||||
|
assertFalse(Hashes.isGithubSha256("sha256:abc"))
|
||||||
|
assertFalse(Hashes.isGithubSha256("sha512:" + "0".repeat(64)))
|
||||||
|
assertNull(Hashes.githubSha256("md5:0123"))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
package com.droiddeck.launcher.core
|
||||||
|
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Assert.assertFalse
|
||||||
|
import org.junit.Assert.assertTrue
|
||||||
|
import org.junit.Test
|
||||||
|
|
||||||
|
class LogRedactorTest {
|
||||||
|
@Test fun labelledJwtIsRedacted() {
|
||||||
|
val out = LogRedactor.redact("Using JWT 25484942796017334")
|
||||||
|
assertFalse(out.contains("25484942796017334"))
|
||||||
|
assertTrue(out.contains("<redacted:jwt>"))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun secretPairKeepsItsKey() {
|
||||||
|
val out = LogRedactor.redact("GET /x?sessionid=abcdef123456 200")
|
||||||
|
assertFalse(out.contains("abcdef123456"))
|
||||||
|
assertTrue(out.contains("sessionid="))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun plainKeyValueSurvives() {
|
||||||
|
assertEquals("language key=english", LogRedactor.redact("language key=english"))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun steamIdIsMaskedNotDeleted() {
|
||||||
|
assertEquals("user 76561********1234", LogRedactor.redact("user 76561198012341234"))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun webApiKeyIsRedactedButDepotChunkIsKept() {
|
||||||
|
val key = "0123456789abcdef0123456789abcdef"
|
||||||
|
val chunk = "0123456789abcdef0123456789abcdef01234567"
|
||||||
|
assertFalse(LogRedactor.redact("key $key").contains(key))
|
||||||
|
assertTrue(LogRedactor.redact("chunk $chunk").contains(chunk))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun emailIsRedacted() {
|
||||||
|
assertEquals("login <redacted:email> ok", LogRedactor.redact("login someone@example.com ok"))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun clockTimeIsNotAnAddress() {
|
||||||
|
val line = "[2026-09-27 10:03:05] Startup"
|
||||||
|
assertEquals(line, LogRedactor.redact(line))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun redactingTwiceChangesNothing() {
|
||||||
|
val lines = listOf(
|
||||||
|
"Using JWT 25484942796017334",
|
||||||
|
"token=abcdefghijklmnop sessionid=qrstuvwxyz123",
|
||||||
|
"user 76561198012341234 [U:1:52075506]",
|
||||||
|
"external address 2607:f8b0:4005:80a::200e",
|
||||||
|
"OnLoginStateChange someaccount 2 1 0 0",
|
||||||
|
)
|
||||||
|
for (line in lines) {
|
||||||
|
val once = LogRedactor.redact(line)
|
||||||
|
assertEquals(once, LogRedactor.redact(once))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
package com.droiddeck.launcher.core
|
||||||
|
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Test
|
||||||
|
|
||||||
|
class PhantomProcessLimitTest {
|
||||||
|
@Test
|
||||||
|
fun developerOptionsToggleAloneCountsAsOff() {
|
||||||
|
assertEquals(PhantomProcessStatus.DISABLED, PhantomProcessLimit.status(null, "false"))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun globalSettingWinsOverTheProperty() {
|
||||||
|
assertEquals(PhantomProcessStatus.DISABLED, PhantomProcessLimit.status("false", "true"))
|
||||||
|
assertEquals(PhantomProcessStatus.ENABLED, PhantomProcessLimit.status("true", "false"))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun emptyGlobalFallsThroughToTheProperty() {
|
||||||
|
assertEquals(PhantomProcessStatus.ENABLED, PhantomProcessLimit.status("", "true"))
|
||||||
|
assertEquals(PhantomProcessStatus.DISABLED, PhantomProcessLimit.status(" ", "0"))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun neitherSetIsUnset() {
|
||||||
|
assertEquals(PhantomProcessStatus.UNSET, PhantomProcessLimit.status(null, null))
|
||||||
|
assertEquals(PhantomProcessStatus.UNSET, PhantomProcessLimit.status("", ""))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,13 +1,17 @@
|
|||||||
# DroidDeck boot animation
|
# DroidDeck boot animation
|
||||||
|
|
||||||
This source accompanies the single Steam startup movie bundled by the app:
|
This source accompanies the single Steam startup movie bundled by the app:
|
||||||
`app/src/main/assets/steam-startup/droiddeck-startup.webm` (1920×1080, pitch black background, VP9 video
|
`app/src/main/assets/steam-startup/droiddeck-startup.webm` (1280×720 at 30 fps, pitch black background, VP8 video
|
||||||
with Opus audio). `droiddeck-boot.html` is the editable animation; the scripts and WAV below
|
with Opus audio). `droiddeck-boot.html` is the editable animation; the scripts and WAV below
|
||||||
reproduce the selected render. No alternate MP4 or WebM exports are kept in the repository.
|
render the animation at the bundled playback profile. No alternate MP4 or WebM exports are kept in the repository.
|
||||||
|
|
||||||
From the repository root, render the movie with:
|
From the repository root, render the movie with:
|
||||||
|
|
||||||
python3 artwork/boot-animation-source/render.py 1920 1080 60 app/src/main/assets/steam-startup/droiddeck-startup.webm dark
|
python3 artwork/boot-animation-source/render.py 1280 720 30 app/src/main/assets/steam-startup/droiddeck-startup.webm dark
|
||||||
|
|
||||||
|
The bundled profile reduces decoded pixels per second by 78% compared with 1080p/60.
|
||||||
|
VP8 also lowers software decode cost while Steam is starting. Keep the bundled movie at
|
||||||
|
720p/30; higher-resolution exports are intended for sharing.
|
||||||
|
|
||||||
The app stages that file into Steam's `config/uioverrides/movies` folder before each session. If
|
The app stages that file into Steam's `config/uioverrides/movies` folder before each session. If
|
||||||
Steam still has its built-in startup movie selected, DroidDeck sets this movie as the device's
|
Steam still has its built-in startup movie selected, DroidDeck sets this movie as the device's
|
||||||
@@ -27,13 +31,12 @@ it down or step frame by frame (arrow keys).
|
|||||||
|
|
||||||
## Re-render the video
|
## Re-render the video
|
||||||
|
|
||||||
pip install playwright && playwright install chromium # ffmpeg with libvpx-vp9 also required
|
pip install playwright && playwright install chromium # ffmpeg with libvpx also required
|
||||||
python3 render.py 1280 800 60 droiddeck-boot-1280x800.webm
|
python3 render.py 1280 720 30 droiddeck-boot-1280x720.webm
|
||||||
python3 render.py 1920 1080 60 droiddeck-boot-1920x1080.webm
|
|
||||||
python3 render.py 1920 1080 60 droiddeck-boot-1920x1080.mp4 # .mp4 = H.264 for sharing
|
python3 render.py 1920 1080 60 droiddeck-boot-1920x1080.mp4 # .mp4 = H.264 for sharing
|
||||||
python3 render.py 1280 800 60 droiddeck-boot-dark-1280x800.webm dark # dark version
|
python3 render.py 1280 720 30 droiddeck-boot-dark-1280x720.webm dark # dark version
|
||||||
|
|
||||||
Each frame gets real motion blur (180° shutter, adaptive sub-frames). Output is VP9 for .webm or H.264 for .mp4, both BT.709,
|
Each frame gets real motion blur (180° shutter, adaptive sub-frames). Output is VP8 for .webm or H.264 for .mp4, both BT.709,
|
||||||
so the orb stays #1A9FFF after compression.
|
so the orb stays #1A9FFF after compression.
|
||||||
|
|
||||||
## Sound
|
## Sound
|
||||||
|
|||||||
@@ -2,11 +2,11 @@
|
|||||||
"""Render the DroidDeck boot animation to .webm (Steam) or .mp4 (H.264).
|
"""Render the DroidDeck boot animation to .webm (Steam) or .mp4 (H.264).
|
||||||
|
|
||||||
Usage: python3 render.py [WIDTH] [HEIGHT] [FPS] [OUT] [light|dark]
|
Usage: python3 render.py [WIDTH] [HEIGHT] [FPS] [OUT] [light|dark]
|
||||||
python3 render.py 1280 800 60 droiddeck-boot.webm
|
python3 render.py 1280 720 30 droiddeck-boot.webm
|
||||||
python3 render.py 1920 1080 60 droiddeck-boot.mp4
|
python3 render.py 1920 1080 60 droiddeck-boot.mp4
|
||||||
python3 render.py 1280 800 60 droiddeck-boot-dark.webm dark
|
python3 render.py 1280 720 30 droiddeck-boot-dark.webm dark
|
||||||
|
|
||||||
Needs: pip install playwright && playwright install chromium, plus ffmpeg with libvpx-vp9.
|
Needs: pip install playwright && playwright install chromium, plus ffmpeg with libvpx.
|
||||||
The animation is drawn by droiddeck-boot.html (same folder); each frame gets real
|
The animation is drawn by droiddeck-boot.html (same folder); each frame gets real
|
||||||
motion blur (180-degree shutter, up to 48 sub-frames when things move fast).
|
motion blur (180-degree shutter, up to 48 sub-frames when things move fast).
|
||||||
"""
|
"""
|
||||||
@@ -15,8 +15,8 @@ from pathlib import Path
|
|||||||
from playwright.sync_api import sync_playwright
|
from playwright.sync_api import sync_playwright
|
||||||
|
|
||||||
W = int(sys.argv[1]) if len(sys.argv) > 1 else 1280
|
W = int(sys.argv[1]) if len(sys.argv) > 1 else 1280
|
||||||
H = int(sys.argv[2]) if len(sys.argv) > 2 else 800
|
H = int(sys.argv[2]) if len(sys.argv) > 2 else 720
|
||||||
FPS = int(sys.argv[3]) if len(sys.argv) > 3 else 60
|
FPS = int(sys.argv[3]) if len(sys.argv) > 3 else 30
|
||||||
OUT = sys.argv[4] if len(sys.argv) > 4 else f"droiddeck-boot-{W}x{H}.webm"
|
OUT = sys.argv[4] if len(sys.argv) > 4 else f"droiddeck-boot-{W}x{H}.webm"
|
||||||
THEME = sys.argv[5] if len(sys.argv) > 5 else "light" # light | dark
|
THEME = sys.argv[5] if len(sys.argv) > 5 else "light" # light | dark
|
||||||
ONLY = [int(x) for x in os.environ.get("FRAMES", "").split(",") if x] # debug: render some frames only
|
ONLY = [int(x) for x in os.environ.get("FRAMES", "").split(",") if x] # debug: render some frames only
|
||||||
@@ -54,9 +54,9 @@ cmd += ["-vf", "scale=out_color_matrix=bt709:out_range=tv:flags=accurate_rnd+ful
|
|||||||
if OUT.lower().endswith(".mp4"): # H.264 for sharing, previews and anything that won't play webm
|
if OUT.lower().endswith(".mp4"): # H.264 for sharing, previews and anything that won't play webm
|
||||||
cmd += ["-c:v", "libx264", "-preset", "slow", "-crf", "15", "-profile:v", "high", "-tune", "animation",
|
cmd += ["-c:v", "libx264", "-preset", "slow", "-crf", "15", "-profile:v", "high", "-tune", "animation",
|
||||||
"-g", str(FPS * 2), "-movflags", "+faststart"]
|
"-g", str(FPS * 2), "-movflags", "+faststart"]
|
||||||
else: # VP9 webm for Steam's startup movie
|
else: # VP8 keeps software decoding inexpensive during Steam startup
|
||||||
cmd += ["-c:v", "libvpx-vp9", "-b:v", "0", "-crf", "18", "-deadline", "good", "-cpu-used", "2",
|
cmd += ["-c:v", "libvpx", "-b:v", "2M", "-crf", "10", "-deadline", "good", "-cpu-used", "2",
|
||||||
"-row-mt", "1", "-g", str(FPS * 2)]
|
"-g", str(FPS * 2)]
|
||||||
cmd += COLOR + ([] if SOUND.exists() else ["-an"]) + [OUT]
|
cmd += COLOR + ([] if SOUND.exists() else ["-an"]) + [OUT]
|
||||||
subprocess.run(cmd, check=True)
|
subprocess.run(cmd, check=True)
|
||||||
if not os.environ.get("FRAMEDIR"):
|
if not os.environ.get("FRAMEDIR"):
|
||||||
|
|||||||
@@ -0,0 +1,172 @@
|
|||||||
|
# DroidDeck 0.2.0 (beta)
|
||||||
|
|
||||||
|
**Valve's native ARM64 Steam client on your Android handheld.** Windows games run through Valve's ARM64 Proton and FEX, and an optional Linux desktop brings emulators along.
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
**Needs:** Android 9+, Adreno 730 or newer (or 8xx), ~3 GB free for the runtime (+1.1 GB for Desktop & apps).
|
||||||
|
|
||||||
|
This is the first release from the [Droid-Deck](https://github.com/Droid-Deck) org, so it covers everything DroidDeck does, not just what changed since 0.1.7. `legacy#N` links go to pull requests in [The412Banner/DroidDeck](https://github.com/The412Banner/DroidDeck), from before the move.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Highlights
|
||||||
|
|
||||||
|
### Steam, running natively
|
||||||
|
The real Steam client in Big Picture, fetched from Valve on your device. Turn on **Run Steam when DroidDeck starts** and the app icon takes you straight in, as above.
|
||||||
|
|
||||||
|
### A launcher made for handhelds
|
||||||
|
Your Steam library as a capsule wall, and a Games tab with per-game settings.
|
||||||
|
|
||||||
|
<p>
|
||||||
|
<img src="https://raw.githubusercontent.com/Droid-Deck/DroidDeck/main/docs/releases/media/0.2.0/launcher-steam.jpg" width="49%" alt="Steam tab with the capsule wall">
|
||||||
|
<img src="https://raw.githubusercontent.com/Droid-Deck/DroidDeck/main/docs/releases/media/0.2.0/launcher-games.jpg" width="49%" alt="Games tab with a game's launch settings">
|
||||||
|
</p>
|
||||||
|
|
||||||
|
### Your Android home screen
|
||||||
|
Set DroidDeck as the Home app and your Android apps live in the launcher too, and in the session menu, so you can open one without leaving your game.
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
### Made for two screens
|
||||||
|
On a dual-screen handheld, launch an Android app on the second screen while Steam keeps the first, or turn the second screen into a keyboard and trackpad, or a Linux terminal.
|
||||||
|
|
||||||
|
<p>
|
||||||
|
<img src="https://raw.githubusercontent.com/Droid-Deck/DroidDeck/main/docs/releases/media/0.2.0/dual-screen-app.gif" width="32%" alt="Launching Geometry Wars 3 on the second screen from the session menu">
|
||||||
|
<img src="https://raw.githubusercontent.com/Droid-Deck/DroidDeck/main/docs/releases/media/0.2.0/second-screen-trackpad.gif" width="32%" alt="Second screen as a trackpad and keyboard">
|
||||||
|
<img src="https://raw.githubusercontent.com/Droid-Deck/DroidDeck/main/docs/releases/media/0.2.0/second-screen-terminal.jpg" width="32%" alt="Second screen as a Linux terminal under Big Picture">
|
||||||
|
</p>
|
||||||
|
|
||||||
|
### A session menu over any game
|
||||||
|
Press Back mid-game for display, controls, components and session settings, paged with LB/RB.
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
### Swap FEX, DXVK and VKD3D-Proton per Proton build
|
||||||
|
Download from the nightlies or import a `.wcp`, and see what the running game is using.
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
### A Linux desktop, with emulators one tap away
|
||||||
|
LXQt on the GPU, plus RPCS3, ARMSX2, Dolphin, DuckStation, melonDS, Cemu, PPSSPP and RetroArch.
|
||||||
|
|
||||||
|
<p>
|
||||||
|
<img src="https://raw.githubusercontent.com/Droid-Deck/DroidDeck/main/docs/releases/media/0.2.0/linux-desktop.jpg" width="49%" alt="LXQt desktop with a file manager and terminal">
|
||||||
|
<img src="https://raw.githubusercontent.com/Droid-Deck/DroidDeck/main/docs/releases/media/0.2.0/desktop-apps.jpg" width="49%" alt="Desktop tab with emulators to install">
|
||||||
|
</p>
|
||||||
|
|
||||||
|
### On-screen controls you can lay out yourself
|
||||||
|
Drag every button where your thumbs want it, with adaptive sticks and phone-sized layouts.
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Everything in 0.2.0
|
||||||
|
|
||||||
|
### Steam
|
||||||
|
|
||||||
|
- Native ARM64 Steam client under gamescope, on DroidDeck's own Vulkan compositor (@The412Banner)
|
||||||
|
- Valve's ARM64 Proton and FEX, ready at first sign-in (@The412Banner, [legacy#22](https://github.com/The412Banner/DroidDeck/pull/22), #33)
|
||||||
|
- Start offline after one sign-in (@The412Banner)
|
||||||
|
- Steam Deck mode: battery and NIS in Quick Access, MangoHud overlay (@The412Banner, [legacy#9](https://github.com/The412Banner/DroidDeck/pull/9), [legacy#16](https://github.com/The412Banner/DroidDeck/pull/16))
|
||||||
|
- Games from your own folders appear in Steam, with store art (@The412Banner, [legacy#9](https://github.com/The412Banner/DroidDeck/pull/9))
|
||||||
|
- Components manager for FEX, DXVK and VKD3D-Proton, applied on every launch (@The412Banner, #29)
|
||||||
|
- GE-Proton and proton-cachyos as extra compatibility tools (@The412Banner, @xXJSONDeruloXx, [legacy#18](https://github.com/The412Banner/DroidDeck/pull/18))
|
||||||
|
- FEX presets per session, Stability to Extreme + TSO (@The412Banner)
|
||||||
|
- Decky Loader, with plugins in Big Picture (@xXJSONDeruloXx, #16)
|
||||||
|
- Steam's Internet settings and connection indicator work (@maxjivi05)
|
||||||
|
- Steam sees the device as "DroidDeck" (@xXJSONDeruloXx, #15)
|
||||||
|
- Steam launchers on the Linux desktop (@The412Banner, #10)
|
||||||
|
- DroidDeck startup movie, and optionally straight into Steam when the app opens (@xXJSONDeruloXx, #25, #27, #36, #38)
|
||||||
|
|
||||||
|
### Launcher
|
||||||
|
|
||||||
|
- Side rail, Games tab, capsule wall, graphite theme, controller hints, phone layouts (@xXJSONDeruloXx, #13, #35, #41)
|
||||||
|
- Launch buttons flood into the loading screen (@xXJSONDeruloXx, #46)
|
||||||
|
- Game files and Proton prefix shortcuts on each game's page (@xXJSONDeruloXx, #39)
|
||||||
|
- Controller navigation everywhere, remembered across the rail (@The412Banner, [legacy#29](https://github.com/The412Banner/DroidDeck/pull/29), [legacy#34](https://github.com/The412Banner/DroidDeck/pull/34), [legacy#38](https://github.com/The412Banner/DroidDeck/pull/38))
|
||||||
|
- Built-in file manager, a ROMs folder anywhere (SD cards too), app files in Android's picker (@The412Banner, [legacy#41](https://github.com/The412Banner/DroidDeck/pull/41))
|
||||||
|
- Themes and the split-D logo (@The412Banner, @xXJSONDeruloXx, [legacy#4](https://github.com/The412Banner/DroidDeck/pull/4), [legacy#37](https://github.com/The412Banner/DroidDeck/pull/37), #34)
|
||||||
|
- Use DroidDeck as your Android home app, with Android apps in the front end (@xXJSONDeruloXx, @The412Banner, [legacy#17](https://github.com/The412Banner/DroidDeck/pull/17), [legacy#44](https://github.com/The412Banner/DroidDeck/pull/44))
|
||||||
|
- Build identity and latest-build link in the top bar (@xXJSONDeruloXx, [legacy#24](https://github.com/The412Banner/DroidDeck/pull/24), #26)
|
||||||
|
|
||||||
|
### Sessions
|
||||||
|
|
||||||
|
- Sessions keep running when you leave the app (@The412Banner)
|
||||||
|
- Pause policy (Auto, Manual, Never), changeable mid-session, audio recovers after a pause (@xXJSONDeruloXx, [legacy#7](https://github.com/The412Banner/DroidDeck/pull/7), #14)
|
||||||
|
- Paged session menu with Display, Controls and Settings tabs (@xXJSONDeruloXx, @The412Banner, [legacy#40](https://github.com/The412Banner/DroidDeck/pull/40), #6, #24)
|
||||||
|
- Back opens the menu; a double press opens Steam's Quick Access (@xXJSONDeruloXx, [legacy#3](https://github.com/The412Banner/DroidDeck/pull/3), [legacy#20](https://github.com/The412Banner/DroidDeck/pull/20))
|
||||||
|
- First run sets itself up from the loading screen (@The412Banner, [legacy#12](https://github.com/The412Banner/DroidDeck/pull/12), [legacy#15](https://github.com/The412Banner/DroidDeck/pull/15))
|
||||||
|
- Launch on any connected display; a second screen can be a keyboard, trackpad or terminal (@xXJSONDeruloXx, [legacy#13](https://github.com/The412Banner/DroidDeck/pull/13), [legacy#33](https://github.com/The412Banner/DroidDeck/pull/33))
|
||||||
|
- Share session logs from the app or the ended-session screen (@xXJSONDeruloXx, @The412Banner, [legacy#11](https://github.com/The412Banner/DroidDeck/pull/11), #17, #41)
|
||||||
|
|
||||||
|
### Controls
|
||||||
|
|
||||||
|
- Any controller shows up as an Xbox 360 pad; an on-screen pad fills in when none is connected (@The412Banner)
|
||||||
|
- On-screen controller editor with adaptive sticks (@maxjivi05, #9)
|
||||||
|
- On-screen sticks that use the letterbox bars, plus Steam and QAM touch buttons (@The412Banner, @xXJSONDeruloXx, [legacy#6](https://github.com/The412Banner/DroidDeck/pull/6))
|
||||||
|
- Real touch in Big Picture; a desktop touchpad that hovers, clicks, scrolls and two-finger drags (@The412Banner, #10, #22)
|
||||||
|
- Cursor shapes, hidden while you play on a pad (@The412Banner, #18)
|
||||||
|
- Soft keyboard and a full PC keyboard (@The412Banner, [legacy#25](https://github.com/The412Banner/DroidDeck/pull/25))
|
||||||
|
|
||||||
|
### Display and performance
|
||||||
|
|
||||||
|
- Frame generation: built-in Win-FG, or LSFG from your own Lossless Scaling, 2×–4× (@The412Banner)
|
||||||
|
- Import or download Turnip drivers per mode, from Banners-Turnip and WinNative (@The412Banner)
|
||||||
|
- Resolution and shape per mode, including "Exactly this panel" for 4:3 and 3:2 screens (@The412Banner, [legacy#14](https://github.com/The412Banner/DroidDeck/pull/14))
|
||||||
|
- Stretch games to fill; Quake-engine games windowed to fit (@The412Banner, [legacy#32](https://github.com/The412Banner/DroidDeck/pull/32))
|
||||||
|
- HDR10 on supported panels (experimental) (@The412Banner)
|
||||||
|
- Runs as a game on Android: sustained performance, fastest panel mode, ADPF hints (@The412Banner)
|
||||||
|
- Steam's interface stays on the GPU (@maxjivi05)
|
||||||
|
- Pin Steam and games to chosen CPU cores (@The412Banner)
|
||||||
|
- Faster proot with WinNative's seccomp and tracing fixes (@maxjivi05, #4, #37)
|
||||||
|
|
||||||
|
### Desktop and emulators
|
||||||
|
|
||||||
|
- LXQt on labwc, on the GPU with Vulkan by default (@The412Banner, [legacy#25](https://github.com/The412Banner/DroidDeck/pull/25))
|
||||||
|
- Emulators downloaded on request: RetroArch, PPSSPP, RPCS3, DuckStation, ARMSX2, Dolphin, melonDS, Cemu and more (@The412Banner)
|
||||||
|
- Emulator games launch full screen from the front end, one tile per disc, with box art (@The412Banner, [legacy#29](https://github.com/The412Banner/DroidDeck/pull/29), [legacy#34](https://github.com/The412Banner/DroidDeck/pull/34), [legacy#38](https://github.com/The412Banner/DroidDeck/pull/38))
|
||||||
|
- ARMSX2 replaces PCSX2 for PS2: 60 fps where PCSX2 managed 17 (@The412Banner, [legacy#26](https://github.com/The412Banner/DroidDeck/pull/26))
|
||||||
|
- Dolphin, melonDS and Cemu set up out of the box (@The412Banner, #10, #18, #42)
|
||||||
|
- Emulator controllers preconfigured, and RPCS3 shader fixes (@The412Banner, [legacy#25](https://github.com/The412Banner/DroidDeck/pull/25))
|
||||||
|
|
||||||
|
### Audio
|
||||||
|
|
||||||
|
- DirectAudio for games, straight to Android (@The412Banner, [legacy#9](https://github.com/The412Banner/DroidDeck/pull/9), [legacy#11](https://github.com/The412Banner/DroidDeck/pull/11))
|
||||||
|
- Microphone for voice chat, on by default (@The412Banner, [legacy#11](https://github.com/The412Banner/DroidDeck/pull/11))
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- Steam updates failing on read-only files (@The412Banner, #33)
|
||||||
|
- A dropped finger-up blocking later touches (@The412Banner, #22)
|
||||||
|
- Stopped sessions leaving stray processes and log spam (@The412Banner, #43)
|
||||||
|
- Cemu and shadPS4 crashing on the input shim; no cursor on the GPU desktop (@The412Banner, #42)
|
||||||
|
- Leftovers from crashed or killed sessions cleaned up at the next start (@The412Banner, [legacy#16](https://github.com/The412Banner/DroidDeck/pull/16))
|
||||||
|
- The menu's dim layer staying over Steam after switching apps (@xXJSONDeruloXx, #45)
|
||||||
|
- Steam library capsule art (@xXJSONDeruloXx, #12)
|
||||||
|
- The menu's Desktop button wrapping (@xXJSONDeruloXx, #28)
|
||||||
|
- Launcher restarting when a controller connects (@xXJSONDeruloXx, #40)
|
||||||
|
- Runtime installs racing, or stopping when you leave the app (@xXJSONDeruloXx, #40)
|
||||||
|
- Steam blocked by Android's child-process limit; Setup lifts it over wireless ADB (@xXJSONDeruloXx, #21)
|
||||||
|
|
||||||
|
### Security
|
||||||
|
|
||||||
|
- SHA-256 checked on every catalog, release and Proton download (@xXJSONDeruloXx, #40)
|
||||||
|
- Runtime archives can't link outside the rootfs (@xXJSONDeruloXx, #40)
|
||||||
|
- Logs scrub account and persona names, public IPs and device IDs (@The412Banner, #19)
|
||||||
|
- Signed with DroidDeck's own release key (@The412Banner, [legacy#41](https://github.com/The412Banner/DroidDeck/pull/41))
|
||||||
|
|
||||||
|
### Behind the scenes
|
||||||
|
|
||||||
|
- Every PR's APK published to DroidDeck-CI (@maxjivi05, #3), with signed builds gated on review (@xXJSONDeruloXx, #5)
|
||||||
|
- Local builds matching CI, and a debug-only ADB agent bridge (@xXJSONDeruloXx, [legacy#5](https://github.com/The412Banner/DroidDeck/pull/5), [legacy#35](https://github.com/The412Banner/DroidDeck/pull/35), #7, #20)
|
||||||
|
- CI hardening, branch protection and copy clean-ups (@The412Banner, @xXJSONDeruloXx, [legacy#8](https://github.com/The412Banner/DroidDeck/pull/8), [legacy#10](https://github.com/The412Banner/DroidDeck/pull/10), [legacy#41](https://github.com/The412Banner/DroidDeck/pull/41), #8)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
**Built on** WinNative by @maxjivi05 (the gamescope runtime, proot session and input interposer), Winlator by brunodev85 (audio and gamepad model), Bannerlator by @The412Banner (file manager, first sign-in flow), lsfg-vk by PancakeTAS, MangoHud by flightlessmango, and Vauzi's Adreno 710/720/722 device entries.
|
||||||
|
|
||||||
|
Not affiliated with Valve. Steam, Proton and Steam Deck are Valve's; the client and Proton are fetched from Valve's servers on your device.
|
||||||
|
|
||||||
|
**Contributors:** @The412Banner, @xXJSONDeruloXx, @maxjivi05
|
||||||
|
After Width: | Height: | Size: 97 KiB |
|
After Width: | Height: | Size: 57 KiB |
|
After Width: | Height: | Size: 94 KiB |
|
After Width: | Height: | Size: 101 KiB |
|
After Width: | Height: | Size: 4.1 MiB |
|
After Width: | Height: | Size: 5.0 MiB |
|
After Width: | Height: | Size: 131 KiB |
|
After Width: | Height: | Size: 153 KiB |
|
After Width: | Height: | Size: 63 KiB |
|
After Width: | Height: | Size: 122 KiB |
|
After Width: | Height: | Size: 1.4 MiB |
|
After Width: | Height: | Size: 481 KiB |
@@ -41,7 +41,8 @@ fi
|
|||||||
|
|
||||||
ndk_version=${DROIDDECK_NDK_VERSION:-}
|
ndk_version=${DROIDDECK_NDK_VERSION:-}
|
||||||
if [[ -z "${ndk_version}" ]]; then
|
if [[ -z "${ndk_version}" ]]; then
|
||||||
ndk_path=$(find "${sdk_dir}/ndk" -mindepth 1 -maxdepth 1 -type d -print | sort -V | tail -1)
|
# Only complete NDKs: an interrupted sdkmanager install leaves a directory without source.properties.
|
||||||
|
ndk_path=$(find "${sdk_dir}/ndk" -mindepth 2 -maxdepth 2 -name source.properties -print | xargs -n1 dirname | sort -V | tail -1)
|
||||||
ndk_version=${ndk_path##*/}
|
ndk_version=${ndk_path##*/}
|
||||||
fi
|
fi
|
||||||
if [[ -z "${ndk_version}" || ! -d "${sdk_dir}/ndk/${ndk_version}" ]]; then
|
if [[ -z "${ndk_version}" || ! -d "${sdk_dir}/ndk/${ndk_version}" ]]; then
|
||||||
@@ -100,7 +101,7 @@ docker run --rm --platform linux/amd64 \
|
|||||||
d=app/src/main/assets/linuxfs
|
d=app/src/main/assets/linuxfs
|
||||||
mkdir -p "$d"
|
mkdir -p "$d"
|
||||||
aarch64-linux-gnu-g++ -shared -fPIC -O2 -Wall -Wno-attributes -Wno-nonnull-compare \
|
aarch64-linux-gnu-g++ -shared -fPIC -O2 -Wall -Wno-attributes -Wno-nonnull-compare \
|
||||||
-pthread -std=c++17 -static-libstdc++ -static-libgcc \
|
-pthread -std=c++17 -static-libstdc++ -static-libgcc -Wl,--exclude-libs,ALL \
|
||||||
-o "$d/libfakeinput.so" app/src/main/cpp/fakeinput_steam.cpp -ldl
|
-o "$d/libfakeinput.so" app/src/main/cpp/fakeinput_steam.cpp -ldl
|
||||||
aarch64-linux-gnu-strip --strip-unneeded "$d/libfakeinput.so"
|
aarch64-linux-gnu-strip --strip-unneeded "$d/libfakeinput.so"
|
||||||
aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -pthread \
|
aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -pthread \
|
||||||
|
|||||||
@@ -717,8 +717,36 @@ CEMU_XML = """<?xml version="1.0" encoding="UTF-8"?>
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
# Cemu's settings, so its Getting Started dialog (shown while settings.xml is missing, and whose
|
||||||
|
# folder picker cannot reach ROMs) never blocks a launch: the Wii U games folder, Vulkan
|
||||||
|
# (Graphic api 1), and audio through Cubeb (the only backend on Linux; api 3) on the default
|
||||||
|
# device for both the TV and the GamePad speaker - some titles play everything through the
|
||||||
|
# GamePad - at full volume (Cemu's own default is 20 %). Keys from config/CemuConfig.cpp.
|
||||||
|
CEMU_SETTINGS = """<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<content>
|
||||||
|
<mlc_path></mlc_path>
|
||||||
|
<GamePaths>
|
||||||
|
<Entry>{games}</Entry>
|
||||||
|
</GamePaths>
|
||||||
|
<Graphic>
|
||||||
|
<api>1</api>
|
||||||
|
</Graphic>
|
||||||
|
<Audio>
|
||||||
|
<api>3</api>
|
||||||
|
<TVVolume>100</TVVolume>
|
||||||
|
<PadVolume>100</PadVolume>
|
||||||
|
<TVDevice>default</TVDevice>
|
||||||
|
<PadDevice>default</PadDevice>
|
||||||
|
</Audio>
|
||||||
|
</content>
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
def cemu():
|
def cemu():
|
||||||
seed(os.path.join(CONFIG, "Cemu/controllerProfiles/controller0.xml"), CEMU_XML, "Cemu")
|
seed(os.path.join(CONFIG, "Cemu/controllerProfiles/controller0.xml"), CEMU_XML, "Cemu")
|
||||||
|
games = system_folder(["wiiu", "wii u"], "wiiu")
|
||||||
|
seed(os.path.join(CONFIG, "Cemu/settings.xml"), CEMU_SETTINGS.format(games=games), "Cemu",
|
||||||
|
done=f"games in {games}, Vulkan, Cubeb audio on the default device")
|
||||||
|
|
||||||
|
|
||||||
# melonDS 1.x: raw SDL joystick indices. The session's pad has the kernel's Xbox 360 layout
|
# melonDS 1.x: raw SDL joystick indices. The session's pad has the kernel's Xbox 360 layout
|
||||||
|
|||||||
@@ -19,7 +19,10 @@ if [ -n "${BL_LOG:-}" ] && [ -z "${BL_INSIDE:-}" ]; then
|
|||||||
if [ "$(stat -c %s "$BL_LOG" 2>/dev/null || echo 0)" -gt 8388608 ]; then
|
if [ "$(stat -c %s "$BL_LOG" 2>/dev/null || echo 0)" -gt 8388608 ]; then
|
||||||
mv -f "$BL_LOG" "$BL_LOG.1"
|
mv -f "$BL_LOG" "$BL_LOG.1"
|
||||||
fi
|
fi
|
||||||
exec >>"$BL_LOG" 2>&1
|
# A guest looping on an error writes gigabytes in minutes (an Xwayland proot had lost track of
|
||||||
|
# managed 9 GB of one line in 19 min): the log keeps its first BL_LOG_CAP bytes and the rest is
|
||||||
|
# drained, not refused - a writer that filled it must not die of SIGPIPE.
|
||||||
|
exec > >({ head -c "${BL_LOG_CAP:-268435456}" >>"$BL_LOG"; cat >/dev/null; }) 2>&1
|
||||||
echo "== bannerlator-session $(date) mode=$mode $*"
|
echo "== bannerlator-session $(date) mode=$mode $*"
|
||||||
echo "== uid=$(id -u) size=${BL_WIDTH:-?}x${BL_HEIGHT:-?} fps=${BL_FPS:-0} icd=${VK_ICD_FILENAMES:-none}"
|
echo "== uid=$(id -u) size=${BL_WIDTH:-?}x${BL_HEIGHT:-?} fps=${BL_FPS:-0} icd=${VK_ICD_FILENAMES:-none}"
|
||||||
echo "== gamescope: $(gamescope --version 2>&1 | head -1) at $(command -v gamescope)"
|
echo "== gamescope: $(gamescope --version 2>&1 | head -1) at $(command -v gamescope)"
|
||||||
@@ -588,6 +591,8 @@ BUSCONF
|
|||||||
wait "$decky_supervisor" 2>/dev/null || true
|
wait "$decky_supervisor" 2>/dev/null || true
|
||||||
echo "== Decky: session supervisor stopped"
|
echo "== Decky: session supervisor stopped"
|
||||||
fi
|
fi
|
||||||
|
_bl_jobs=$(jobs -p)
|
||||||
|
[ -n "$_bl_jobs" ] && kill $_bl_jobs 2>/dev/null
|
||||||
reap_orphans
|
reap_orphans
|
||||||
fi
|
fi
|
||||||
exit "$rc"
|
exit "$rc"
|
||||||
|
|||||||
@@ -19,3 +19,28 @@ Ported from WinNative (`feature/proot-enhancements`, e7af0f24):
|
|||||||
workaround is active.
|
workaround is active.
|
||||||
- `0003-clone3-flags-read-guard.patch` - a thread created with `clone3` keeps the flags it
|
- `0003-clone3-flags-read-guard.patch` - a thread created with `clone3` keeps the flags it
|
||||||
inherited when `struct clone_args` cannot be read, instead of being tracked as a fork.
|
inherited when `struct clone_args` cannot be read, instead of being tracked as a fork.
|
||||||
|
|
||||||
|
Ported from WinNative (`main`, 53836ca9, "Fix/performance and vac"):
|
||||||
|
|
||||||
|
- `0004-seccomp-filter-by-argument.patch` - the seccomp filter traces `prctl` only for
|
||||||
|
`PR_SET_DUMPABLE`, `setrlimit` only for `RLIMIT_STACK` and `prlimit64` only when it sets a new
|
||||||
|
`RLIMIT_STACK`, the only cases proot acts on; every other call runs without a stop. `uname` is
|
||||||
|
traced by the core only on x86_64, the one arch it rewrites; kompat still adds it for
|
||||||
|
`--kernel-release`.
|
||||||
|
- `0005-seccomp-skip-unneeded-sysexit.patch` - a seccomp stop fetches the registers once and
|
||||||
|
looks the filter flags up by syscall number, instead of a `PTRACE_GETEVENTMSG` and a second
|
||||||
|
register fetch. The flags table is built from proot's list merged with the enabled extensions'
|
||||||
|
(kompat and fake_id0 here), so it is exactly what the filter reports. `wait4`/`waitpid` left to
|
||||||
|
the kernel and `accept`/`accept4` without a sockaddr skip their exit stop, unless an extension
|
||||||
|
replaced the syscall (kompat turning `accept4` into `accept`).
|
||||||
|
- `0006-clone3-exit-signal.patch` - `clone3` flags and exit signal are read as the 64-bit fields
|
||||||
|
of `struct clone_args`, so a `clone3` fork is told apart from a thread when proot decides how the
|
||||||
|
child is traced.
|
||||||
|
- `0007-proc-self-thread-group.patch` - tracees track their thread group, `/proc/self` names it
|
||||||
|
instead of the calling thread, and `/proc/thread-self` resolves to `/proc/<tgid>/task/<tid>`.
|
||||||
|
- `0008-fchmodat2-openat2.patch` - `fchmodat2` paths are translated (honouring
|
||||||
|
`AT_SYMLINK_NOFOLLOW`), `openat2` answers `ENOSYS` so callers fall back to the translated
|
||||||
|
`openat`, and syscall numbers past the end of a table are rejected instead of read.
|
||||||
|
- `0009-tracee-relatives-sweep.patch` - tracees count their children, so a terminating thread
|
||||||
|
with no children or ptracees no longer walks every tracee; the per-stop memory collector is
|
||||||
|
emptied instead of freed and reallocated.
|
||||||
@@ -0,0 +1,209 @@
|
|||||||
|
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
|
||||||
|
From: maxjivi05 <maxjividen@gmail.com>
|
||||||
|
Date: Sun, 27 Sep 2026 07:56:54 -0400
|
||||||
|
Subject: [PATCH] seccomp: trace prctl, setrlimit and prlimit64 only for the
|
||||||
|
arguments PRoot acts on
|
||||||
|
|
||||||
|
---
|
||||||
|
src/syscall/seccomp.c | 106 +++++++++++++++++++++++++++++++++++-------
|
||||||
|
1 file changed, 89 insertions(+), 17 deletions(-)
|
||||||
|
|
||||||
|
diff --git a/src/syscall/seccomp.c b/src/syscall/seccomp.c
|
||||||
|
index 6d1ba47..8557d4a 100644
|
||||||
|
--- a/src/syscall/seccomp.c
|
||||||
|
+++ b/src/syscall/seccomp.c
|
||||||
|
@@ -37,6 +37,7 @@
|
||||||
|
#include <string.h> /* memcpy(3), */
|
||||||
|
#include <stddef.h> /* offsetof(3), */
|
||||||
|
#include <stdint.h> /* uint*_t, UINT*_MAX, */
|
||||||
|
+#include <sys/resource.h>
|
||||||
|
#include <assert.h> /* assert(3), */
|
||||||
|
|
||||||
|
#include "syscall/seccomp.h"
|
||||||
|
@@ -121,13 +122,86 @@ static int add_trace_syscall(struct sock_fprog *program, word_t syscall, int fla
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
+static int add_trace_syscall_if_arg(struct sock_fprog *program, word_t syscall,
|
||||||
|
+ size_t arg, uint32_t value, int flag)
|
||||||
|
+{
|
||||||
|
+ const size_t arg_offset = offsetof(struct seccomp_data, args[arg]);
|
||||||
|
+
|
||||||
|
+ #define LENGTH_TRACE_SYSCALL_IF_ARG 5
|
||||||
|
+ struct sock_filter statements[LENGTH_TRACE_SYSCALL_IF_ARG] = {
|
||||||
|
+ BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, syscall, 0, 4),
|
||||||
|
+ BPF_STMT(BPF_LD + BPF_W + BPF_ABS, arg_offset),
|
||||||
|
+ BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, value, 0, 1),
|
||||||
|
+ BPF_STMT(BPF_RET + BPF_K, SECCOMP_RET_TRACE + flag),
|
||||||
|
+ BPF_STMT(BPF_RET + BPF_K, SECCOMP_RET_ALLOW)
|
||||||
|
+ };
|
||||||
|
+
|
||||||
|
+ DEBUG_FILTER("FILTER: trace if syscall == %ld and arg %zd == %u\n",
|
||||||
|
+ syscall, arg, value);
|
||||||
|
+
|
||||||
|
+ return add_statements(program, LENGTH_TRACE_SYSCALL_IF_ARG, statements);
|
||||||
|
+}
|
||||||
|
+
|
||||||
|
+static int add_trace_prlimit_stack(struct sock_fprog *program, word_t syscall, int flag)
|
||||||
|
+{
|
||||||
|
+ const size_t resource_offset = offsetof(struct seccomp_data, args[1]);
|
||||||
|
+ const size_t limit_offset = offsetof(struct seccomp_data, args[2]);
|
||||||
|
+
|
||||||
|
+ #define LENGTH_TRACE_PRLIMIT_STACK 9
|
||||||
|
+ struct sock_filter statements[LENGTH_TRACE_PRLIMIT_STACK] = {
|
||||||
|
+ BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, syscall, 0, 8),
|
||||||
|
+ BPF_STMT(BPF_LD + BPF_W + BPF_ABS, resource_offset),
|
||||||
|
+ BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, RLIMIT_STACK, 0, 5),
|
||||||
|
+ BPF_STMT(BPF_LD + BPF_W + BPF_ABS, limit_offset),
|
||||||
|
+ BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, 0, 0, 2),
|
||||||
|
+ BPF_STMT(BPF_LD + BPF_W + BPF_ABS, limit_offset + sizeof(uint32_t)),
|
||||||
|
+ BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, 0, 1, 0),
|
||||||
|
+ BPF_STMT(BPF_RET + BPF_K, SECCOMP_RET_TRACE + flag),
|
||||||
|
+ BPF_STMT(BPF_RET + BPF_K, SECCOMP_RET_ALLOW)
|
||||||
|
+ };
|
||||||
|
+
|
||||||
|
+ DEBUG_FILTER("FILTER: trace if syscall == %ld sets RLIMIT_STACK\n", syscall);
|
||||||
|
+
|
||||||
|
+ return add_statements(program, LENGTH_TRACE_PRLIMIT_STACK, statements);
|
||||||
|
+}
|
||||||
|
+
|
||||||
|
+static size_t trace_length(Sysnum sysnum)
|
||||||
|
+{
|
||||||
|
+ switch (sysnum) {
|
||||||
|
+ case PR_prctl:
|
||||||
|
+ case PR_setrlimit:
|
||||||
|
+ return LENGTH_TRACE_SYSCALL_IF_ARG;
|
||||||
|
+ case PR_prlimit64:
|
||||||
|
+ return LENGTH_TRACE_PRLIMIT_STACK;
|
||||||
|
+ default:
|
||||||
|
+ return LENGTH_TRACE_SYSCALL;
|
||||||
|
+ }
|
||||||
|
+}
|
||||||
|
+
|
||||||
|
+static int add_trace(struct sock_fprog *program, Sysnum sysnum, word_t syscall, int flag)
|
||||||
|
+{
|
||||||
|
+ if (syscall > UINT32_MAX)
|
||||||
|
+ return -ERANGE;
|
||||||
|
+
|
||||||
|
+ switch (sysnum) {
|
||||||
|
+ case PR_prctl:
|
||||||
|
+ return add_trace_syscall_if_arg(program, syscall, 0, PR_SET_DUMPABLE, flag);
|
||||||
|
+ case PR_setrlimit:
|
||||||
|
+ return add_trace_syscall_if_arg(program, syscall, 0, RLIMIT_STACK, flag);
|
||||||
|
+ case PR_prlimit64:
|
||||||
|
+ return add_trace_prlimit_stack(program, syscall, flag);
|
||||||
|
+ default:
|
||||||
|
+ return add_trace_syscall(program, syscall, flag);
|
||||||
|
+ }
|
||||||
|
+}
|
||||||
|
+
|
||||||
|
/**
|
||||||
|
* Append to @program->filter the statements that allow anything (if
|
||||||
|
- * unfiltered). Note that @nb_traced_syscalls is used to make a
|
||||||
|
- * sanity check. This function returns -errno if an error occurred,
|
||||||
|
+ * unfiltered). Note that @section_length is used to make a sanity
|
||||||
|
+ * check. This function returns -errno if an error occurred,
|
||||||
|
* otherwise 0.
|
||||||
|
*/
|
||||||
|
-static int end_arch_section(struct sock_fprog *program, size_t nb_traced_syscalls)
|
||||||
|
+static int end_arch_section(struct sock_fprog *program, size_t section_length)
|
||||||
|
{
|
||||||
|
int status;
|
||||||
|
|
||||||
|
@@ -143,8 +217,7 @@ static int end_arch_section(struct sock_fprog *program, size_t nb_traced_syscall
|
||||||
|
return status;
|
||||||
|
|
||||||
|
/* Sanity check, see start_arch_section(). */
|
||||||
|
- if ( talloc_array_length(program->filter) - program->len
|
||||||
|
- != LENGTH_END_SECTION + nb_traced_syscalls * LENGTH_TRACE_SYSCALL)
|
||||||
|
+ if (talloc_array_length(program->filter) - program->len != section_length)
|
||||||
|
return -ERANGE;
|
||||||
|
|
||||||
|
return 0;
|
||||||
|
@@ -152,16 +225,14 @@ static int end_arch_section(struct sock_fprog *program, size_t nb_traced_syscall
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Append to @program->filter the statements that check the current
|
||||||
|
- * @architecture. Note that @nb_traced_syscalls is used to make a
|
||||||
|
+ * @architecture. Note that @section_length is used to make a
|
||||||
|
* sanity check. This function returns -errno if an error occurred,
|
||||||
|
* otherwise 0.
|
||||||
|
*/
|
||||||
|
-static int start_arch_section(struct sock_fprog *program, uint32_t arch, size_t nb_traced_syscalls)
|
||||||
|
+static int start_arch_section(struct sock_fprog *program, uint32_t arch, size_t section_length)
|
||||||
|
{
|
||||||
|
const size_t arch_offset = offsetof(struct seccomp_data, arch);
|
||||||
|
const size_t syscall_offset = offsetof(struct seccomp_data, nr);
|
||||||
|
- const size_t section_length = LENGTH_END_SECTION +
|
||||||
|
- nb_traced_syscalls * LENGTH_TRACE_SYSCALL;
|
||||||
|
int status;
|
||||||
|
|
||||||
|
/* Sanity checks. */
|
||||||
|
@@ -191,7 +262,7 @@ static int start_arch_section(struct sock_fprog *program, uint32_t arch, size_t
|
||||||
|
};
|
||||||
|
|
||||||
|
DEBUG_FILTER("FILTER: if arch == %ld, up to %zdth statement\n",
|
||||||
|
- arch, nb_traced_syscalls);
|
||||||
|
+ arch, section_length);
|
||||||
|
|
||||||
|
status = add_statements(program, LENGTH_START_SECTION, statements);
|
||||||
|
if (status < 0)
|
||||||
|
@@ -256,7 +327,7 @@ static int set_seccomp_filters(const FilteredSysnum *sysnums)
|
||||||
|
size_t nb_archs = sizeof(seccomp_archs) / sizeof(SeccompArch);
|
||||||
|
|
||||||
|
struct sock_fprog program = { .len = 0, .filter = NULL };
|
||||||
|
- size_t nb_traced_syscalls;
|
||||||
|
+ size_t section_length;
|
||||||
|
size_t i, j, k;
|
||||||
|
int status;
|
||||||
|
|
||||||
|
@@ -268,19 +339,18 @@ static int set_seccomp_filters(const FilteredSysnum *sysnums)
|
||||||
|
for (i = 0; i < nb_archs; i++) {
|
||||||
|
word_t syscall;
|
||||||
|
|
||||||
|
- nb_traced_syscalls = 0;
|
||||||
|
+ section_length = LENGTH_END_SECTION;
|
||||||
|
|
||||||
|
- /* Pre-compute the number of traced syscalls for this architecture. */
|
||||||
|
for (j = 0; j < seccomp_archs[i].nb_abis; j++) {
|
||||||
|
for (k = 0; sysnums[k].value != PR_void; k++) {
|
||||||
|
syscall = detranslate_sysnum(seccomp_archs[i].abis[j], sysnums[k].value);
|
||||||
|
if (syscall != SYSCALL_AVOIDER)
|
||||||
|
- nb_traced_syscalls++;
|
||||||
|
+ section_length += trace_length(sysnums[k].value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Filter: if handled architecture */
|
||||||
|
- status = start_arch_section(&program, seccomp_archs[i].value, nb_traced_syscalls);
|
||||||
|
+ status = start_arch_section(&program, seccomp_archs[i].value, section_length);
|
||||||
|
if (status < 0)
|
||||||
|
goto end;
|
||||||
|
|
||||||
|
@@ -292,14 +362,14 @@ static int set_seccomp_filters(const FilteredSysnum *sysnums)
|
||||||
|
continue;
|
||||||
|
|
||||||
|
/* Filter: trace if handled syscall */
|
||||||
|
- status = add_trace_syscall(&program, syscall, sysnums[k].flags);
|
||||||
|
+ status = add_trace(&program, sysnums[k].value, syscall, sysnums[k].flags);
|
||||||
|
if (status < 0)
|
||||||
|
goto end;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Filter: allow untraced syscalls for this architecture */
|
||||||
|
- status = end_arch_section(&program, nb_traced_syscalls);
|
||||||
|
+ status = end_arch_section(&program, section_length);
|
||||||
|
if (status < 0)
|
||||||
|
goto end;
|
||||||
|
}
|
||||||
|
@@ -411,7 +481,9 @@ static FilteredSysnum proot_sysnums[] = {
|
||||||
|
{ PR_truncate64, 0 },
|
||||||
|
{ PR_umount, 0 },
|
||||||
|
{ PR_umount2, 0 },
|
||||||
|
+#if defined(ARCH_X86_64)
|
||||||
|
{ PR_uname, FILTER_SYSEXIT },
|
||||||
|
+#endif
|
||||||
|
{ PR_unlink, 0 },
|
||||||
|
{ PR_unlinkat, 0 },
|
||||||
|
{ PR_uselib, 0 },
|
||||||
@@ -0,0 +1,242 @@
|
|||||||
|
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
|
||||||
|
From: maxjivi05 <maxjividen@gmail.com>
|
||||||
|
Date: Sun, 27 Sep 2026 07:57:46 -0400
|
||||||
|
Subject: [PATCH] seccomp: answer a stop's flags from its registers and skip
|
||||||
|
the sysexit stop when nothing is left for it
|
||||||
|
|
||||||
|
---
|
||||||
|
src/syscall/enter.c | 3 +++
|
||||||
|
src/syscall/seccomp.c | 51 +++++++++++++++++++++++++++++++++++++------
|
||||||
|
src/syscall/seccomp.h | 1 +
|
||||||
|
src/syscall/syscall.c | 17 ++++++++++++---
|
||||||
|
src/tracee/event.c | 14 +++++++-----
|
||||||
|
src/tracee/tracee.h | 2 ++
|
||||||
|
6 files changed, 73 insertions(+), 15 deletions(-)
|
||||||
|
|
||||||
|
diff --git a/src/syscall/enter.c b/src/syscall/enter.c
|
||||||
|
index 8c3eb2e..b84fdc3 100644
|
||||||
|
--- a/src/syscall/enter.c
|
||||||
|
+++ b/src/syscall/enter.c
|
||||||
|
@@ -149,6 +149,8 @@ int translate_syscall_enter(Tracee *tracee)
|
||||||
|
case PR_wait4:
|
||||||
|
case PR_waitpid:
|
||||||
|
status = translate_wait_enter(tracee);
|
||||||
|
+ tracee->sysexit_unneeded = status >= 0
|
||||||
|
+ && tracee->as_ptracer.waits_in == WAITS_IN_KERNEL;
|
||||||
|
break;
|
||||||
|
|
||||||
|
case PR_brk:
|
||||||
|
@@ -271,6 +273,7 @@ int translate_syscall_enter(Tracee *tracee)
|
||||||
|
case PR_accept4:
|
||||||
|
/* Nothing special to do if no sockaddr was specified. */
|
||||||
|
if (peek_reg(tracee, ORIGINAL, SYSARG_2) == 0) {
|
||||||
|
+ tracee->sysexit_unneeded = true;
|
||||||
|
status = 0;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
diff --git a/src/syscall/seccomp.c b/src/syscall/seccomp.c
|
||||||
|
index 8557d4a..cec4330 100644
|
||||||
|
--- a/src/syscall/seccomp.c
|
||||||
|
+++ b/src/syscall/seccomp.c
|
||||||
|
@@ -37,6 +37,7 @@
|
||||||
|
#include <string.h> /* memcpy(3), */
|
||||||
|
#include <stddef.h> /* offsetof(3), */
|
||||||
|
#include <stdint.h> /* uint*_t, UINT*_MAX, */
|
||||||
|
+#include <stdbool.h>
|
||||||
|
#include <sys/resource.h>
|
||||||
|
#include <assert.h> /* assert(3), */
|
||||||
|
|
||||||
|
@@ -542,6 +543,9 @@ static int merge_filtered_sysnums(TALLOC_CTX *context, FilteredSysnum **sysnums,
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
+static int collect_filtered_sysnums(TALLOC_CTX *context, const Tracee *tracee,
|
||||||
|
+ FilteredSysnum **filtered_sysnums);
|
||||||
|
+
|
||||||
|
/**
|
||||||
|
* Tell the kernel to trace only syscalls handled by PRoot and its
|
||||||
|
* extensions. This filter will be enabled for the given @tracee and
|
||||||
|
@@ -551,14 +555,30 @@ static int merge_filtered_sysnums(TALLOC_CTX *context, FilteredSysnum **sysnums,
|
||||||
|
int enable_syscall_filtering(const Tracee *tracee)
|
||||||
|
{
|
||||||
|
FilteredSysnum *filtered_sysnums = NULL;
|
||||||
|
- Extension *extension;
|
||||||
|
int status;
|
||||||
|
|
||||||
|
assert(tracee != NULL && tracee->ctx != NULL);
|
||||||
|
|
||||||
|
+ status = collect_filtered_sysnums(tracee->ctx, tracee, &filtered_sysnums);
|
||||||
|
+ if (status < 0)
|
||||||
|
+ return status;
|
||||||
|
+
|
||||||
|
+ status = set_seccomp_filters(filtered_sysnums);
|
||||||
|
+ if (status < 0)
|
||||||
|
+ return status;
|
||||||
|
+
|
||||||
|
+ return 0;
|
||||||
|
+}
|
||||||
|
+
|
||||||
|
+static int collect_filtered_sysnums(TALLOC_CTX *context, const Tracee *tracee,
|
||||||
|
+ FilteredSysnum **filtered_sysnums)
|
||||||
|
+{
|
||||||
|
+ Extension *extension;
|
||||||
|
+ int status;
|
||||||
|
+
|
||||||
|
/* Add the sysnums required by PRoot to the list of filtered
|
||||||
|
* sysnums. TODO: only if path translation is required. */
|
||||||
|
- status = merge_filtered_sysnums(tracee->ctx, &filtered_sysnums, proot_sysnums);
|
||||||
|
+ status = merge_filtered_sysnums(context, filtered_sysnums, proot_sysnums);
|
||||||
|
if (status < 0)
|
||||||
|
return status;
|
||||||
|
|
||||||
|
@@ -569,20 +589,37 @@ int enable_syscall_filtering(const Tracee *tracee)
|
||||||
|
if (extension->filtered_sysnums == NULL)
|
||||||
|
continue;
|
||||||
|
|
||||||
|
- status = merge_filtered_sysnums(tracee->ctx, &filtered_sysnums,
|
||||||
|
+ status = merge_filtered_sysnums(context, filtered_sysnums,
|
||||||
|
extension->filtered_sysnums);
|
||||||
|
if (status < 0)
|
||||||
|
return status;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
- status = set_seccomp_filters(filtered_sysnums);
|
||||||
|
- if (status < 0)
|
||||||
|
- return status;
|
||||||
|
-
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
+word_t filtered_sysnum_flags(const Tracee *tracee, Sysnum sysnum)
|
||||||
|
+{
|
||||||
|
+ static word_t flags[PR_NB_SYSNUM];
|
||||||
|
+ static bool initialized = false;
|
||||||
|
+ FilteredSysnum *filtered_sysnums = NULL;
|
||||||
|
+ size_t i;
|
||||||
|
+
|
||||||
|
+ if (!initialized) {
|
||||||
|
+ if (collect_filtered_sysnums(NULL, tracee, &filtered_sysnums) < 0) {
|
||||||
|
+ TALLOC_FREE(filtered_sysnums);
|
||||||
|
+ return FILTER_SYSEXIT;
|
||||||
|
+ }
|
||||||
|
+ for (i = 0; filtered_sysnums[i].value != PR_void; i++)
|
||||||
|
+ flags[filtered_sysnums[i].value] |= filtered_sysnums[i].flags;
|
||||||
|
+ TALLOC_FREE(filtered_sysnums);
|
||||||
|
+ initialized = true;
|
||||||
|
+ }
|
||||||
|
+
|
||||||
|
+ return sysnum < PR_NB_SYSNUM ? flags[sysnum] : FILTER_SYSEXIT;
|
||||||
|
+}
|
||||||
|
+
|
||||||
|
#else
|
||||||
|
|
||||||
|
#include "tracee/tracee.h"
|
||||||
|
diff --git a/src/syscall/seccomp.h b/src/syscall/seccomp.h
|
||||||
|
index 3d5ba40..67053b5 100644
|
||||||
|
--- a/src/syscall/seccomp.h
|
||||||
|
+++ b/src/syscall/seccomp.h
|
||||||
|
@@ -44,5 +44,6 @@ typedef struct {
|
||||||
|
#define FILTER_SYSEXIT 0x1
|
||||||
|
|
||||||
|
extern int enable_syscall_filtering(const Tracee *tracee);
|
||||||
|
+extern word_t filtered_sysnum_flags(const Tracee *tracee, Sysnum sysnum);
|
||||||
|
|
||||||
|
#endif /* SECCOMP_H */
|
||||||
|
diff --git a/src/syscall/syscall.c b/src/syscall/syscall.c
|
||||||
|
index 0761a26..9ab063c 100644
|
||||||
|
--- a/src/syscall/syscall.c
|
||||||
|
+++ b/src/syscall/syscall.c
|
||||||
|
@@ -107,9 +107,13 @@ void translate_syscall(Tracee *tracee)
|
||||||
|
|
||||||
|
assert(tracee->exe != NULL);
|
||||||
|
|
||||||
|
- status = fetch_regs(tracee);
|
||||||
|
- if (status < 0)
|
||||||
|
- return;
|
||||||
|
+ if (tracee->regs_fresh)
|
||||||
|
+ tracee->regs_fresh = false;
|
||||||
|
+ else {
|
||||||
|
+ status = fetch_regs(tracee);
|
||||||
|
+ if (status < 0)
|
||||||
|
+ return;
|
||||||
|
+ }
|
||||||
|
|
||||||
|
int suppressed_syscall_status = 0;
|
||||||
|
|
||||||
|
@@ -136,9 +140,16 @@ void translate_syscall(Tracee *tracee)
|
||||||
|
* requested by the tracee, it is not a syscall
|
||||||
|
* chained by PRoot. */
|
||||||
|
if (tracee->chain.syscalls == NULL) {
|
||||||
|
+ tracee->sysexit_unneeded = false;
|
||||||
|
save_current_regs(tracee, ORIGINAL);
|
||||||
|
status = translate_syscall_enter(tracee);
|
||||||
|
save_current_regs(tracee, MODIFIED);
|
||||||
|
+
|
||||||
|
+ if (status >= 0 && tracee->sysexit_unneeded
|
||||||
|
+ && tracee->seccomp == ENABLED && !tracee->sysexit_pending
|
||||||
|
+ && !tracee->restore_original_regs_after_seccomp_event
|
||||||
|
+ && get_sysnum(tracee, MODIFIED) == get_sysnum(tracee, ORIGINAL))
|
||||||
|
+ tracee->restart_how = PTRACE_CONT;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
if (tracee->chain.sysnum_workaround_state != SYSNUM_WORKAROUND_PROCESS_REPLACED_CALL) {
|
||||||
|
diff --git a/src/tracee/event.c b/src/tracee/event.c
|
||||||
|
index ec79ef3..41afacd 100644
|
||||||
|
--- a/src/tracee/event.c
|
||||||
|
+++ b/src/tracee/event.c
|
||||||
|
@@ -38,6 +38,7 @@
|
||||||
|
#include "tracee/event.h"
|
||||||
|
#include "tracee/seccomp.h"
|
||||||
|
#include "tracee/mem.h"
|
||||||
|
+#include "tracee/reg.h"
|
||||||
|
#include "cli/note.h"
|
||||||
|
#include "path/path.h"
|
||||||
|
#include "path/binding.h"
|
||||||
|
@@ -576,18 +577,20 @@ int handle_tracee_event(Tracee *tracee, int tracee_status)
|
||||||
|
if (tracee->seccomp != ENABLED)
|
||||||
|
break;
|
||||||
|
|
||||||
|
- status = ptrace(PTRACE_GETEVENTMSG, tracee->pid, NULL, &flags);
|
||||||
|
+ status = fetch_regs(tracee);
|
||||||
|
if (status < 0)
|
||||||
|
break;
|
||||||
|
+ tracee->regs_fresh = true;
|
||||||
|
+ flags = filtered_sysnum_flags(tracee, get_sysnum(tracee, CURRENT));
|
||||||
|
|
||||||
|
/* Use the common ptrace flow when
|
||||||
|
* sysexit has to be handled. */
|
||||||
|
if ((flags & FILTER_SYSEXIT) != 0 || sysexit_necessary) {
|
||||||
|
- if (seccomp_after_ptrace_enter) {
|
||||||
|
- tracee->restart_how = PTRACE_SYSCALL;
|
||||||
|
- translate_syscall(tracee);
|
||||||
|
- }
|
||||||
|
tracee->restart_how = PTRACE_SYSCALL;
|
||||||
|
+ if (seccomp_after_ptrace_enter)
|
||||||
|
+ translate_syscall(tracee);
|
||||||
|
+ else
|
||||||
|
+ tracee->regs_fresh = false;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
@@ -720,6 +723,7 @@ bool restart_tracee(Tracee *tracee, int signal)
|
||||||
|
|
||||||
|
tracee->last_restart_how = tracee->restart_how;
|
||||||
|
tracee->restart_how = 0;
|
||||||
|
+ tracee->regs_fresh = false;
|
||||||
|
tracee->running = true;
|
||||||
|
|
||||||
|
return true;
|
||||||
|
diff --git a/src/tracee/tracee.h b/src/tracee/tracee.h
|
||||||
|
index e4be3ff..c444a50 100644
|
||||||
|
--- a/src/tracee/tracee.h
|
||||||
|
+++ b/src/tracee/tracee.h
|
||||||
|
@@ -161,6 +161,8 @@ typedef struct tracee {
|
||||||
|
bool _regs_were_changed;
|
||||||
|
bool restore_original_regs;
|
||||||
|
bool restore_original_regs_after_seccomp_event;
|
||||||
|
+ bool regs_fresh;
|
||||||
|
+ bool sysexit_unneeded;
|
||||||
|
|
||||||
|
/* State for the special handling of SIGSTOP. */
|
||||||
|
enum {
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
|
||||||
|
From: maxjivi05 <maxjividen@gmail.com>
|
||||||
|
Date: Sun, 27 Sep 2026 07:58:07 -0400
|
||||||
|
Subject: [PATCH] tracee: take a clone3 child's exit signal from struct
|
||||||
|
clone_args
|
||||||
|
|
||||||
|
---
|
||||||
|
src/tracee/tracee.c | 10 +++++++---
|
||||||
|
1 file changed, 7 insertions(+), 3 deletions(-)
|
||||||
|
|
||||||
|
diff --git a/src/tracee/tracee.c b/src/tracee/tracee.c
|
||||||
|
index 7c0c50c..25eeb57 100644
|
||||||
|
--- a/src/tracee/tracee.c
|
||||||
|
+++ b/src/tracee/tracee.c
|
||||||
|
@@ -424,9 +424,13 @@ int new_child(Tracee *parent, word_t clone_flags)
|
||||||
|
if (status >= 0 && get_sysnum(parent, CURRENT) == PR_clone)
|
||||||
|
clone_flags = peek_reg(parent, CURRENT, SYSARG_1);
|
||||||
|
else if (status >= 0 && get_sysnum(parent, CURRENT) == PR_clone3) {
|
||||||
|
- word_t flags = peek_word(parent, peek_reg(parent, CURRENT, SYSARG_1));
|
||||||
|
- if (errno == 0)
|
||||||
|
- clone_flags = flags;
|
||||||
|
+ word_t args = peek_reg(parent, CURRENT, SYSARG_1);
|
||||||
|
+ word_t flags = peek_uint64(parent, args);
|
||||||
|
+ if (errno == 0) {
|
||||||
|
+ word_t exit_signal = peek_uint64(parent, args + 4 * sizeof(uint64_t));
|
||||||
|
+ if (errno == 0)
|
||||||
|
+ clone_flags = (flags & ~(word_t) 0xFF) | (exit_signal & 0xFF);
|
||||||
|
+ }
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Get the pid of the parent's new child. */
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
|
||||||
|
From: maxjivi05 <maxjividen@gmail.com>
|
||||||
|
Date: Sun, 27 Sep 2026 07:58:16 -0400
|
||||||
|
Subject: [PATCH] proc: name a thread's /proc/self by its thread group and
|
||||||
|
resolve /proc/thread-self
|
||||||
|
|
||||||
|
---
|
||||||
|
src/path/proc.c | 7 +++++--
|
||||||
|
src/tracee/tracee.c | 3 +++
|
||||||
|
src/tracee/tracee.h | 1 +
|
||||||
|
3 files changed, 9 insertions(+), 2 deletions(-)
|
||||||
|
|
||||||
|
diff --git a/src/path/proc.c b/src/path/proc.c
|
||||||
|
index 1c816df..62650f6 100644
|
||||||
|
--- a/src/path/proc.c
|
||||||
|
+++ b/src/path/proc.c
|
||||||
|
@@ -58,10 +58,13 @@ Action readlink_proc(const Tracee *tracee, char result[PATH_MAX],
|
||||||
|
switch (comparison) {
|
||||||
|
case PATHS_ARE_EQUAL:
|
||||||
|
/* Substitute "/proc/self" with "/proc/<PID>". */
|
||||||
|
- if (strcmp(component, "self") != 0)
|
||||||
|
+ if (strcmp(component, "self") == 0)
|
||||||
|
+ status = snprintf(result, PATH_MAX, "/proc/%d", tracee->tgid);
|
||||||
|
+ else if (strcmp(component, "thread-self") == 0)
|
||||||
|
+ status = snprintf(result, PATH_MAX, "/proc/%d/task/%d", tracee->tgid, tracee->pid);
|
||||||
|
+ else
|
||||||
|
return DEFAULT;
|
||||||
|
|
||||||
|
- status = snprintf(result, PATH_MAX, "/proc/%d", tracee->pid);
|
||||||
|
if (status < 0 || status >= PATH_MAX)
|
||||||
|
return -EPERM;
|
||||||
|
|
||||||
|
diff --git a/src/tracee/tracee.c b/src/tracee/tracee.c
|
||||||
|
index 25eeb57..d6e414d 100644
|
||||||
|
--- a/src/tracee/tracee.c
|
||||||
|
+++ b/src/tracee/tracee.c
|
||||||
|
@@ -234,6 +234,7 @@ static Tracee *new_tracee(pid_t pid)
|
||||||
|
talloc_set_destructor(tracee, remove_tracee);
|
||||||
|
|
||||||
|
tracee->pid = pid;
|
||||||
|
+ tracee->tgid = pid;
|
||||||
|
tracee->vpid = next_vpid++;
|
||||||
|
|
||||||
|
LIST_INSERT_HEAD(&tracees, tracee, link);
|
||||||
|
@@ -355,6 +356,7 @@ Tracee *get_tracee(const Tracee *current_tracee, pid_t pid, bool create)
|
||||||
|
void set_tracee_pid(Tracee *tracee, pid_t pid)
|
||||||
|
{
|
||||||
|
tracee->pid = pid;
|
||||||
|
+ tracee->tgid = pid;
|
||||||
|
LIST_REMOVE(tracee, bucket_link);
|
||||||
|
LIST_INSERT_HEAD(bucket_of(pid), tracee, bucket_link);
|
||||||
|
}
|
||||||
|
@@ -511,6 +513,7 @@ int new_child(Tracee *parent, word_t clone_flags)
|
||||||
|
* specificity (ie. when a thread calls execve(2), its pid
|
||||||
|
* gets replaced by the pid of its thread group leader). */
|
||||||
|
child->clone = ((clone_flags & CLONE_THREAD) != 0);
|
||||||
|
+ child->tgid = child->clone ? parent->tgid : child->pid;
|
||||||
|
|
||||||
|
/* Depending on how the new process is created, it may be
|
||||||
|
* automatically traced by the parent's tracer. */
|
||||||
|
diff --git a/src/tracee/tracee.h b/src/tracee/tracee.h
|
||||||
|
index c444a50..527f428 100644
|
||||||
|
--- a/src/tracee/tracee.h
|
||||||
|
+++ b/src/tracee/tracee.h
|
||||||
|
@@ -83,6 +83,7 @@ typedef struct tracee {
|
||||||
|
|
||||||
|
/* Process identifier. */
|
||||||
|
pid_t pid;
|
||||||
|
+ pid_t tgid;
|
||||||
|
|
||||||
|
/* Unique tracee identifier. */
|
||||||
|
uint64_t vpid;
|
||||||
@@ -0,0 +1,120 @@
|
|||||||
|
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
|
||||||
|
From: maxjivi05 <maxjividen@gmail.com>
|
||||||
|
Date: Sun, 27 Sep 2026 07:58:30 -0400
|
||||||
|
Subject: [PATCH] syscall: translate fchmodat2, send openat2 callers to openat,
|
||||||
|
bound sysnum lookups by the table length
|
||||||
|
|
||||||
|
---
|
||||||
|
src/syscall/enter.c | 18 ++++++++++++++++++
|
||||||
|
src/syscall/seccomp.c | 2 ++
|
||||||
|
src/syscall/sysnum.c | 2 +-
|
||||||
|
src/syscall/sysnums-arm.h | 2 ++
|
||||||
|
src/syscall/sysnums-arm64.h | 2 ++
|
||||||
|
src/syscall/sysnums.list | 2 ++
|
||||||
|
6 files changed, 27 insertions(+), 1 deletion(-)
|
||||||
|
|
||||||
|
diff --git a/src/syscall/enter.c b/src/syscall/enter.c
|
||||||
|
index b84fdc3..1d3b3fd 100644
|
||||||
|
--- a/src/syscall/enter.c
|
||||||
|
+++ b/src/syscall/enter.c
|
||||||
|
@@ -447,6 +447,24 @@ int translate_syscall_enter(Tracee *tracee)
|
||||||
|
status = translate_path2(tracee, dirfd, path, SYSARG_2, REGULAR);
|
||||||
|
break;
|
||||||
|
|
||||||
|
+ case PR_fchmodat2:
|
||||||
|
+ dirfd = peek_reg(tracee, CURRENT, SYSARG_1);
|
||||||
|
+ flags = peek_reg(tracee, CURRENT, SYSARG_4);
|
||||||
|
+
|
||||||
|
+ status = get_sysarg_path(tracee, path, SYSARG_2);
|
||||||
|
+ if (status < 0)
|
||||||
|
+ break;
|
||||||
|
+
|
||||||
|
+ if ((flags & AT_SYMLINK_NOFOLLOW) != 0)
|
||||||
|
+ status = translate_path2(tracee, dirfd, path, SYSARG_2, SYMLINK);
|
||||||
|
+ else
|
||||||
|
+ status = translate_path2(tracee, dirfd, path, SYSARG_2, REGULAR);
|
||||||
|
+ break;
|
||||||
|
+
|
||||||
|
+ case PR_openat2:
|
||||||
|
+ status = -ENOSYS;
|
||||||
|
+ break;
|
||||||
|
+
|
||||||
|
case PR_inotify_add_watch:
|
||||||
|
flags = peek_reg(tracee, CURRENT, SYSARG_3);
|
||||||
|
|
||||||
|
diff --git a/src/syscall/seccomp.c b/src/syscall/seccomp.c
|
||||||
|
index cec4330..0b381bb 100644
|
||||||
|
--- a/src/syscall/seccomp.c
|
||||||
|
+++ b/src/syscall/seccomp.c
|
||||||
|
@@ -419,6 +419,7 @@ static FilteredSysnum proot_sysnums[] = {
|
||||||
|
{ PR_faccessat2, FILTER_SYSEXIT },
|
||||||
|
{ PR_fchdir, FILTER_SYSEXIT },
|
||||||
|
{ PR_fchmodat, 0 },
|
||||||
|
+ { PR_fchmodat2, 0 },
|
||||||
|
{ PR_fchownat, 0 },
|
||||||
|
{ PR_fstatat64, 0 },
|
||||||
|
{ PR_futimesat, 0 },
|
||||||
|
@@ -455,6 +456,7 @@ static FilteredSysnum proot_sysnums[] = {
|
||||||
|
{ PR_oldstat, 0 },
|
||||||
|
{ PR_open, 0 },
|
||||||
|
{ PR_openat, 0 },
|
||||||
|
+ { PR_openat2, 0 },
|
||||||
|
{ PR_pivot_root, 0 },
|
||||||
|
{ PR_prctl, 0 },
|
||||||
|
{ PR_prlimit64, FILTER_SYSEXIT },
|
||||||
|
diff --git a/src/syscall/sysnum.c b/src/syscall/sysnum.c
|
||||||
|
index b5440a6..785593e 100644
|
||||||
|
--- a/src/syscall/sysnum.c
|
||||||
|
+++ b/src/syscall/sysnum.c
|
||||||
|
@@ -92,7 +92,7 @@ static Sysnum translate_sysnum(Abi abi, word_t sysnum)
|
||||||
|
index = sysnum - sysnums.offset;
|
||||||
|
|
||||||
|
/* Sanity checks. */
|
||||||
|
- if (index > sysnums.length)
|
||||||
|
+ if (index >= sysnums.length)
|
||||||
|
return PR_void;
|
||||||
|
|
||||||
|
return sysnums.table[index];
|
||||||
|
diff --git a/src/syscall/sysnums-arm.h b/src/syscall/sysnums-arm.h
|
||||||
|
index 0503fdd..e3f6f6b 100644
|
||||||
|
--- a/src/syscall/sysnums-arm.h
|
||||||
|
+++ b/src/syscall/sysnums-arm.h
|
||||||
|
@@ -358,4 +358,6 @@ static const Sysnum sysnums_arm[] = {
|
||||||
|
[ 397 ] = PR_statx,
|
||||||
|
[ 439 ] = PR_faccessat2,
|
||||||
|
[ 435 ] = PR_clone3,
|
||||||
|
+ [ 437 ] = PR_openat2,
|
||||||
|
+ [ 452 ] = PR_fchmodat2,
|
||||||
|
};
|
||||||
|
diff --git a/src/syscall/sysnums-arm64.h b/src/syscall/sysnums-arm64.h
|
||||||
|
index 751382f..b257339 100644
|
||||||
|
--- a/src/syscall/sysnums-arm64.h
|
||||||
|
+++ b/src/syscall/sysnums-arm64.h
|
||||||
|
@@ -279,5 +279,7 @@ static const Sysnum sysnums_arm64[] = {
|
||||||
|
[ 290 ] = PR_pkey_free,
|
||||||
|
[ 291 ] = PR_statx,
|
||||||
|
[ 435 ] = PR_clone3,
|
||||||
|
+ [ 437 ] = PR_openat2,
|
||||||
|
[ 439 ] = PR_faccessat2,
|
||||||
|
+ [ 452 ] = PR_fchmodat2,
|
||||||
|
};
|
||||||
|
diff --git a/src/syscall/sysnums.list b/src/syscall/sysnums.list
|
||||||
|
index 8170b6e..c221ddd 100644
|
||||||
|
--- a/src/syscall/sysnums.list
|
||||||
|
+++ b/src/syscall/sysnums.list
|
||||||
|
@@ -72,6 +72,7 @@ SYSNUM(fanotify_mark)
|
||||||
|
SYSNUM(fchdir)
|
||||||
|
SYSNUM(fchmod)
|
||||||
|
SYSNUM(fchmodat)
|
||||||
|
+SYSNUM(fchmodat2)
|
||||||
|
SYSNUM(fchown)
|
||||||
|
SYSNUM(fchown32)
|
||||||
|
SYSNUM(fchownat)
|
||||||
|
@@ -221,6 +222,7 @@ SYSNUM(olduname)
|
||||||
|
SYSNUM(open)
|
||||||
|
SYSNUM(open_by_handle_at)
|
||||||
|
SYSNUM(openat)
|
||||||
|
+SYSNUM(openat2)
|
||||||
|
SYSNUM(pause)
|
||||||
|
SYSNUM(pciconfig_iobase)
|
||||||
|
SYSNUM(pciconfig_read)
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
|
||||||
|
From: maxjivi05 <maxjividen@gmail.com>
|
||||||
|
Date: Sun, 27 Sep 2026 07:58:52 -0400
|
||||||
|
Subject: [PATCH] tracee: sweep relatives only for tracees that have some,
|
||||||
|
reuse the memory collector
|
||||||
|
|
||||||
|
---
|
||||||
|
src/path/path.h | 2 +-
|
||||||
|
src/tracee/tracee.c | 16 ++++++++++------
|
||||||
|
src/tracee/tracee.h | 1 +
|
||||||
|
3 files changed, 12 insertions(+), 7 deletions(-)
|
||||||
|
|
||||||
|
diff --git a/src/path/path.h b/src/path/path.h
|
||||||
|
index d455894..7d0e68d 100644
|
||||||
|
--- a/src/path/path.h
|
||||||
|
+++ b/src/path/path.h
|
||||||
|
@@ -48,9 +48,9 @@ typedef enum {
|
||||||
|
|
||||||
|
/* Path with cached attributes. */
|
||||||
|
typedef struct {
|
||||||
|
- char path[PATH_MAX];
|
||||||
|
size_t length;
|
||||||
|
Side side;
|
||||||
|
+ char path[PATH_MAX];
|
||||||
|
} Path;
|
||||||
|
|
||||||
|
/* Path ending type. */
|
||||||
|
diff --git a/src/tracee/tracee.c b/src/tracee/tracee.c
|
||||||
|
index d6e414d..8bb2929 100644
|
||||||
|
--- a/src/tracee/tracee.c
|
||||||
|
+++ b/src/tracee/tracee.c
|
||||||
|
@@ -105,12 +105,16 @@ static int remove_tracee(Tracee *tracee)
|
||||||
|
* span. */
|
||||||
|
talloc_report_depth_cb(tracee->life_context, 0, 100, clean_life_span_object, tracee);
|
||||||
|
|
||||||
|
- /* This could be optimize by using a dedicated list of
|
||||||
|
- * children and ptracees. */
|
||||||
|
+ if (tracee->parent != NULL)
|
||||||
|
+ tracee->parent->nb_children--;
|
||||||
|
+
|
||||||
|
+ if (tracee->nb_children != 0 || tracee->as_ptracer.nb_ptracees != 0)
|
||||||
|
LIST_FOREACH(relative, &tracees, link) {
|
||||||
|
/* Its children are now orphan. */
|
||||||
|
- if (relative->parent == tracee)
|
||||||
|
+ if (relative->parent == tracee) {
|
||||||
|
relative->parent = NULL;
|
||||||
|
+ tracee->nb_children--;
|
||||||
|
+ }
|
||||||
|
|
||||||
|
/* Its tracees are now free. */
|
||||||
|
if (relative->as_ptracee.ptracer == tracee) {
|
||||||
|
@@ -342,9 +346,7 @@ Tracee *get_tracee(const Tracee *current_tracee, pid_t pid, bool create)
|
||||||
|
|
||||||
|
LIST_FOREACH(tracee, bucket_of(pid), bucket_link) {
|
||||||
|
if (tracee->pid == pid) {
|
||||||
|
- /* Flush then allocate a new memory collector. */
|
||||||
|
- TALLOC_FREE(tracee->ctx);
|
||||||
|
- tracee->ctx = talloc_new(tracee);
|
||||||
|
+ talloc_free_children(tracee->ctx);
|
||||||
|
|
||||||
|
return tracee;
|
||||||
|
}
|
||||||
|
@@ -506,6 +508,8 @@ int new_child(Tracee *parent, word_t clone_flags)
|
||||||
|
child->parent = parent->parent;
|
||||||
|
else
|
||||||
|
child->parent = parent;
|
||||||
|
+ if (child->parent != NULL)
|
||||||
|
+ child->parent->nb_children++;
|
||||||
|
|
||||||
|
/* Remember if this child belongs to the same thread group as
|
||||||
|
* its parent. This is currently useful for ptrace emulation
|
||||||
|
diff --git a/src/tracee/tracee.h b/src/tracee/tracee.h
|
||||||
|
index 527f428..1fca85f 100644
|
||||||
|
--- a/src/tracee/tracee.h
|
||||||
|
+++ b/src/tracee/tracee.h
|
||||||
|
@@ -101,6 +101,7 @@ typedef struct tracee {
|
||||||
|
|
||||||
|
/* Parent of this tracee, NULL if none. */
|
||||||
|
struct tracee *parent;
|
||||||
|
+ size_t nb_children;
|
||||||
|
|
||||||
|
/* Is it a "clone", i.e has the same parent as its creator. */
|
||||||
|
bool clone;
|
||||||