diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 555d8b673c..15f68eb87c 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -562,6 +562,12 @@ jobs: command -v x86_64-w64-mingw32-gcc >/dev/null || { sudo apt-get update -qq && sudo apt-get install -y -qq gcc-mingw-w64-x86-64; } bash tools/ubisoft-launcher/build.sh + - name: Rockstar launcher service (32-bit and 64-bit) + run: | + set -euo pipefail + command -v i686-w64-mingw32-gcc >/dev/null || { sudo apt-get update -qq && sudo apt-get install -y -qq gcc-mingw-w64-i686; } + bash tools/rockstar-launcher/build.sh + - uses: actions/download-artifact@v4 with: name: xbox-arm64 @@ -617,12 +623,11 @@ jobs: - name: Check out MaliBridge run: git submodule update --init external/MaliBridge - name: Fetch the Mali (Venus) component (tools/venus/release.env) - env: - GH_TOKEN: ${{ github.token }} run: | set -euo pipefail . tools/venus/release.env - gh release download "${VENUS_TAG}" -R "${VENUS_REPO}" -p venus.tzst -O venus.tzst + curl -fsSL --retry 5 --retry-all-errors --retry-delay 10 -o venus.tzst \ + "https://github.com/${VENUS_REPO}/releases/download/${VENUS_TAG}/venus.tzst" echo "${VENUS_SHA256} venus.tzst" | sha256sum -c - tar --use-compress-program=unzstd -xf venus.tzst -C app/src/main test -f app/src/main/jniLibs/arm64-v8a/libvirgl_test_server.so @@ -798,9 +803,11 @@ jobs: set -o pipefail cd app/src/main/rust/stores cargo test --locked 2>&1 | tail -60 - - name: Ubisoft launcher service host unit tests + - name: Windows launcher service host unit tests timeout-minutes: 10 - run: cargo test --locked --manifest-path tools/ubisoft-launcher/Cargo.toml + run: | + cargo test --locked --manifest-path tools/ubisoft-launcher/Cargo.toml + cargo test --locked --manifest-path tools/rockstar-launcher/Cargo.toml python-tests: name: Python and native regression tests diff --git a/.gitignore b/.gitignore index 0a404ef667..d0fe3ea9ea 100644 --- a/.gitignore +++ b/.gitignore @@ -36,3 +36,4 @@ __pycache__/ app/src/main/assets/directaudio/ app/src/main/assets/hybris/ /tools/vr/out/ +app/src/main/resources/rockstar/helpers/ diff --git a/AGENTS.md b/AGENTS.md index c22c5647c0..447807615b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,3 +1,13 @@ # Rules - Comments should be rare, factual, and explain only non-obvious external constraints or business invariants. + +# Working on the device + +- `dd-lab-build` builds only committed work. Check `git status` and `gh api user` for the identity before committing; if `git config user.name` is empty, use the `gh` login's name and noreply email for this repo, never a guess. +- Do not commit or start a build in the same step: a build started next to a failed commit fails too. Commit first, check it, then build. +- Uncommitted changes in the tree may not be yours. Read `git diff` before committing them and tell the user what they do. +- If `dd-lab-build` says "could not read DroidDeck's state", loopback adb is down and `$ADB_SERIAL` is stale. Run `adb devices`; the port changes whenever wireless debugging is toggled. Ask the user to turn it on rather than retrying. +- A build that "did not start" can be adb, not the app. Read `~/.cache/dd-lab-build.json` and `.log` for the real reason; they can be stale from an earlier build, so compare their times with `date`. +- Run `dd-lab-build` with `run_in_background` and read its output file. A foreground `sleep` is blocked; wait with Monitor and an until-loop. +- The build restarts DroidDeck and ends your process. A turn that ends this way is not a failure. diff --git a/app/build.gradle b/app/build.gradle index 28bf184e32..bb0b7132e5 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -277,6 +277,8 @@ def stageRuntimeAssets = tasks.register('stageRuntimeAssets', Sync) { dependsOn(stageSessionScripts) from(layout.projectDirectory.dir('src/main/assets')) { exclude 'pulseaudio.tzst' } from(rootProject.file('tools/linuxfs/innoextract')) + from(rootProject.file('tools')) { include 'droiddeckctl', 'adb_device.py', 'proot_profile.py'; into('agent/ctl') } + from(rootProject.file('docs/agent-control.md')) { into('agent/ctl') } from(layout.buildDirectory.dir('prepared-assets')) into(runtimeAssetsDir) } @@ -380,6 +382,11 @@ dependencies { implementation 'androidx.activity:activity-compose:1.8.2' implementation 'androidx.compose.material:material-icons-extended' implementation 'io.coil-kt:coil-compose:2.6.0' + implementation 'io.noties.markwon:core:4.6.2' + implementation 'io.noties.markwon:ext-strikethrough:4.6.2' + implementation 'io.noties.markwon:ext-tables:4.6.2' + implementation 'io.noties.markwon:ext-tasklist:4.6.2' + implementation 'com.atlassian.commonmark:commonmark-ext-autolink:0.13.0' implementation 'com.caverock:androidsvg-aar:1.4' implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.3' implementation 'com.flyfishxu:kadb-android:1.2.1' @@ -387,11 +394,14 @@ dependencies { implementation 'androidx.camera:camera-camera2:1.4.2' implementation 'androidx.camera:camera-lifecycle:1.4.2' implementation 'androidx.webkit:webkit:1.12.1' + implementation 'androidx.palette:palette:1.0.0' implementation 'io.github.webrtc-sdk:android:125.6422.07' implementation("com.google.mediapipe:tasks-vision:${trackingPack.MEDIAPIPE_VERSION}") { exclude group: 'com.google.auto.value', module: 'auto-value' } implementation 'com.google.zxing:core:3.5.3' + implementation 'androidx.media3:media3-exoplayer:1.3.1' + implementation 'androidx.media3:media3-session:1.3.1' testImplementation 'junit:junit:4.13.2' testImplementation 'org.robolectric:robolectric:4.16.1' diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 4ae8741a4d..5d3f283701 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -18,8 +18,15 @@ + + + + + + + @@ -146,6 +153,7 @@ + @@ -339,6 +347,14 @@ android:name=".sync.SyncthingService" android:exported="false" android:foregroundServiceType="dataSync" /> + + + + + /dev/null 2>&1 +# Starts GitHub's device login and opens its approval page in Android. coproc GH { BROWSER=true gh auth login --hostname github.com --git-protocol https --web 2>&1; } -# bash drops GH and GH_PID once gh exits, which can be before the loop reads its last line. -ghpid=$GH_PID +gh_pid=$GH_PID exec {ghout}<&"${GH[0]}" {ghin}>&"${GH[1]}" -typed= +shown= while IFS= read -r line <&"$ghout"; do printf '%s\n' "$line" code=$(grep -oE '[A-Z0-9]{4}-[A-Z0-9]{4}' <<<"$line" | head -1) - if [ -n "$code" ] && [ -z "$typed" ]; then - typed=1 + if [ -n "$code" ] && [ -z "$shown" ]; then + shown=1 echo >&"$ghin" - adb -s "$serial" shell "am start --display $display -a android.intent.action.VIEW -d https://github.com/login/device" >/dev/null 2>&1 - # Chrome drops characters from `input text` and from fast key events on this page. - keys= - for ((i = 0; i < ${#code}; i++)); do - c=${code:i:1} - [ "$c" = - ] || keys+="input -d $display keyevent KEYCODE_$c; sleep 0.4; " - done - (sleep 7; adb -s "$serial" shell "$keys" >/dev/null 2>&1) & + printf 'GitHub device code: %s ยท github.com/login/device\n' "$code" + android-open https://github.com/login/device fi done -wait "$ghpid" +wait "$gh_pid" diff --git a/app/src/main/assets/agent/droiddeckctl b/app/src/main/assets/agent/droiddeckctl new file mode 100755 index 0000000000..a72cb2587c --- /dev/null +++ b/app/src/main/assets/agent/droiddeckctl @@ -0,0 +1,2 @@ +#!/bin/sh +exec python3 /root/.local/share/droiddeck/ctl/droiddeckctl "$@" diff --git a/app/src/main/cpp/waylandcomp/CMakeLists.txt b/app/src/main/cpp/waylandcomp/CMakeLists.txt index 61baf0d379..c7aa1b0eb4 100644 --- a/app/src/main/cpp/waylandcomp/CMakeLists.txt +++ b/app/src/main/cpp/waylandcomp/CMakeLists.txt @@ -1,5 +1,6 @@ add_library(droiddeckwayland SHARED src/compositor.c + src/clock_domain.c src/vk_present.c src/effects_chain.c src/cardboard.c diff --git a/app/src/main/cpp/waylandcomp/src/clock_domain.c b/app/src/main/cpp/waylandcomp/src/clock_domain.c new file mode 100644 index 0000000000..30fd73a4eb --- /dev/null +++ b/app/src/main/cpp/waylandcomp/src/clock_domain.c @@ -0,0 +1,72 @@ +#define _GNU_SOURCE +#include "clock_domain.h" + +#include +#include +#include +#include +#include +#include +#include + +static const int64_t *g_shift; +static pthread_mutex_t g_control_lock = PTHREAD_MUTEX_INITIALIZER; +static dev_t g_device; +static ino_t g_inode; + +void droiddeck_clock_domain_set_control(const char *path) { + int fd; + struct stat st; + pthread_mutex_lock(&g_control_lock); + if (!path || !*path) { + const int64_t *previous = g_shift; + g_shift = NULL; + if (previous) munmap((void *)previous, sizeof(*previous)); + pthread_mutex_unlock(&g_control_lock); + return; + } + fd = open(path, O_RDONLY | O_CLOEXEC); + if (fd < 0 || fstat(fd, &st) != 0 || st.st_size < (off_t)sizeof(int64_t)) { + if (fd >= 0) close(fd); + pthread_mutex_unlock(&g_control_lock); + return; + } + if (g_shift && st.st_dev == g_device && st.st_ino == g_inode) { + close(fd); + pthread_mutex_unlock(&g_control_lock); + return; + } + const int64_t *shift = mmap(NULL, sizeof(*shift), PROT_READ, MAP_SHARED, fd, 0); + close(fd); + if (shift != MAP_FAILED) { + g_device = st.st_dev; + g_inode = st.st_ino; + const int64_t *previous = g_shift; + g_shift = shift; + if (previous) munmap((void *)previous, sizeof(*previous)); + } + pthread_mutex_unlock(&g_control_lock); +} + +static int64_t shift_ns(void) { + pthread_mutex_lock(&g_control_lock); + const int64_t *mapping = g_shift; + int64_t shift = mapping ? __atomic_load_n(mapping, __ATOMIC_RELAXED) : 0; + pthread_mutex_unlock(&g_control_lock); + return shift > 0 ? shift : 0; +} + +int64_t droiddeck_clock_domain_adjust_ns(int64_t value) { + int64_t shift = shift_ns(); + return value > shift ? value - shift : 0; +} + +int64_t droiddeck_clock_domain_now_ns(void) { + struct timespec ts; + clock_gettime(CLOCK_MONOTONIC, &ts); + return droiddeck_clock_domain_adjust_ns((int64_t)ts.tv_sec * 1000000000LL + ts.tv_nsec); +} + +uint32_t droiddeck_clock_domain_now_ms(void) { + return (uint32_t)(droiddeck_clock_domain_now_ns() / 1000000LL); +} diff --git a/app/src/main/cpp/waylandcomp/src/clock_domain.h b/app/src/main/cpp/waylandcomp/src/clock_domain.h new file mode 100644 index 0000000000..acb7e0e174 --- /dev/null +++ b/app/src/main/cpp/waylandcomp/src/clock_domain.h @@ -0,0 +1,11 @@ +#ifndef DROIDDECK_CLOCK_DOMAIN_H +#define DROIDDECK_CLOCK_DOMAIN_H + +#include + +void droiddeck_clock_domain_set_control(const char *path); +int64_t droiddeck_clock_domain_now_ns(void); +uint32_t droiddeck_clock_domain_now_ms(void); +int64_t droiddeck_clock_domain_adjust_ns(int64_t value); + +#endif diff --git a/app/src/main/cpp/waylandcomp/src/compositor.c b/app/src/main/cpp/waylandcomp/src/compositor.c index 21ef1d23f9..3510ea29a3 100644 --- a/app/src/main/cpp/waylandcomp/src/compositor.c +++ b/app/src/main/cpp/waylandcomp/src/compositor.c @@ -36,6 +36,7 @@ #include "droiddeck_ext.h" #include "droiddeck_color.h" #include "compositor_internal.h" +#include "clock_domain.h" #define WLOGI(...) __android_log_print(ANDROID_LOG_INFO, "DroidDeckWayland", __VA_ARGS__) #define WLOGE(...) __android_log_print(ANDROID_LOG_ERROR, "DroidDeckWayland", __VA_ARGS__) @@ -727,9 +728,7 @@ static void on_pending_buffer_destroyed(struct wl_listener *l, void *data) { static void fire_frames(struct wl_list *frames) { struct wl_resource *cb, *tmp; uint32_t t; - struct timespec ts; - clock_gettime(CLOCK_MONOTONIC, &ts); - t = (uint32_t)(ts.tv_sec * 1000 + ts.tv_nsec / 1000000); + t = droiddeck_clock_domain_now_ms(); wl_resource_for_each_safe(cb, tmp, frames) { wl_callback_send_done(cb, t); wl_resource_destroy(cb); @@ -1061,6 +1060,7 @@ static int64_t presented_ns(int64_t render_ns) { static void feedback_present_all(struct wl_list *list, int64_t t) { struct wl_resource *fb, *tmp; + t = droiddeck_clock_domain_adjust_ns(t); uint64_t sec = (uint64_t)(t / 1000000000LL); uint32_t nsec = (uint32_t)(t % 1000000000LL); wl_resource_for_each_safe(fb, tmp, list) { @@ -2493,8 +2493,7 @@ static void on_vsync(int64_t frame_time_ns) { static uint32_t now_ms(void) { - struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); - return (uint32_t)(ts.tv_sec * 1000 + ts.tv_nsec / 1000000); + return droiddeck_clock_domain_now_ms(); } static void pointer_set_cursor(struct wl_client *c, struct wl_resource *r, uint32_t serial, @@ -3114,12 +3113,10 @@ static void relative_pointers_pointer_gone(struct wl_resource *pointer) { static int send_relative_motion(struct wl_client *client, double dx, double dy) { struct relative_pointer *rp; - struct timespec ts; uint64_t ut; int sent = 0; if (dx == 0 && dy == 0) return 0; - clock_gettime(CLOCK_MONOTONIC, &ts); - ut = (uint64_t)ts.tv_sec * 1000000ULL + (uint64_t)ts.tv_nsec / 1000; + ut = (uint64_t)(droiddeck_clock_domain_now_ns() / 1000); wl_list_for_each(rp, &g_relative_pointers, link) { if (!rp->pointer || wl_resource_get_client(rp->pointer) != client) continue; zwp_relative_pointer_v1_send_relative_motion(rp->resource, (uint32_t)(ut >> 32), (uint32_t)ut, diff --git a/app/src/main/cpp/waylandcomp/src/framegen_bridge.c b/app/src/main/cpp/waylandcomp/src/framegen_bridge.c index eceb796398..d29b328a05 100644 --- a/app/src/main/cpp/waylandcomp/src/framegen_bridge.c +++ b/app/src/main/cpp/waylandcomp/src/framegen_bridge.c @@ -33,7 +33,9 @@ static PFN_vkGetInstanceProcAddr g_gipa; static VkPhysicalDevice g_pd; static VkQueue g_queue; static uint32_t g_qfam; -static int g_dev_ready, g_dev_lost, g_features_enabled; +static _Atomic int g_dev_ready, g_dev_lost; +static int g_features_enabled; +static _Atomic int g_caps_lsfg_ok, g_caps_ddfg_ok; static VkPhysicalDeviceMemoryProperties g_memprops; static struct { PFN_vkCreateImage CreateImage; @@ -141,9 +143,12 @@ static void mark_failed(int kind) { } int vkp_framegen_problem(void) { - if (!g_dev_ready) return -1; + if (!atomic_load(&g_dev_ready)) return -1; int kind = atomic_load(&g_kind); - if (!fge_caps_ok(kind)) return 1; + int caps_ok = kind == VKP_FG_ENGINE_DDFG + ? atomic_load(&g_caps_ddfg_ok) + : atomic_load(&g_caps_lsfg_ok); + if (!caps_ok) return 1; if (start_failed_for(kind)) return 2; if (g_engine_ok && g_engine_kind == kind && fge_unavailable()) return 2; return 0; @@ -179,13 +184,17 @@ void vkp_framegen_device_ready(VkDevice dev, VkQueue queue, uint32_t qfam, int f #undef R g_vk.GetPhysicalDeviceMemoryProperties(g_pd, &g_memprops); fge_device_ready(g_gipa, g_inst, g_pd, dev, queue, qfam, features_enabled); - g_dev_ready = vk.CreateImage && vk.CreateImageView && vk.CmdPipelineBarrier; + atomic_store(&g_caps_lsfg_ok, fge_caps_ok(VKP_FG_ENGINE_LSFG)); + atomic_store(&g_caps_ddfg_ok, fge_caps_ok(VKP_FG_ENGINE_DDFG)); + atomic_store(&g_dev_lost, 0); + atomic_store(&g_dev_ready, + vk.CreateImage && vk.CreateImageView && vk.CmdPipelineBarrier); FGLOG("engines ready on the compositor's device: LSFG Native %s (%s), DD-FG Native %s", fge_caps_ok(VKP_FG_ENGINE_LSFG) ? "available" : "unavailable", fge_caps_reason(), fge_caps_ok(VKP_FG_ENGINE_DDFG) ? "available" : "unavailable"); } -void vkp_framegen_device_lost(void) { g_dev_lost = 1; } +void vkp_framegen_device_lost(void) { atomic_store(&g_dev_lost, 1); } static void destroy_ring(void) { @@ -244,7 +253,12 @@ static int ensure_ring(uint32_t w, uint32_t h, VkFormat fmt, uint32_t n) { static int engine_usable(void) { int kind = atomic_load(&g_kind); - return g_dev_ready && !g_dev_lost && fge_caps_ok(kind) && !start_failed_for(kind); + int ready = atomic_load(&g_dev_ready); + int lost = atomic_load(&g_dev_lost); + int caps_ok = kind == VKP_FG_ENGINE_DDFG + ? atomic_load(&g_caps_ddfg_ok) + : atomic_load(&g_caps_lsfg_ok); + return ready && !lost && caps_ok && !start_failed_for(kind); } int vkp_framegen_format_ok(VkFormat fmt) { diff --git a/app/src/main/cpp/waylandcomp/src/framegen_jni.c b/app/src/main/cpp/waylandcomp/src/framegen_jni.c index 35c5a3de46..e5a51456ed 100644 --- a/app/src/main/cpp/waylandcomp/src/framegen_jni.c +++ b/app/src/main/cpp/waylandcomp/src/framegen_jni.c @@ -50,6 +50,12 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeFrameGenCapsReason(J return (*env)->NewStringUTF(env, r ? r : ""); } +JNIEXPORT jboolean JNICALL +Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeFrameGenActive(JNIEnv *env, jclass clazz) { + (void)env; (void)clazz; + return vkp_framegen_active() ? JNI_TRUE : JNI_FALSE; +} + JNIEXPORT jfloatArray JNICALL Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeFrameGenStats(JNIEnv *env, jclass clazz) { (void)clazz; diff --git a/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c b/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c index ffbfdfd935..25b97ae0f8 100644 --- a/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c +++ b/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c @@ -18,6 +18,7 @@ #include "cardboard.h" #include "droiddeck_color.h" #include "gpu_clock_pin.h" +#include "clock_domain.h" extern int droiddeck_wayland_run(void); extern void droiddeck_wayland_set_scale_mode(int mode, int alignment); @@ -354,6 +355,13 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeVsync(JNIEnv *env, j droiddeck_wayland_vsync((int64_t)frameTimeNanos); } +JNIEXPORT void JNICALL +Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetClockControl(JNIEnv *env, jclass clazz, jstring path) { + const char *value = path ? (*env)->GetStringUTFChars(env, path, NULL) : NULL; + droiddeck_clock_domain_set_control(value); + if (value) (*env)->ReleaseStringUTFChars(env, path, value); +} + JNIEXPORT void JNICALL Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetHideShell(JNIEnv *env, jclass clazz, jboolean hide) { g_hide_shell = hide ? 1 : 0; diff --git a/app/src/main/java/com/droiddeck/launcher/App.kt b/app/src/main/java/com/droiddeck/launcher/App.kt index 79f42d118a..6ecd72d5f5 100644 --- a/app/src/main/java/com/droiddeck/launcher/App.kt +++ b/app/src/main/java/com/droiddeck/launcher/App.kt @@ -43,7 +43,10 @@ class App : Application() { process == "$packageName:shortcuts_sync" || process == "$packageName:bottom_desktop") return CrashHandler.install(this) com.droiddeck.launcher.agent.AgentHost.refresh(this) - if (com.droiddeck.launcher.agent.AgentHost.available) com.droiddeck.launcher.lab.LabNotice.openOnInstall = "agent" + com.droiddeck.launcher.agent.AgentTab.load(this) + com.droiddeck.launcher.ui.NavTabs.load(this) + com.droiddeck.launcher.ui.AgentPet.install(this) + if (com.droiddeck.launcher.agent.AgentTab.visible) com.droiddeck.launcher.lab.LabNotice.openOnInstall = "agent" com.droiddeck.launcher.lab.LabNotice.started(this) com.droiddeck.launcher.core.SteamIntegration.syncShortcutsListing(this) com.droiddeck.launcher.session.QuestExperimental.initialize(this) @@ -70,6 +73,7 @@ class App : Application() { com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.ubisoft.UbisoftBackend) com.droiddeck.launcher.stores.ea.EaBackend.app = this com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.ea.EaBackend) + com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.rockstar.RockstarBackend) } private fun prefetchAddonPacks() { diff --git a/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt index 55fdf3f1f3..c8ce1e4ae8 100644 --- a/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt @@ -84,7 +84,7 @@ import com.droiddeck.launcher.session.SteamLibraries import com.droiddeck.launcher.input.SecondScreenDisplay import com.droiddeck.launcher.input.SecondScreenDisplays -class FrontEndActivity : ComponentActivity() { +class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPetHost { override fun attachBaseContext(newBase: android.content.Context) { super.attachBaseContext(newBase) com.droiddeck.launcher.core.AppLanguage.applyTo(this, newBase) @@ -196,6 +196,7 @@ class FrontEndActivity : ComponentActivity() { private var stretch16x9 by mutableStateOf(false) private var orientation by mutableStateOf(android.content.pm.ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE) private var launcherOrientation by mutableStateOf(android.content.pm.ActivityInfo.SCREEN_ORIENTATION_USER) + private var homePage by mutableStateOf(com.droiddeck.launcher.core.AppUiPrefs.HOME_PAGE_STEAM) private var launcherFullscreen by mutableStateOf(true) private var downloadSource by mutableStateOf(DownloadSource.MODE_AUTO) private var downloadMirror by mutableStateOf("") @@ -205,6 +206,10 @@ class FrontEndActivity : ComponentActivity() { private var lowStorageWarning by mutableStateOf(true) private var launcherIcon by mutableStateOf(LauncherIcon.DARK) private var gameStoresEnabled by mutableStateOf(true) + private var soundtracksEnabled by mutableStateOf(true) + private var soundtracksIngame by mutableStateOf(false) + private var soundtracks by mutableStateOf>(emptyList()) + private var soundtracksLoaded by mutableStateOf(false) private var gameStoresSpeedTier by mutableStateOf("fast") private var navRequest by mutableStateOf(null) private val gameLaunchRequest = java.util.concurrent.atomic.AtomicLong() @@ -226,6 +231,11 @@ class FrontEndActivity : ComponentActivity() { refreshWifiDiscovery() } } + private val dateReceiver = object : android.content.BroadcastReceiver() { + override fun onReceive(context: android.content.Context?, intent: Intent?) { + refreshAndroidApps() + } + } private val mediaRefresh = Runnable { refresh() refreshAddedGames() @@ -593,6 +603,7 @@ class FrontEndActivity : ComponentActivity() { private var vacDiagnostics by mutableStateOf(false) private var agentCommands by mutableStateOf(false) private var graphicsLogs by mutableStateOf(false) + private var buildWatermark by mutableStateOf(true) private var steamGpuDrawing by mutableStateOf(false) private var bridgeFellBack by mutableStateOf(false) private var bridgeFellBackMemory by mutableStateOf(false) @@ -778,6 +789,11 @@ class FrontEndActivity : ComponentActivity() { private var shortcutPicker by mutableStateOf(false) private var shortcutLibraryScanning by mutableStateOf(false) @Volatile private var libraryScanGeneration = 0 + private class SoundtrackRemoval(val op: Int, var scan: Int, var settled: Boolean) + private val soundtrackRemovals = HashMap() + private var soundtrackOp = 0 + private var soundtrackAddScan = -1 + private val soundtrackWork = java.util.concurrent.Executors.newSingleThreadExecutor { r -> Thread(r, "soundtrack-work").apply { isDaemon = true } } @Volatile private var lastComponentRestore = 0L @Volatile private var componentRestoreRetry = false private val componentRestoreLock = Any() @@ -828,6 +844,10 @@ class FrontEndActivity : ComponentActivity() { private fun readGameIntent(request: Intent) { request.getStringExtra(com.droiddeck.launcher.stores.download.StoreDownloadService.EXTRA_NAV)?.let { navRequest = it; request.removeExtra(com.droiddeck.launcher.stores.download.StoreDownloadService.EXTRA_NAV) } + if (navRequest == com.droiddeck.launcher.core.AppUiPrefs.HOME_PAGE_APPS) { + homeAppSelected = HomeApp.isHomeScreenEnabled(this) && HomeApp.isDefault(this) + if (!homeAppSelected) navRequest = null + } shortcutPicker = request.action == Intent.ACTION_CREATE_SHORTCUT if (shortcutPicker) { steamGames = emptyList() @@ -836,6 +856,15 @@ class FrontEndActivity : ComponentActivity() { pendingGameLink = null gameLinkReading = false gameLinkTried = false + soundtrackLaunch = false + val soundtrackId = com.droiddeck.launcher.frontend.SoundtrackShortcuts.read(request) + if (soundtrackId != null) { + soundtrackLaunch = true + navRequest = if (SessionPrefs.soundtracksEnabled(this)) "sound:$soundtrackId" else "app:$soundtrackId" + request.data = null + request.action = Intent.ACTION_MAIN + return + } if (GameLaunchIntent.accepts(request.action)) { gameLinkReading = true com.droiddeck.launcher.ui.DualScreenPanel.hide(taskId) @@ -860,6 +889,7 @@ class FrontEndActivity : ComponentActivity() { } private fun launchGame(game: Library.SteamGame, returnHome: Boolean = false): Boolean { + if (!SessionPrefs.soundtracksIngame(this)) com.droiddeck.launcher.playback.SoundtrackController.pause(this) if (pkgStage != null) { android.widget.Toast.makeText(this, R.string.main_wait_install_game, android.widget.Toast.LENGTH_SHORT).show() return false @@ -1106,7 +1136,7 @@ class FrontEndActivity : ComponentActivity() { if (savedInstanceState == null) readIntegrationIntent(intent) readGameIntent(intent) // A Lab build is usually the agent's work, so the app comes back where the agent is. - if (savedInstanceState == null && navRequest == null && com.droiddeck.launcher.lab.LabOverlay.promoted && com.droiddeck.launcher.agent.AgentHost.available) navRequest = "agent" + if (savedInstanceState == null && navRequest == null && com.droiddeck.launcher.lab.LabOverlay.promoted && com.droiddeck.launcher.agent.AgentTab.visible) navRequest = "agent" gameSyncFolder = GameFileSync.folder(this) displayManager = getSystemService(DISPLAY_SERVICE) as DisplayManager refreshPhantomStatus() @@ -1121,6 +1151,7 @@ class FrontEndActivity : ComponentActivity() { orientation = SessionPrefs.orientation(this) launcherOrientation = com.droiddeck.launcher.core.AppUiPrefs.orientation(this) requestedOrientation = launcherOrientation + homePage = com.droiddeck.launcher.core.AppUiPrefs.homePage(this) launcherFullscreen = SessionPrefs.launcherFullscreen(this) downloadSource = DownloadSource.mode(this) downloadMirror = DownloadSource.mirror(this) @@ -1132,6 +1163,8 @@ class FrontEndActivity : ComponentActivity() { LauncherIcon.repair(this, intent?.component) launcherIcon = LauncherIcon.current(this) gameStoresEnabled = SessionPrefs.gameStoresEnabled(this) + soundtracksEnabled = SessionPrefs.soundtracksEnabled(this) + soundtracksIngame = SessionPrefs.soundtracksIngame(this) gameStoresSpeedTier = SessionPrefs.gameStoresSpeedTier(this) storesShowMature = SessionPrefs.storesShowMature(this) storesSort = SessionPrefs.storesSort(this) @@ -1178,6 +1211,7 @@ class FrontEndActivity : ComponentActivity() { gameDebugLogsEnabled = gameDebugLogsEnabled, gameDebugLogsNeedsRestart = gameDebugLogsNeedsRestart, vacDiagnostics = vacDiagnostics, agentCommands = agentCommands, graphicsLogs = graphicsLogs, steamGpuDrawing = steamGpuDrawing, bridgeFellBack = bridgeFellBack, bridgeFellBackMemory = bridgeFellBackMemory, + buildWatermark = buildWatermark, clearCachedApps = clearCachedApps, adbPaired = adbPaired, memoryHud = memoryHud, backgroundAppLimit = backgroundAppLimit, tpUbwcMode = drivers.tpUbwcModeForDevice(), tpUbwcRestartRequired = drivers.tpUbwcRestartRequired(), canRestartApp = !runtimeChangesBlocked(), steamGames = steamGames, steamGamesX64 = steamGamesX64, emulators = emulatorList, running = runningLabel, @@ -1216,6 +1250,7 @@ class FrontEndActivity : ComponentActivity() { showPhantomGate = showPhantomGate, orientation = orientation, launcherOrientation = launcherOrientation, + homePage = homePage, launcherFullscreen = launcherFullscreen, downloadSource = downloadSource, downloadMirror = downloadMirror, @@ -1225,6 +1260,10 @@ class FrontEndActivity : ComponentActivity() { lowStorageWarning = lowStorageWarning, launcherIcon = launcherIcon, gameStoresEnabled = gameStoresEnabled, + soundtracksEnabled = soundtracksEnabled, + soundtracksIngame = soundtracksIngame, + soundtracks = soundtracks, + soundtracksLoaded = soundtracksLoaded, gameStoresSpeedTier = gameStoresSpeedTier, navigate = navRequest, addedGamesArt = addedGamesArt, @@ -1273,7 +1312,10 @@ class FrontEndActivity : ComponentActivity() { }, onEpicLauncher = { openEpicLauncher() }, onUninstallEpicLauncher = { uninstallEpicLauncher() }, - onGameShortcut = { g -> com.droiddeck.launcher.frontend.GameShortcuts.pin(this, g) }, + onGameShortcut = { g -> + if (g.soundtrack) com.droiddeck.launcher.frontend.SoundtrackShortcuts.pin(this, g) + else com.droiddeck.launcher.frontend.GameShortcuts.pin(this, g) + }, onExportGameFile = { g -> pickGameExport(g) }, onSyncGameFiles = { pickGameExport(null) }, onAddGameExe = { path -> addGameExe(path) }, @@ -1298,8 +1340,9 @@ class FrontEndActivity : ComponentActivity() { }, "game-file-stop-sync").start() }, onCopyGameLink = { g -> - (getSystemService(CLIPBOARD_SERVICE) as ClipboardManager).setPrimaryClip( - ClipData.newPlainText(g.name, com.droiddeck.launcher.frontend.GameLaunchLink.uri(g.gameIdString))) + val link = if (g.soundtrack) com.droiddeck.launcher.frontend.SoundtrackShortcuts.uri(g.appId) + else com.droiddeck.launcher.frontend.GameLaunchLink.uri(g.gameIdString) + (getSystemService(CLIPBOARD_SERVICE) as ClipboardManager).setPrimaryClip(ClipData.newPlainText(g.name, link)) android.widget.Toast.makeText(this, R.string.game_link_copied, android.widget.Toast.LENGTH_SHORT).show() }, onDesktop = { @@ -1324,6 +1367,7 @@ class FrontEndActivity : ComponentActivity() { }, onRom = { g -> val e = emulatorList.first { it.id == g.emulatorId } + if (!SessionPrefs.soundtracksIngame(this)) com.droiddeck.launcher.playback.SoundtrackController.pause(this) startActivity(Intent(this, SessionActivity::class.java) .putExtra(SessionService.EXTRA_MODE, SessionService.MODE_RUN) .putExtra(SessionService.EXTRA_PROGRAM, e.program) @@ -1416,6 +1460,11 @@ class FrontEndActivity : ComponentActivity() { SessionPrefs.setDetailedGraphicsLogs(this, !SessionPrefs.detailedGraphicsLogs(this)) graphicsLogs = SessionPrefs.detailedGraphicsLogs(this) }, + onBuildWatermark = { + SessionPrefs.setBuildWatermarkEnabled(this, !SessionPrefs.buildWatermarkEnabled(this)) + buildWatermark = SessionPrefs.buildWatermarkEnabled(this) + com.droiddeck.launcher.ui.BuildWatermark.refresh(this) + }, onVacDiagnostics = { SessionPrefs.setVacDiagnostics(this, !SessionPrefs.vacDiagnostics(this)) vacDiagnostics = SessionPrefs.vacDiagnostics(this) @@ -1487,6 +1536,15 @@ class FrontEndActivity : ComponentActivity() { }, onPageBack = { showPerformance = false; showComponents = false; showMapping = false }, onGameStoresEnabled = { on -> SessionPrefs.setGameStoresEnabled(this, on); gameStoresEnabled = on }, + onSoundtracksEnabled = { on -> SessionPrefs.setSoundtracksEnabled(this, on); soundtracksEnabled = on }, + onSoundtracksIngame = { on -> + SessionPrefs.setSoundtracksIngame(this, on) + soundtracksIngame = on + com.droiddeck.launcher.playback.SoundtrackController.setIngame(this, on) + }, + onSoundtrackAdded = { folder -> addSoundtrack(folder) }, + onSoundtracksChanged = { refreshAddedSoundtracks() }, + onSoundtrackRemoved = { g -> removeSoundtrack(g) }, onTheme = { id -> SessionPrefs.setTheme(this, id); theme = id }, onLauncherIcon = { style -> switchLauncherIcon(style) }, onLanguage = { tag -> @@ -1508,6 +1566,10 @@ class FrontEndActivity : ComponentActivity() { launcherOrientation = value requestedOrientation = value }, + onHomePage = { value -> + com.droiddeck.launcher.core.AppUiPrefs.setHomePage(this, value) + homePage = value + }, onLauncherFullscreen = { on -> SessionPrefs.setLauncherFullscreen(this, on) launcherFullscreen = on @@ -1576,6 +1638,7 @@ class FrontEndActivity : ComponentActivity() { refreshHomeAppState() } }, + onAppIconsChanged = { refreshAndroidApps() }, onAndroidApp = { app, displayId -> launchAndroidApp(app, displayId) }, onBackActionsInverted = { inverted -> SessionPrefs.setBackActionsInverted(this, inverted) @@ -1758,6 +1821,8 @@ class FrontEndActivity : ComponentActivity() { }, "finish-abandoned").start() } + override val petBlocked: Boolean get() = false + override fun onNewIntent(intent: Intent) { super.onNewIntent(intent) setIntent(intent) @@ -1773,7 +1838,10 @@ class FrontEndActivity : ComponentActivity() { startSteamAtStartupIfEnabled() } + private var soundtrackLaunch = false + private fun startSteamAtStartupIfEnabled(cold: Boolean = false) { + if (soundtrackLaunch) return if (intent.action != Intent.ACTION_MAIN && !(cold && intent.action == null)) return if (isFinishing || isDestroyed) return when (SessionPrefs.startupSession(this)) { @@ -1851,6 +1919,7 @@ class FrontEndActivity : ComponentActivity() { } override fun dispatchKeyEvent(event: KeyEvent): Boolean { + if (com.droiddeck.launcher.ui.AgentPet.handleBack(this, event)) return true if (compatLaunch != null) { if (event.keyCode == KeyEvent.KEYCODE_BACK || event.keyCode == KeyEvent.KEYCODE_BUTTON_B) { if (event.action == KeyEvent.ACTION_UP) cancelCompatLaunch() @@ -1900,6 +1969,7 @@ class FrontEndActivity : ComponentActivity() { orientation = SessionPrefs.orientation(this) launcherOrientation = com.droiddeck.launcher.core.AppUiPrefs.orientation(this) requestedOrientation = launcherOrientation + homePage = com.droiddeck.launcher.core.AppUiPrefs.homePage(this) SteamIntegration.syncShortcutsListing(this) refreshWifiDiscovery() com.droiddeck.launcher.stores.StoresState.refresh(this) @@ -1953,6 +2023,7 @@ class FrontEndActivity : ComponentActivity() { override fun onStart() { super.onStart() registerReceiver(wifiLocationReceiver, android.content.IntentFilter(android.location.LocationManager.MODE_CHANGED_ACTION)) + registerReceiver(dateReceiver, android.content.IntentFilter(Intent.ACTION_DATE_CHANGED)) registerReceiver(mediaReceiver, android.content.IntentFilter().apply { for (action in listOf(Intent.ACTION_MEDIA_MOUNTED, Intent.ACTION_MEDIA_UNMOUNTED, Intent.ACTION_MEDIA_REMOVED, Intent.ACTION_MEDIA_EJECT, Intent.ACTION_MEDIA_BAD_REMOVAL)) addAction(action) @@ -2019,6 +2090,7 @@ class FrontEndActivity : ComponentActivity() { override fun onStop() { if (!homeChoiceOpen) HomeApp.releaseUnusedHomeEntry(this) unregisterReceiver(wifiLocationReceiver) + unregisterReceiver(dateReceiver) unregisterReceiver(mediaReceiver) getSystemService(android.content.pm.LauncherApps::class.java).unregisterCallback(packageCallback) HomeWidgets.stopListening(this) @@ -2614,15 +2686,89 @@ class FrontEndActivity : ComponentActivity() { val version = (steamArtRefreshes[appId] ?: 0) + 1 steamArtRefreshes[appId] = version Thread({ - val fresh = com.droiddeck.launcher.frontend.Library.steamGames(this).firstOrNull { it.appId == appId } ?: return@Thread + val fresh = com.droiddeck.launcher.frontend.Library.steamGames(this, soundtracks = true).firstOrNull { it.appId == appId } ?: return@Thread ui.post { if (steamArtRefreshes[appId] != version) return@post - steamGames = steamGames.map { if (it.appId == appId && it.library != Library.ADDED) fresh else it } + if (fresh.soundtrack) soundtracks = soundtracks.map { if (it.appId == appId && it.library != Library.ADDED) fresh else it } + else steamGames = steamGames.map { if (it.appId == appId && it.library != Library.ADDED) fresh else it } } }, "steam-art-update").start() } + private fun addSoundtrack(folder: java.io.File) { + val op = ++soundtrackOp + soundtrackAddScan = libraryScanGeneration + soundtrackWork.execute { + val added = com.droiddeck.launcher.frontend.AddedSoundtracks.add(this, folder) + val list = com.droiddeck.launcher.frontend.AddedSoundtracks.games(this) + ui.post { + if (added) { + soundtrackRemovals[folder.path]?.takeIf { it.op < op }?.let { + soundtrackRemovals.remove(folder.path) + com.droiddeck.launcher.playback.SoundtrackController.allow(listOf(folder.path)) + } + val visible = list.filterNot { s -> s.gameFiles?.path?.let { soundtrackRemovals[it] }?.let { it.op > op } == true } + soundtracks = soundtracks.filter { it.library != Library.ADDED } + visible + } else android.widget.Toast.makeText(this, R.string.soundtracks_add_empty, android.widget.Toast.LENGTH_SHORT).show() + } + } + } + + private fun refreshAddedSoundtracks() { + val op = soundtrackOp + soundtrackWork.execute { + val list = com.droiddeck.launcher.frontend.AddedSoundtracks.games(this) + ui.post { + if (op != soundtrackOp) return@post + val visible = list.filterNot { s -> s.gameFiles?.path?.let { soundtrackRemovals[it] } != null } + soundtracks = soundtracks.filter { it.library != Library.ADDED } + visible + } + } + } + + private fun removeSoundtrack(g: Library.SteamGame) { + val path = g.gameFiles?.path + val added = g.library == Library.ADDED + val target = if (added) null else com.droiddeck.launcher.frontend.GameRemoval.steamFiles(g) ?: return + com.droiddeck.launcher.playback.SoundtrackController.stopIf(this, g.gameFiles) + val marker = SoundtrackRemoval(++soundtrackOp, libraryScanGeneration, added) + path?.let { soundtrackRemovals[it] = marker } + if (target == null) { + soundtracks = soundtracks.filterNot { it.appId == g.appId && it.library == Library.ADDED } + soundtrackWork.execute { + val removed = com.droiddeck.launcher.frontend.AddedSoundtracks.remove(this, path.orEmpty()) + val list = if (removed) emptyList() else com.droiddeck.launcher.frontend.AddedSoundtracks.games(this) + if (!removed) ui.post { + if (path != null && soundtrackRemovals[path] === marker) { + soundtrackRemovals.remove(path) + com.droiddeck.launcher.playback.SoundtrackController.allow(listOf(path)) + } + soundtracks = soundtracks.filter { it.library != Library.ADDED } + list.filterNot { s -> s.gameFiles?.path?.let { soundtrackRemovals[it] } != null } + android.widget.Toast.makeText(this, getString(R.string.gfiles_remove_failed, g.name), android.widget.Toast.LENGTH_SHORT).show() + } + } + return + } + soundtrackWork.execute { + val deleted = com.droiddeck.launcher.frontend.GameRemoval.delete(target) + ui.post { + if (deleted) { + marker.scan = libraryScanGeneration + marker.settled = true + } else { + if (path != null && soundtrackRemovals[path] === marker) { + soundtrackRemovals.remove(path) + com.droiddeck.launcher.playback.SoundtrackController.allow(listOf(path)) + } + android.widget.Toast.makeText(this, getString(R.string.gfiles_remove_failed, g.name), android.widget.Toast.LENGTH_SHORT).show() + } + refresh() + } + } + } + private fun removeGame(g: Library.SteamGame) { + if (g.soundtrack) { removeSoundtrack(g); return } val folder = g.gameFiles ?: return when (com.droiddeck.launcher.frontend.GameRemoval.kind(g)) { com.droiddeck.launcher.frontend.GameRemoval.Kind.LAUNCHER -> Unit @@ -2867,6 +3013,7 @@ class FrontEndActivity : ComponentActivity() { vacDiagnostics = SessionPrefs.vacDiagnostics(this) agentCommands = com.droiddeck.launcher.agent.AgentAccess.commandsEnabled(this) graphicsLogs = SessionPrefs.detailedGraphicsLogs(this) + buildWatermark = SessionPrefs.buildWatermarkEnabled(this) steamGpuDrawing = SessionPrefs.steamGpuCompositing(this) bridgeFellBack = SessionPrefs.bridgeFellBack(this) bridgeFellBackMemory = SessionPrefs.bridgeFellBackForMemory(this) @@ -2905,6 +3052,19 @@ class FrontEndActivity : ComponentActivity() { } val scannedArch = SessionPrefs.activeSteamClientArch(this) val scannedX64 = scannedArch == "x86_64" + val scannedSoundtracks = runCatching { + (if (ready || com.droiddeck.launcher.runtime.LinuxRuntime.hasRootfs(this)) Library.soundtracks(this, scannedArch) else emptyList()) + + com.droiddeck.launcher.frontend.AddedSoundtracks.games(this) + }.getOrDefault(emptyList()) + ui.post { + if (scanGeneration == libraryScanGeneration) { + val scanned = if (scanGeneration <= soundtrackAddScan) scannedSoundtracks + soundtracks.filter { cur -> cur.library == Library.ADDED && scannedSoundtracks.none { it.library == Library.ADDED && it.appId == cur.appId } } else scannedSoundtracks + val kept = scanned.filterNot { s -> s.gameFiles?.path?.let { p -> soundtrackRemovals[p]?.let { m -> !m.settled || s.library == Library.ADDED || scanGeneration <= m.scan } } == true } + com.droiddeck.launcher.playback.SoundtrackController.allow(kept.mapNotNull { it.gameFiles?.path }) + soundtracks = kept + soundtracksLoaded = true + } + } val games = if (ready || com.droiddeck.launcher.runtime.LinuxRuntime.hasRootfs(this)) Library.launchableGames(this, arch = scannedArch) else emptyList() val all = games.distinctBy { it.gameId } if (ready && scanGeneration == libraryScanGeneration) com.droiddeck.launcher.frontend.LibraryCache.save(this, all, scannedX64) @@ -3046,6 +3206,8 @@ class FrontEndActivity : ComponentActivity() { com.droiddeck.launcher.core.AppLanguage.setChosen(this, com.droiddeck.launcher.core.AppLanguage.SYSTEM) if (!ok) android.widget.Toast.makeText(this, R.string.setup_reset_settings_partial, android.widget.Toast.LENGTH_LONG).show() com.droiddeck.launcher.ui.Motion.refresh(this) + com.droiddeck.launcher.agent.AgentTab.load(this) + com.droiddeck.launcher.ui.NavTabs.load(this) if (!switchLauncherIcon(LauncherIcon.DARK)) recreate() } }, "reset-settings").start() diff --git a/app/src/main/java/com/droiddeck/launcher/HomeActivity.kt b/app/src/main/java/com/droiddeck/launcher/HomeActivity.kt index 59e10c48e7..0f3a37e83e 100644 --- a/app/src/main/java/com/droiddeck/launcher/HomeActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/HomeActivity.kt @@ -4,6 +4,7 @@ import android.app.Activity import android.content.Intent import android.os.Bundle import com.droiddeck.launcher.session.SessionService +import com.droiddeck.launcher.session.SessionState class HomeActivity : Activity() { override fun attachBaseContext(newBase: android.content.Context) { @@ -18,15 +19,22 @@ class HomeActivity : Activity() { } private fun routeHome() { - val destination = if (HomeApp.isActiveSteamSession()) { + val destination = if (HomeApp.isActiveSteamSession() && !SessionState.pipActive) { Intent(this, SessionActivity::class.java) .setAction(SessionService.ACTION_HOME_GUIDE) .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP) } else { Intent(this, FrontEndActivity::class.java) .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP) + .apply { + val page = com.droiddeck.launcher.core.AppUiPrefs.homePage(this@HomeActivity) + if (page != com.droiddeck.launcher.core.AppUiPrefs.HOME_PAGE_STEAM) { + putExtra(com.droiddeck.launcher.stores.download.StoreDownloadService.EXTRA_NAV, page) + } + } } - startActivity(destination) + if (SessionState.pipActive && destination.component?.className == FrontEndActivity::class.java.name) HomeApp.showFrontEnd(this, destination) + else startActivity(destination) finish() } } diff --git a/app/src/main/java/com/droiddeck/launcher/HomeApp.kt b/app/src/main/java/com/droiddeck/launcher/HomeApp.kt index 9a724d9044..789af4ec49 100644 --- a/app/src/main/java/com/droiddeck/launcher/HomeApp.kt +++ b/app/src/main/java/com/droiddeck/launcher/HomeApp.kt @@ -41,7 +41,7 @@ object HomeApp { val userSerial: Long = 0L, ) { val component get() = ComponentName(packageName, className) - val key get() = "$packageName/$className" + if (userSerial != 0L) "#$userSerial" else "" + val key get() = appKey(packageName, className, userSerial) val work get() = userSerial != 0L } @@ -101,6 +101,9 @@ object HomeApp { ?: resolved.loadLabel(pm)?.toString()?.trim()?.takeIf { it.isNotEmpty() } } + private fun appKey(packageName: String, className: String, userSerial: Long) = + "$packageName/$className" + if (userSerial != 0L) "#$userSerial" else "" + fun roleRequestIntent(context: Context): Intent? { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) return null val roles = context.getSystemService(RoleManager::class.java) ?: return null @@ -116,13 +119,25 @@ object HomeApp { val pm = context.packageManager val own = Process.myUserHandle() val iconPx = (ICON_DP * context.resources.displayMetrics.density).roundToInt() + val densityDpi = context.resources.displayMetrics.densityDpi + val pack = IconPack.active(context) + val appColors = IconPack.appColors(context) + HomeIcons.load(context) + val overrides = HomeIcons.overrides val apps = users.userProfiles.flatMap { user -> val serial = if (user == own) 0L else users.getSerialNumberForUser(user) runCatching { launcher.getActivityList(null, user) }.getOrDefault(emptyList()).mapNotNull { info -> val component = info.componentName if (component.packageName == context.packageName && user == own) return@mapNotNull null val label = info.label?.toString()?.trim().orEmpty().ifEmpty { component.packageName } - val icon = runCatching { info.getBadgedIcon(0).toBitmap(iconPx, iconPx) }.getOrNull() + val icon = runCatching { + (overrides[appKey(component.packageName, component.className, serial)] + ?.let { IconPack.drawable(context, it.pack, it.drawable, densityDpi) } + ?: pack?.icon(component, densityDpi) + ?: pack?.plated(info.getIcon(0), iconPx, densityDpi, appColors)) + ?.let { pm.getUserBadgedIcon(it, user) } + ?.toBitmap(iconPx, iconPx) + }.getOrNull() ?: runCatching { info.getBadgedIcon(0).toBitmap(iconPx, iconPx) }.getOrNull() val app = info.applicationInfo val updated = if (user == own) runCatching { pm.getPackageInfo(component.packageName, 0).lastUpdateTime }.getOrNull() else null @Suppress("DEPRECATION") @@ -243,6 +258,19 @@ object HomeApp { fun isActiveSteamSession(): Boolean = SessionState.running && SessionState.mode == SessionService.MODE_STEAM + fun showFrontEnd(context: Context, intent: Intent = Intent(context, FrontEndActivity::class.java)) { + val frontEnd = FrontEndActivity::class.java.name + val tasks = runCatching { context.getSystemService(android.app.ActivityManager::class.java)?.appTasks }.getOrNull().orEmpty() + val own = tasks.firstOrNull { task -> + runCatching { task.taskInfo.let { it.baseIntent.component?.className == frontEnd && it.topActivity?.className == frontEnd } } + .getOrDefault(false) + } + val launch = Intent(intent).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP) + if (own != null && runCatching { own.startActivity(context, launch, null) }.isSuccess) return + // The session task shares the front end's affinity, so without MULTIPLE_TASK the front end lands inside the session's PiP window. + context.startActivity(launch.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_MULTIPLE_TASK)) + } + fun openSystemHomeSettings(context: Context) { try { context.startActivity(settingsIntent()) diff --git a/app/src/main/java/com/droiddeck/launcher/HomeIcons.kt b/app/src/main/java/com/droiddeck/launcher/HomeIcons.kt new file mode 100644 index 0000000000..d3a57be2b4 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/HomeIcons.kt @@ -0,0 +1,46 @@ +package com.droiddeck.launcher + +import android.content.Context +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue + +object HomeIcons { + private const val PREFS = "home_launcher" + private const val KEY = "icon_overrides" + private const val SEPARATOR = '\t' + + data class Choice(val pack: String, val drawable: String) + + var overrides by mutableStateOf>(emptyMap()) + private set + @Volatile private var loaded = false + + @Synchronized + fun load(context: Context) { + if (loaded) return + overrides = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE) + .getStringSet(KEY, emptySet()).orEmpty().mapNotNull(::decode).toMap() + loaded = true + } + + fun set(context: Context, key: String, pack: String, drawable: String) = save(context, overrides + (key to Choice(pack, drawable))) + + fun clear(context: Context, key: String) = save(context, overrides - key) + + fun clearAll(context: Context) = save(context, emptyMap()) + + private fun save(context: Context, next: Map) { + overrides = next + context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit() + .putStringSet(KEY, next.map { (key, choice) -> encode(key, choice) }.toSet()).apply() + } + + internal fun encode(key: String, choice: Choice) = listOf(key, choice.pack, choice.drawable).joinToString(SEPARATOR.toString()) + + internal fun decode(entry: String): Pair? { + val parts = entry.split(SEPARATOR) + if (parts.size != 3 || parts.any { it.isEmpty() }) return null + return parts[0] to Choice(parts[1], parts[2]) + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/IconPack.kt b/app/src/main/java/com/droiddeck/launcher/IconPack.kt new file mode 100644 index 0000000000..227714277e --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/IconPack.kt @@ -0,0 +1,198 @@ +package com.droiddeck.launcher + +import android.content.ComponentName +import android.content.Context +import android.content.Intent +import android.content.pm.PackageManager +import android.content.res.Resources +import android.graphics.Bitmap +import android.graphics.Canvas +import android.graphics.Paint +import android.graphics.PorterDuff +import android.graphics.PorterDuffColorFilter +import android.graphics.PorterDuffXfermode +import android.graphics.Rect +import android.graphics.drawable.Drawable +import android.util.Xml +import androidx.core.content.res.ResourcesCompat +import androidx.core.graphics.createBitmap +import androidx.core.graphics.drawable.toBitmap +import androidx.core.graphics.drawable.toDrawable +import androidx.palette.graphics.Palette +import org.xmlpull.v1.XmlPullParser +import java.time.LocalDate +import kotlin.math.roundToInt + +object IconPack { + const val NONE = "" + private const val PREFS = "home_launcher" + private const val KEY = "icon_pack" + private const val APP_COLORS = "icon_pack_app_colors" + private const val FILTER = "appfilter" + private const val DRAWABLES = "drawable" + + private val ACTIONS = listOf("org.adw.launcher.THEMES", "com.novalauncher.THEME") + + data class Pack(val packageName: String, val label: String) + + internal data class Plate(val back: String?, val mask: String?, val upon: String?, val scale: Float) + + internal data class Filter(val icons: Map, val calendars: Map, val plate: Plate?) { + fun names(component: String, day: Int) = listOfNotNull(calendars[component]?.plus(day), icons[component]) + } + + class Loaded internal constructor( + private val resources: Resources, + internal val pack: String, + internal val updatedAt: Long, + private val filter: Filter, + ) { + fun icon(component: ComponentName, densityDpi: Int) = + filter.names(component.flattenToString(), LocalDate.now().dayOfMonth).firstNotNullOfOrNull { load(resources, pack, it, densityDpi) } + + val hasBack get() = filter.plate?.back != null + + fun plated(icon: Drawable, size: Int, densityDpi: Int, appColor: Boolean): Drawable? { + val plate = filter.plate ?: return null + fun image(name: String?) = name?.let { load(resources, pack, it, densityDpi) }?.toBitmap(size, size) + val base = icon.toBitmap(size, size) + val color = if (appColor) Palette.from(base).generate().getDominantColor(0).takeIf { it != 0 } else null + return compose(base, image(plate.back), image(plate.mask), image(plate.upon), plate.scale, color).toDrawable(resources) + } + } + + @Volatile private var cached: Loaded? = null + + fun selected(context: Context): String = + context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getString(KEY, NONE).orEmpty() + + fun select(context: Context, pack: String) { + context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putString(KEY, pack).apply() + } + + fun appColors(context: Context): Boolean = + context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getBoolean(APP_COLORS, false) + + fun setAppColors(context: Context, on: Boolean) { + context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putBoolean(APP_COLORS, on).apply() + } + + fun installed(context: Context): List { + val pm = context.packageManager + return ACTIONS.flatMap { pm.queryIntentActivities(Intent(it), 0) } + .map { it.activityInfo.applicationInfo } + .distinctBy { it.packageName } + .filter { app -> resources(pm, app.packageName)?.let { withXml(it, app.packageName, FILTER) { true } } == true } + .map { app -> Pack(app.packageName, app.loadLabel(pm).toString().trim().ifEmpty { app.packageName }) } + .sortedWith(compareBy(String.CASE_INSENSITIVE_ORDER) { it.label }) + } + + fun active(context: Context): Loaded? { + val pack = selected(context) + if (pack == NONE) return null + val pm = context.packageManager + val updatedAt = runCatching { pm.getPackageInfo(pack, 0).lastUpdateTime }.getOrNull() ?: return null + cached?.takeIf { it.pack == pack && it.updatedAt == updatedAt }?.let { return it } + val resources = resources(pm, pack) ?: return null + val filter = withXml(resources, pack, FILTER) { parse(it) } ?: return null + return Loaded(resources, pack, updatedAt, filter).also { cached = it } + } + + fun drawable(context: Context, pack: String, name: String, densityDpi: Int): Drawable? { + val resources = resources(context.packageManager, pack) ?: return null + return load(resources, pack, name, densityDpi) + } + + fun names(context: Context, pack: String): List { + val resources = resources(context.packageManager, pack) ?: return emptyList() + return withXml(resources, pack, DRAWABLES) { parseNames(it) }?.takeIf { it.isNotEmpty() } + ?: withXml(resources, pack, FILTER) { parse(it).icons.values.distinct().sorted() }.orEmpty() + } + + private fun resources(pm: PackageManager, pack: String): Resources? = + runCatching { pm.getResourcesForApplication(pack) }.getOrNull() + + private fun load(resources: Resources, pack: String, name: String, densityDpi: Int): Drawable? { + val id = resources.getIdentifier(name, "drawable", pack).takeIf { it != 0 } + ?: resources.getIdentifier(name, "mipmap", pack).takeIf { it != 0 } + ?: return null + return runCatching { ResourcesCompat.getDrawableForDensity(resources, id, densityDpi, null) }.getOrNull() + } + + internal fun parseNames(xml: XmlPullParser): List { + val names = LinkedHashSet() + forEachTag(xml) { if (xml.name == "item") xml.getAttributeValue(null, "drawable")?.trim()?.takeIf { it.isNotEmpty() }?.let { names.add(it) } } + return names.toList() + } + + internal fun parse(xml: XmlPullParser): Filter { + val icons = HashMap() + val calendars = HashMap() + var back: String? = null + var mask: String? = null + var upon: String? = null + var scale = 1f + fun image() = xml.getAttributeValue(null, "img1")?.trim()?.takeIf { it.isNotEmpty() } + forEachTag(xml) { + when (xml.name) { + "item" -> { + val key = componentKey(xml.getAttributeValue(null, "component")) + val drawable = xml.getAttributeValue(null, "drawable")?.trim() + if (key != null && !drawable.isNullOrEmpty()) icons.putIfAbsent(key, drawable) + } + "calendar" -> { + val key = componentKey(xml.getAttributeValue(null, "component")) + val prefix = xml.getAttributeValue(null, "prefix")?.trim() + if (key != null && !prefix.isNullOrEmpty()) calendars.putIfAbsent(key, prefix) + } + "iconback" -> back = back ?: image() + "iconmask" -> mask = mask ?: image() + "iconupon" -> upon = upon ?: image() + "scale" -> scale = xml.getAttributeValue(null, "factor")?.toFloatOrNull() ?: scale + } + } + return Filter(icons, calendars, if (back == null && mask == null && upon == null) null else Plate(back, mask, upon, scale)) + } + + internal fun compose(icon: Bitmap, back: Bitmap?, mask: Bitmap?, upon: Bitmap?, scale: Float, backColor: Int? = null): Bitmap { + val size = icon.width + val inset = (size * (1 - scale) / 2).roundToInt() + val result = createBitmap(size, size) + val canvas = Canvas(result) + val paint = Paint(Paint.ANTI_ALIAS_FLAG or Paint.FILTER_BITMAP_FLAG) + val full = Rect(0, 0, size, size) + canvas.drawBitmap(icon, null, Rect(inset, inset, size - inset, size - inset), paint) + mask?.let { + paint.xfermode = PorterDuffXfermode(PorterDuff.Mode.DST_OUT) + canvas.drawBitmap(it, null, full, paint) + } + back?.let { + paint.xfermode = PorterDuffXfermode(PorterDuff.Mode.DST_OVER) + paint.colorFilter = backColor?.let { color -> PorterDuffColorFilter(color, PorterDuff.Mode.SRC_IN) } + canvas.drawBitmap(it, null, full, paint) + } + paint.xfermode = null + paint.colorFilter = null + upon?.let { canvas.drawBitmap(it, null, full, paint) } + return result + } + + private inline fun forEachTag(xml: XmlPullParser, block: () -> Unit) { + var event = xml.eventType + while (event != XmlPullParser.END_DOCUMENT) { + if (event == XmlPullParser.START_TAG) block() + event = xml.next() + } + } + + internal fun componentKey(component: String?): String? = + component?.trim()?.removePrefix("ComponentInfo{")?.removeSuffix("}")?.let(ComponentName::unflattenFromString)?.flattenToString() + + private fun withXml(resources: Resources, pack: String, file: String, block: (XmlPullParser) -> T): T? = runCatching { + val xml = resources.getIdentifier(file, "xml", pack) + val raw = resources.getIdentifier(file, "raw", pack) + if (xml != 0) resources.getXml(xml).use(block) + else (if (raw != 0) resources.openRawResource(raw) else resources.assets.open("$file.xml")) + .use { stream -> block(Xml.newPullParser().also { it.setInput(stream, null) }) } + }.getOrNull() +} diff --git a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt index 5f39d03c6c..5e7a39b639 100644 --- a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt @@ -151,7 +151,7 @@ import com.droiddeck.launcher.ui.sessionDrawerPages import com.droiddeck.launcher.ui.step import kotlin.math.abs -class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { +class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droiddeck.launcher.ui.AgentPetHost { override fun attachBaseContext(newBase: android.content.Context) { super.attachBaseContext(newBase) com.droiddeck.launcher.core.AppLanguage.applyTo(this, newBase) @@ -159,6 +159,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { private lateinit var pip: com.droiddeck.launcher.session.SessionPipController private var pipUi by mutableStateOf(false) + + override val petBlocked: Boolean get() = drawerOpenState || pipUi || pcKeyboardOpen private var pipAutoEnter by mutableStateOf(false) private var unfoldedControls by mutableStateOf(false) private var unfoldedControlsWithController by mutableStateOf(false) @@ -452,6 +454,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { private var drawerDefaultProton by mutableStateOf(null) private val drawerComponentMenu by lazy { ComponentsMenu(this, uiHandler) } private var drawerGameProfileId by mutableStateOf(null) + private var drawerGameProfileSelectionMade = false private var fpsLimit by mutableStateOf(SessionState.fpsLimit) private fun noSteamSession(): Boolean = (SessionState.mode == SessionService.MODE_RUN && @@ -460,7 +463,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { com.droiddeck.launcher.session.NoSteamLaunch.BATTLENET, )) || SessionState.mode == SessionService.MODE_DESKTOP private val drawerGameInventory = GameProfileInventoryCache() - private var drawerGameInventoryRevision = 0L + @Volatile private var drawerGameInventoryRevision = 0L private var drawerGameFexPresetSaving by mutableStateOf(false) private var drawerGameNoSteamSaving by mutableStateOf(false) private val drawerGameProfileFollowState = GameProfileFollowState() @@ -556,8 +559,25 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { if (r.resultCode == RESULT_OK) InAppFilePicker.pickedFile(r.data)?.let { importLossless(it) } } private var frameGen by mutableStateOf(FrameGen.Mode.OFF) + private var frameGenActiveGameId by mutableStateOf(null) + private var frameGenActiveGameName by mutableStateOf(null) + private var frameGenHasGameOverride by mutableStateOf(false) private var frameGenPip = false private val frameGenRequests = java.util.concurrent.atomic.AtomicInteger() + private val frameGenActivityGeneration = synchronized(frameGenGlobalLock) { + frameGenGlobalGeneration.incrementAndGet() + } + @Volatile private var frameGenActivityActive = true + private val frameGenForcePending = java.util.concurrent.atomic.AtomicBoolean() + @Volatile private var frameGenInventoryIds: Set? = null + @Volatile private var frameGenInventoryRevision = -1L + private val frameGenInventoryLock = Any() + @Volatile private var frameGenInventoryLastAttemptAt = 0L + private val frameGenInventoryRetryScheduled = java.util.concurrent.atomic.AtomicBoolean() + private val frameGenInventoryRefreshScheduled = java.util.concurrent.atomic.AtomicBoolean() + + @Volatile private var appliedFrameGenMode: FrameGen.Mode? = null + @Volatile private var appliedFrameGenHz: Float? = null private var fexPreset by mutableStateOf("") private var suspendPolicy by mutableStateOf(SessionPrefs.SUSPEND_MANUAL) private var steamDownloadsInBackground by mutableStateOf(false) @@ -859,7 +879,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { hud.attach(root, root.childCount) memoryHud = com.droiddeck.launcher.session.MemoryHud(this) hud.onPresentingWindowChanged = { - if (FrameGen.engine(this) != FrameGen.ENGINE_OFF) CompositorHost.rearmFrameGen { applyFrameGen() } + CompositorHost.rearmFrameGen { applyFrameGen(force = true) } } if (SessionState.running && SessionState.firstFrameSeen) { loading.visible = false @@ -892,8 +912,24 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { } } glassesScope.launch { com.droiddeck.launcher.handtracking.HandTracking.settings.collect { updateHandCamera() } } glassesScope.launch { + var lastRunGameId: String? = null while (true) { updateTrackingRecovery() + if (SessionState.mode == SessionService.MODE_RUN) { + val gameId = SessionState.gameId + ?.takeIf { it.toLongOrNull() != null } + ?: intent.getStringExtra(SessionService.EXTRA_GAME_ID) + ?.takeIf { it.toLongOrNull() != null } + if (gameId != lastRunGameId) { + lastRunGameId = gameId + if (drawerGameProfileFollowState.followsSteam) { + loadFrameGenFor(gameId?.toLongOrNull()) + } + applyFrameGen() + } + } else { + lastRunGameId = null + } kotlinx.coroutines.delay(100) } } @@ -956,7 +992,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { applyOutputPacing() if (pipUi != frameGenPip) { frameGenPip = pipUi - if (FrameGen.engine(this@SessionActivity) != FrameGen.ENGINE_OFF && ::surfaceView.isInitialized) applyFrameGen() + if (::surfaceView.isInitialized) applyFrameGen() } } androidx.compose.runtime.LaunchedEffect(AgentGuest.steamKeyboard) { updateOnScreenControls() } @@ -1032,7 +1068,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { window.setBackgroundDrawable(android.graphics.drawable.ColorDrawable(android.graphics.Color.BLACK)) }, ) - LaunchedEffect(AgentGuest.focusRevision, secondScreenDisplays.isNotEmpty()) { + LaunchedEffect(AgentGuest.focusRevision, secondScreenDisplays.isNotEmpty(), drawerGameInventoryRevision) { val nextGame = kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) { if (SessionState.mode == SessionService.MODE_RUN) SessionState.program?.let { "program:$it" } else { @@ -1045,11 +1081,40 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { } } } + if (SessionState.mode == SessionService.MODE_STEAM) { + val target = kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) { + val games = LibraryCache.load(this@SessionActivity) + val cachedIds = games.mapNotNull { it.profileKey.toLongOrNull() }.toSet() + val inventoryIds = synchronized(frameGenInventoryLock) { + frameGenInventoryIds + }.orEmpty() + val id = AgentGuest.activeSteamAppId( + this@SessionActivity, cachedIds + inventoryIds + ) + val name = id?.let { activeId -> + games.firstOrNull { it.profileKey == activeId.toString() }?.name + } + id to name + } + if (target.first != frameGenActiveGameId) { + frameGenActiveGameId = target.first + if (drawerGameProfileFollowState.followsSteam) { + loadFrameGenFor(target.first) + } + } + frameGenActiveGameName = target.second + } if (nextGame != gestureGame) { if (nextGame != null) gameStarts++ gestureGame = nextGame refreshGestureConfig() } + if ( + SessionState.mode == SessionService.MODE_STEAM && + CompositorHost.isStarted + ) { + applyFrameGen() + } if (secondScreenDisplays.isNotEmpty()) kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) { runCatching { com.droiddeck.launcher.session.TelemetryOutput.applyAutomatic(this@SessionActivity, nextGame) } } @@ -1234,6 +1299,18 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { textureAnisotropy = if (drawerGameProfileId == null) textureAnisotropy else drawerTextureAnisotropy, textureLodBias = if (drawerGameProfileId == null) textureLodBias else drawerTextureLodBias, frameGen = frameGen, + frameGenTargetGameId = frameGenTargetGameId()?.toString(), + frameGenTargetGameName = when { + !drawerGameProfileFollowState.followsSteam -> + drawerGameProfileRefresh.data?.profiles + ?.firstOrNull { it.first == frameGenTargetGameId() }?.second + SessionState.mode == SessionService.MODE_STEAM -> frameGenActiveGameName + SessionState.mode == SessionService.MODE_RUN -> + com.droiddeck.launcher.frontend.Library.nameForProgram(SessionState.program) + else -> drawerGameProfileRefresh.data?.profiles + ?.firstOrNull { it.first == frameGenTargetGameId() }?.second + }, + hasGameOverride = frameGenHasGameOverride, lossless = lossless, oscMode = oscMode, suspendPolicy = suspendPolicy, steamDownloadsInBackground = steamDownloadsInBackground, touchMode = touchMode, @@ -1293,9 +1370,22 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { applyOutputPacing() }, onFrameGenPick = { mode -> - FrameGen.set(this@SessionActivity, mode) + val appId = frameGenTargetGameId() + + if (appId == null) FrameGen.set(this@SessionActivity, mode) + else FrameGen.setForGame(this@SessionActivity, appId.toString(), mode) + loadFrameGenFor(appId) readPrefs() - applyFrameGen() + applyFrameGen(force = true) + }, + onFrameGenReset = { + val appId = frameGenTargetGameId() + + if (appId == null) FrameGen.clearGlobal(this@SessionActivity) + else FrameGen.clearGame(this@SessionActivity, appId.toString()) + loadFrameGenFor(appId) + readPrefs() + applyFrameGen(force = true) }, onImportLossless = { pickLossless.launch(InAppFilePicker.buildIntent( @@ -1628,9 +1718,35 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { }, "drawer-components").start() } + private fun frameGenTargetGameId(): Long? { + if (!drawerGameProfileFollowState.followsSteam) { + return drawerGameProfileId + } + if (SessionState.mode == SessionService.MODE_RUN) { + return ( + SessionState.gameId?.toLongOrNull() + ?: intent.getStringExtra(SessionService.EXTRA_GAME_ID)?.toLongOrNull() + ) + } + if (SessionState.mode == SessionService.MODE_STEAM) { + return frameGenActiveGameId + } + return drawerGameProfileId + } + + private fun loadFrameGenFor(appId: Long?) { + val profileId = appId?.toString() + frameGen = FrameGen.mode(this, profileId) + frameGenHasGameOverride = appId?.let { + FrameGen.hasGameOverride(this, it.toString()) + } == true + } + private fun selectDrawerGameProfile(appId: Long?) { drawerGameProfileFollowState.selectManually() + drawerGameProfileSelectionMade = true drawerGameProfileId = appId + loadFrameGenFor(frameGenTargetGameId()) drawerGameProfileRefresh = drawerGameProfileRefresh.retrying() readDrawerTextureFiltering(appId) refreshDrawerGameProfile() @@ -1703,6 +1819,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { if (refresh.followsSteam) { if (drawerGameProfileFollowState.followsSteam) { drawerGameProfileId = result.selectedAppId + loadFrameGenFor(result.selectedAppId) readDrawerTextureFiltering(result.selectedAppId) } } @@ -1727,6 +1844,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { gameProtonId = ProtonDefault.gameSelectedId(this, game.profileKey, protons), gameComponents = ComponentsManager.gameComponents(this, game.profileKey), gameWindowsComponents = WinComponents.picks(this, game.profileKey), + frameGenMode = FrameGen.mode(this, game.profileKey), + frameGenInherited = !FrameGen.hasGameOverride(this, game.profileKey), ) } @@ -1970,7 +2089,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { if (routedTouchMode != nextRoutedTouchMode) gestureTouchStreamGate.reset() routedTouchMode = nextRoutedTouchMode requestRelativeMouse() - frameGen = FrameGen.mode(this) + loadFrameGenFor(frameGenTargetGameId()) fexPreset = SessionPrefs.fexPreset(this) suspendPolicy = SessionPrefs.suspendPolicy(this, SessionState.mode) steamDownloadsInBackground = SessionPrefs.steamDownloadsInBackground(this) @@ -2257,7 +2376,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { if (resized) { cancelTouchGestures() Log.i(TAG, "surface resized to ${width}x$height - rebinding the compositor") - CompositorHost.resize(holder.surface) { applyFrameGen() } + CompositorHost.resize(holder.surface) { applyFrameGen(force = true) } resizeOutputForWindow(width, height) } } @@ -2398,17 +2517,161 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { } } - private fun applyFrameGen() { + private fun frameGenModeForActiveGame(request: Int): FrameGen.Mode { + if (SessionState.mode == SessionService.MODE_RUN) { + val activeAppId = ( + SessionState.gameId?.takeIf { it.toLongOrNull() != null } + ?: intent.getStringExtra(SessionService.EXTRA_GAME_ID) + )?.toLongOrNull() + return FrameGen.mode(this, activeAppId?.toString()) + } + + val cachedIds = LibraryCache.load(this) + .mapNotNull { it.profileKey.toLongOrNull() } + .toSet() + + var inventoryRevision = drawerGameInventoryRevision + var ids = synchronized(frameGenInventoryLock) { + if (frameGenInventoryRevision != inventoryRevision) { + frameGenInventoryIds = null + frameGenInventoryRevision = inventoryRevision + frameGenInventoryLastAttemptAt = 0L + } + frameGenInventoryIds + } + if (ids == null) { + val now = SystemClock.elapsedRealtime() + val shouldScan = synchronized(frameGenInventoryLock) { + val currentRevision = drawerGameInventoryRevision + if (frameGenInventoryRevision != currentRevision) { + frameGenInventoryIds = null + frameGenInventoryRevision = currentRevision + frameGenInventoryLastAttemptAt = 0L + } + inventoryRevision = currentRevision + if (frameGenInventoryIds != null) { + false + } else if ( + frameGenInventoryLastAttemptAt != 0L && + now - frameGenInventoryLastAttemptAt < 15_000L + ) { + false + } else { + frameGenInventoryLastAttemptAt = now + true + } + } + + if (shouldScan) { + val currentIds = runCatching { + Library.launchableGames(this, strictRead = true) + .mapNotNull { it.profileKey.toLongOrNull() } + .toSet() + }.getOrNull() + + if (currentIds == null) { + if (frameGenInventoryRetryScheduled.compareAndSet(false, true)) { + uiHandler.postDelayed({ + frameGenInventoryRetryScheduled.set(false) + val retry = synchronized(frameGenInventoryLock) { + frameGenInventoryIds == null + } + if (retry && !isFinishing && !isDestroyed) { + applyFrameGen() + } + }, 15_000L) + } + } else { + var published = false + synchronized(frameGenInventoryLock) { + if (drawerGameInventoryRevision == inventoryRevision && + frameGenInventoryRevision == inventoryRevision + ) { + ids = cachedIds + currentIds + frameGenInventoryIds = ids + published = true + } + } + if (published) { + if (frameGenInventoryRefreshScheduled.compareAndSet(false, true)) { + uiHandler.postDelayed({ + frameGenInventoryRefreshScheduled.set(false) + if (frameGenActivityActive && !isFinishing && !isDestroyed) { + synchronized(frameGenInventoryLock) { + frameGenInventoryIds = null + frameGenInventoryLastAttemptAt = 0L + } + applyFrameGen() + } + }, 15_000L) + } + if (frameGenRequests.get() != request) { + applyFrameGen() + } + } + } + } + + if (ids == null) { + ids = synchronized(frameGenInventoryLock) { + frameGenInventoryIds + } ?: emptySet() + } + } + + val activeAppId = AgentGuest.activeSteamAppId( + this, cachedIds + (ids ?: emptySet()) + ) + if (activeAppId == null) return FrameGen.Mode.OFF + return FrameGen.mode(this, activeAppId.toString()) + } + + private fun applyFrameGen(force: Boolean = false) { + val request = synchronized(frameGenGlobalLock) { + if (force) frameGenForcePending.set(true) + frameGenRequests.incrementAndGet() + } val hz = refreshHz() val pip = pipUi && mirrorRefreshLimit() <= 0 - val request = frameGenRequests.incrementAndGet() Thread({ - val problem = synchronized(frameGenRequests) { + val mode = if (pip) FrameGen.Mode.OFF else frameGenModeForActiveGame(request) + val needsApply = synchronized(frameGenGlobalLock) { + if (frameGenActivityGeneration != frameGenGlobalGeneration.get()) return@Thread if (request != frameGenRequests.get()) return@Thread - if (pip) FrameGen.apply(this, FrameGen.Mode.OFF, hz) else FrameGen.apply(this, hz) + if (!frameGenActivityActive || isFinishing || isDestroyed) return@Thread + val lastAppliedHz = appliedFrameGenHz + frameGenForcePending.get() || appliedFrameGenMode == null || + mode != appliedFrameGenMode || lastAppliedHz == null || + kotlin.math.abs(lastAppliedHz - hz) > 0.1f + } + val prepared = if (needsApply) FrameGen.prepareApply(this, mode) else null + val problem = synchronized(frameGenGlobalLock) { + if (frameGenActivityGeneration != frameGenGlobalGeneration.get()) return@Thread + if (request != frameGenRequests.get()) return@Thread + if (!frameGenActivityActive || isFinishing || isDestroyed) return@Thread + val forcePending = frameGenForcePending.get() + val lastAppliedHz = appliedFrameGenHz + if (!forcePending && appliedFrameGenMode != null && mode == appliedFrameGenMode && + lastAppliedHz != null && kotlin.math.abs(lastAppliedHz - hz) <= 0.1f + ) { + null + } else { + val ready = prepared ?: return@Thread + frameGenForcePending.set(false) + FrameGen.applyPrepared(this, ready, hz).also { problem -> + if (problem == null) { + appliedFrameGenMode = mode + appliedFrameGenHz = hz + } else { + appliedFrameGenMode = null + appliedFrameGenHz = null + } + } + } } val state = Lossless.state(this) runOnUiThread { + if (frameGenActivityGeneration != frameGenGlobalGeneration.get()) return@runOnUiThread lossless = state if (problem != null) Toast.makeText(this, problem, Toast.LENGTH_LONG).show() } @@ -2425,12 +2688,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { private fun importLossless(dll: File) { Thread({ - val message = Lossless.message(this, Lossless.import(this, dll)) + val result = Lossless.import(this, dll) + val message = Lossless.message(this, result) val state = Lossless.state(this) runOnUiThread { lossless = state Toast.makeText(this, message, Toast.LENGTH_LONG).show() - if (FrameGen.engine(this) == FrameGen.ENGINE_LSFG) applyFrameGen() + applyFrameGen(force = result == Lossless.ImportResult.UPDATED) } }, "lossless-import").start() } @@ -2637,6 +2901,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { override fun dispatchKeyEvent(event: KeyEvent): Boolean { + if (com.droiddeck.launcher.ui.AgentPet.handleBack(this, event)) return true when (event.keyCode) { KeyEvent.KEYCODE_VOLUME_UP, KeyEvent.KEYCODE_VOLUME_DOWN, KeyEvent.KEYCODE_VOLUME_MUTE -> { val steamVolume = @@ -4708,12 +4973,14 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { override fun onResume() { super.onResume() + drawerGameInventoryRevision++ com.droiddeck.launcher.input.SystemKeyCapture.attach(this, { hasWindowFocus() && !appUiOwnsPointer() && CompositorHost.isStarted }) { event -> com.droiddeck.launcher.input.GuestKeys.send(event) { code, down -> sendGuestKey(code, down, 8) } } if (refreshActivityDisplayId() && started) { SessionService.setActivityDisplay(this, sessionActivityDisplayId) } + if (CompositorHost.isStarted) applyFrameGen(force = true) applyFollowOrientation(resources.configuration) if (runtimeRemovalBlocked) return if (!SessionState.suspended) pausedFrame = null @@ -5391,6 +5658,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { } override fun onDestroy() { + synchronized(frameGenGlobalLock) { + frameGenActivityActive = false + frameGenRequests.incrementAndGet() + } if (AgentGuest.readyListener === agentReadyListener) AgentGuest.readyListener = null com.droiddeck.launcher.input.HomeButtonShortcuts.detach(this) relativeMouseRequests.shutdownNow() @@ -5505,6 +5776,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { private const val BOTTOM_RECOVERY_MS = 1_000L private const val BOTTOM_RECOVERY_TRIES = 3 private const val TAG = "SessionActivity" + private val frameGenGlobalLock = Any() + private val frameGenGlobalGeneration = java.util.concurrent.atomic.AtomicLong(0L) private var startedScreens = 0 @Volatile private var activeInstallWorker: Any? = null private const val FEX_MISSING = "droiddeck-fex: x86 Linux programs need" diff --git a/app/src/main/java/com/droiddeck/launcher/agent/AgentAccess.kt b/app/src/main/java/com/droiddeck/launcher/agent/AgentAccess.kt index b755ca6466..2113161467 100644 --- a/app/src/main/java/com/droiddeck/launcher/agent/AgentAccess.kt +++ b/app/src/main/java/com/droiddeck/launcher/agent/AgentAccess.kt @@ -23,7 +23,7 @@ object AgentAccess { fun requireCommands(context: Context) { if (!commandsAllowed(context)) throw AgentException( "AGENT_COMMANDS_DISABLED", - "Debugging tools are off: turn on Setup > Diagnostics > Debugging tools on the device", + "Debugging tools are off: turn on Setup > Developer > Debugging tools on the device", ) } diff --git a/app/src/main/java/com/droiddeck/launcher/agent/AgentChats.kt b/app/src/main/java/com/droiddeck/launcher/agent/AgentChats.kt index e228f1aa5d..aedd840dd0 100644 --- a/app/src/main/java/com/droiddeck/launcher/agent/AgentChats.kt +++ b/app/src/main/java/com/droiddeck/launcher/agent/AgentChats.kt @@ -74,7 +74,11 @@ object AgentChats { is Entry.Used -> JSONObject().put("used", entry.tool).put("detail", entry.detail).put("id", entry.id).put("input", entry.input) .apply { entry.output?.let { put("output", it).put("failed", entry.failed) } } is Entry.Finished -> JSONObject().put("finished", true).put("error", entry.error ?: JSONObject.NULL).put("stopped", entry.stopped).apply { - entry.usage?.let { put("ms", it.durationMs).put("cost", it.costUsd).put("in", it.inputTokens).put("out", it.outputTokens) } + if (entry.planned) put("planned", true) + entry.usage?.let { + put("ms", it.durationMs).put("cost", it.costUsd).put("in", it.inputTokens).put("out", it.outputTokens) + if (it.context > 0) put("ctx", it.context).put("win", it.window) + } } }.toString() @@ -105,7 +109,8 @@ object AgentChats { o.has("result") -> Entry.Result(o.getString("result"), o.optString("output"), o.optBoolean("failed")) o.has("finished") -> Entry.Finished( if (o.isNull("error")) null else o.optString("error"), o.optBoolean("stopped"), - if (o.has("ms")) AgentHost.Usage(o.optLong("ms"), o.optDouble("cost", 0.0), o.optLong("in"), o.optLong("out")) else null, + if (o.has("ms")) AgentHost.Usage(o.optLong("ms"), o.optDouble("cost", 0.0), o.optLong("in"), o.optLong("out"), o.optLong("ctx"), o.optLong("win")) else null, + o.optBoolean("planned"), ) else -> null } diff --git a/app/src/main/java/com/droiddeck/launcher/agent/AgentHarness.kt b/app/src/main/java/com/droiddeck/launcher/agent/AgentHarness.kt index de45d4b51a..6709399b01 100644 --- a/app/src/main/java/com/droiddeck/launcher/agent/AgentHarness.kt +++ b/app/src/main/java/com/droiddeck/launcher/agent/AgentHarness.kt @@ -21,16 +21,22 @@ interface AgentHarness { val signIn: List /** Whether [Options.plan] means anything to this CLI. */ val plans: Boolean + /** Reasoning effort levels the CLI accepts, lowest first; empty when it has none. */ + val efforts: List /** Models to offer besides the CLI's default; [rootfs] is where the CLI's own files can be read. */ fun models(rootfs: File): List /** The guest command for one turn; [conversation] is null for the first one. */ fun turn(message: String, conversation: String?, options: Options): List /** One line of the CLI's output, or null when it carries nothing to show. */ fun parse(line: String): AgentEvent? + /** Sets the CLI's own defaults in the userland before it runs; [rootfs] is the userland's root. */ + fun prepare(rootfs: File) {} + /** Context and plan limits the CLI keeps on disk rather than printing, read once a turn of [conversation] is done. */ + fun usage(rootfs: File, conversation: String?): AgentEvent? = null data class Model(val id: String, val label: String) - data class Options(val model: String? = null, val plan: Boolean = false, val brief: String? = null) + data class Options(val model: String? = null, val plan: Boolean = false, val brief: String? = null, val effort: String? = null) companion object { val all: List = listOf(ClaudeCode, Codex) @@ -46,6 +52,9 @@ data class AgentEvent( val thinking: String? = null, /** Tokens the conversation's context holds after this step. */ val context: Long? = null, + /** Tokens the model's context can hold. */ + val window: Long? = null, + val limits: List? = null, val usage: AgentHost.Usage? = null, ) @@ -58,6 +67,29 @@ object ClaudeCode : AgentHarness { override val signedIn = listOf("sh", "-c", "$binary auth status | grep -q '\"loggedIn\": true'") override val signIn = listOf(binary, "auth", "login", "--claudeai") override val plans = true + override val efforts = listOf("low", "medium", "high", "xhigh", "max") + + /** + * Commits and pull requests the agent makes carry no Claude Code credit or co-author line by + * default. Only keys the user has not set are written, so their own choice stays. + */ + override fun prepare(rootfs: File) { + val file = File(rootfs, "root/.claude/settings.json") + val settings = if (file.exists()) runCatching { JSONObject(file.readText()) }.getOrNull() ?: return else JSONObject() + var changed = false + if (!settings.has("includeCoAuthoredBy")) { + settings.put("includeCoAuthoredBy", false) + changed = true + } + if (!settings.has("attribution")) { + settings.put("attribution", JSONObject().put("commit", "").put("pr", "")) + changed = true + } + if (changed) runCatching { + file.parentFile?.mkdirs() + file.writeText(settings.toString(2) + "\n") + } + } override fun models(rootfs: File) = listOf( AgentHarness.Model("opus", "Opus"), AgentHarness.Model("sonnet", "Sonnet"), AgentHarness.Model("haiku", "Haiku"), @@ -68,6 +100,7 @@ object ClaudeCode : AgentHarness { addAll(listOf(binary, "-p", message, "--output-format", "stream-json", "--verbose", "--include-partial-messages")) addAll(listOf("--permission-mode", if (options.plan) "plan" else "bypassPermissions")) options.model?.let { addAll(listOf("--model", it)) } + options.effort?.let { addAll(listOf("--effort", it)) } options.brief?.let { addAll(listOf("--append-system-prompt", it)) } if (conversation != null) addAll(listOf("--resume", conversation)) } @@ -111,10 +144,12 @@ object ClaudeCode : AgentHarness { } AgentEvent(conversation, results) } + "rate_limit_event" -> AgentEvent(conversation, limits = limits(o.optJSONObject("rate_limit_info"))) // A resumed session first answers background tasks the last run left behind; that result is not the turn's. "result" -> if (o.optJSONObject("origin")?.optString("kind") == "task-notification") conversation?.let { AgentEvent(it) } else AgentEvent( conversation, listOf(AgentHost.Entry.Finished(if (o.optBoolean("is_error")) o.optString("result").ifEmpty { o.optString("subtype") } else null)), + window = window(o.optJSONObject("modelUsage")), usage = AgentHost.Usage( o.optLong("duration_ms"), o.optDouble("total_cost_usd", 0.0), o.optJSONObject("usage")?.let { it.optLong("input_tokens") + it.optLong("cache_read_input_tokens") + it.optLong("cache_creation_input_tokens") } ?: 0, @@ -125,6 +160,24 @@ object ClaudeCode : AgentHarness { } } + private val WINDOW_MINUTES = mapOf("five_hour" to 300, "seven_day" to 10_080) + + @VisibleForTesting + internal fun limits(info: JSONObject?): List? { + val windows = info?.optJSONObject("unifiedWindows") ?: return null + return WINDOW_MINUTES.mapNotNull { (key, minutes) -> + val w = windows.optJSONObject(key) ?: return@mapNotNull null + AgentHost.Limit(minutes, (w.optDouble("utilization", 0.0) * 100).toInt(), w.optLong("resetsAt")) + }.takeIf { it.isNotEmpty() } + } + + /** The context window of the model that did most of the turn; subagents may run a smaller one. */ + private fun window(models: JSONObject?): Long? { + models ?: return null + return models.keys().asSequence().mapNotNull { models.optJSONObject(it) } + .maxByOrNull { it.optDouble("costUSD", 0.0) }?.optLong("contextWindow")?.takeIf { it > 0 } + } + private fun resultText(content: Any?): String = when (content) { is String -> content is JSONArray -> (0 until content.length()).mapNotNull { i -> @@ -152,8 +205,8 @@ object ClaudeCode : AgentHarness { input ?: return "" return when { tool == "Bash" -> input.optString("command") - tool == "Edit" -> "${input.optString("file_path")}\n\n- ${input.optString("old_string").replace("\n", "\n- ")}\n\n+ ${input.optString("new_string").replace("\n", "\n+ ")}" - tool == "Write" -> "${input.optString("file_path")}\n\n${input.optString("content")}" + tool == "Edit" -> input.optString("file_path") + "\n" + lineDiff(input.optString("old_string"), input.optString("new_string")) + tool == "Write" -> input.optString("file_path") + "\n" + lineDiff("", input.optString("content")) tool == "TodoWrite" -> todos(input.optJSONArray("todos")) else -> input.toString(2) } @@ -188,6 +241,7 @@ object Codex : AgentHarness { override val signedIn = listOf(binary, "login", "status") override val signIn = listOf(binary, "login") override val plans = false + override val efforts = listOf("low", "medium", "high") /** Codex keeps the models its account can use in `~/.codex/models_cache.json` once it has run. */ override fun models(rootfs: File): List = runCatching { @@ -207,6 +261,7 @@ object Codex : AgentHarness { if (conversation != null) addAll(listOf("resume", conversation)) addAll(listOf("--json", "--dangerously-bypass-approvals-and-sandbox", "--skip-git-repo-check")) options.model?.let { addAll(listOf("-m", it)) } + options.effort?.let { addAll(listOf("-c", "model_reasoning_effort=\"$it\"")) } // codex exec has no system prompt option, so a new conversation starts with the brief. add(if (conversation == null && options.brief != null) "${options.brief}\n\n$message" else message) } @@ -257,6 +312,33 @@ object Codex : AgentHarness { return if (entries.isEmpty()) null else AgentEvent(entries = entries) } + private const val TOKEN_COUNT = "\"payload\":{\"type\":\"token_count\"" + + /** Codex prints no limits with --json; its session log, named after the thread, has a token_count event each step. */ + override fun usage(rootfs: File, conversation: String?): AgentEvent? { + conversation ?: return null + val log = File(rootfs, "root/.codex/sessions").walkBottomUp().filter { it.isFile && it.name.endsWith("-$conversation.jsonl") } + .maxByOrNull { it.lastModified() } ?: return null + val last = runCatching { log.readLines().lastOrNull { it.contains(TOKEN_COUNT) } }.getOrNull() ?: return null + return tokenCount(last) + } + + @VisibleForTesting + internal fun tokenCount(line: String): AgentEvent? { + val payload = runCatching { JSONObject(line).optJSONObject("payload") }.getOrNull()?.takeIf { it.optString("type") == "token_count" } ?: return null + val info = payload.optJSONObject("info") + val rates = payload.optJSONObject("rate_limits") + val limits = listOf("primary", "secondary").mapNotNull { key -> + val w = rates?.optJSONObject(key) ?: return@mapNotNull null + AgentHost.Limit(w.optInt("window_minutes"), w.optDouble("used_percent", 0.0).toInt(), w.optLong("resets_at")) + } + return AgentEvent( + context = info?.optJSONObject("last_token_usage")?.optLong("total_tokens")?.takeIf { it > 0 }, + window = info?.optLong("model_context_window")?.takeIf { it > 0 }, + limits = limits.takeIf { it.isNotEmpty() }, + ) + } + private fun todoEntry(id: String, item: JSONObject): AgentHost.Entry.Used { val items = item.optJSONArray("items") ?: JSONArray() val text = (0 until items.length()).mapNotNull { i -> @@ -275,6 +357,28 @@ object Codex : AgentHarness { @VisibleForTesting internal fun firstLine(text: String) = text.lineSequence().first().take(160) +private const val DIFF_CONTEXT = 2 + +/** + * [old] against [new], one line per changed or nearby line, each led by ' ', '-' or '+'. Edits + * replace a short span, so the lines both share at the start and end are cut to [DIFF_CONTEXT]. + */ +@VisibleForTesting +internal fun lineDiff(old: String, new: String): String { + val a = if (old.isEmpty()) emptyList() else old.removeSuffix("\n").lines() + val b = if (new.isEmpty()) emptyList() else new.removeSuffix("\n").lines() + var head = 0 + while (head < a.size && head < b.size && a[head] == b[head]) head++ + var tail = 0 + while (tail < a.size - head && tail < b.size - head && a[a.size - 1 - tail] == b[b.size - 1 - tail]) tail++ + return buildList { + a.subList(maxOf(0, head - DIFF_CONTEXT), head).forEach { add(" $it") } + a.subList(head, a.size - tail).forEach { add("-$it") } + b.subList(head, b.size - tail).forEach { add("+$it") } + a.subList(a.size - tail, minOf(a.size, a.size - tail + DIFF_CONTEXT)).forEach { add(" $it") } + }.joinToString("\n") +} + private val SHELL_WRAPPER = Regex("^/bin/(?:ba)?sh -l?c '(.*)'$", RegexOption.DOT_MATCHES_ALL) /** Codex runs each command as `/bin/bash -lc ''`; the command is what the user wants to read. */ diff --git a/app/src/main/java/com/droiddeck/launcher/agent/AgentHost.kt b/app/src/main/java/com/droiddeck/launcher/agent/AgentHost.kt index bbb99b744d..1f78672f4a 100644 --- a/app/src/main/java/com/droiddeck/launcher/agent/AgentHost.kt +++ b/app/src/main/java/com/droiddeck/launcher/agent/AgentHost.kt @@ -14,6 +14,7 @@ import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import com.droiddeck.launcher.R import com.droiddeck.launcher.runtime.LinuxRuntime +import com.droiddeck.launcher.session.OrphanReaper import com.droiddeck.launcher.session.SessionPrefs import java.io.File import java.nio.file.Files @@ -31,10 +32,18 @@ object AgentHost { /** A tool call; [output] stays null until its result arrives. */ data class Used(val id: String, val tool: String, val detail: String, val input: String = "", val output: String? = null, val failed: Boolean = false) : Entry data class Result(val id: String, val output: String, val failed: Boolean) : Entry - data class Finished(val error: String?, val stopped: Boolean = false, val usage: Usage? = null) : Entry + /** [planned]: the turn ran in plan mode, so it ends on a plan that nothing has carried out yet. */ + data class Finished(val error: String?, val stopped: Boolean = false, val usage: Usage? = null, val planned: Boolean = false) : Entry } - data class Usage(val durationMs: Long, val costUsd: Double, val inputTokens: Long, val outputTokens: Long) + /** [context] of [window] tokens is what the conversation held when the turn ended. */ + data class Usage( + val durationMs: Long, val costUsd: Double, val inputTokens: Long, val outputTokens: Long, + val context: Long = 0, val window: Long = 0, + ) + + /** A plan usage limit over a rolling window of [minutes]; [resetsAt] is in epoch seconds. */ + data class Limit(val minutes: Int, val usedPercent: Int, val resetsAt: Long) /** A message typed while the agent was working, sent when the turn ends. */ data class Queued(val text: String, val files: List) @@ -43,6 +52,7 @@ object AgentHost { private const val TAG = "AgentHost" private const val WORKSPACE = "/root/DroidDeck" + internal const val GUEST_PATH = "/root/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" private const val TICK_MS = 1_000L private const val IDLE_TICK_MS = 5_000L @@ -50,12 +60,18 @@ object AgentHost { @VisibleForTesting internal const val BRIEF = "You run inside DroidDeck on the user's handheld, in its Linux userland (Ubuntu under proot, aarch64), " + "and the user talks to you from DroidDeck's Agent tab, often on a small screen, so keep replies short. " + - "droiddeckctl (in the /root/DroidDeck checkout, tools/droiddeckctl) inspects and drives the app over loopback adb (\$ADB_SERIAL). " + + "droiddeckctl inspects and drives the app over loopback adb (\$ADB_SERIAL); its guide is ${AgentSetup.CTL}/agent-control.md. " + + "Steam, the desktop and games run in DroidDeck's session, a separate guest from yours: a program you start here is not in it and has no screen. " + + "Reach the session through droiddeckctl: state, start steam, stop, launch, quit, focus, screenshot, logs, and guest to run a command inside it. " + + "Starting, stopping or restarting a session leaves you running. " + + "Never kill by a command-line pattern (pkill -f, pgrep -f piped to kill): your own command line holds the user's message, so the pattern matches you. " + + "End a game with droiddeckctl quit, the session with droiddeckctl stop, anything else by its pid. " + "dd-lab-build builds the checkout as a Lab build and restarts DroidDeck on it (docs/lab-builds.md). DroidDeck runs the build in a " + "process of its own and shows the user its progress and time left; dd-lab-build follows that build's log until it is done. " + "Run it with run_in_background and keep checking its output, so the user can talk to you meanwhile. " + "The restart ends this process, and this conversation continues on the new build. " + - "Files the user attaches are listed at the end of their message, under /root/.cache/droiddeck/attachments." + "Files the user attaches are listed at the end of their message, under /root/.cache/droiddeck/attachments. " + + "Commits and pull requests you make are the user's own: add no co-author line, AI credit or generated-by note." val entries = mutableStateListOf() val queue = mutableStateListOf() @@ -71,6 +87,9 @@ object AgentHost { /** The chosen model for [harness]; null is the CLI's default. */ var model by mutableStateOf(null) private set + /** The chosen reasoning effort for [harness]; null is the CLI's default. */ + var effort by mutableStateOf(null) + private set var plan by mutableStateOf(false) private set var chat by mutableStateOf(null) @@ -93,6 +112,12 @@ object AgentHost { /** Tokens in the conversation's context after its last step. */ var context by mutableLongStateOf(0L) private set + /** Tokens the model's context can hold; 0 until a turn has told. */ + var window by mutableLongStateOf(0L) + private set + /** The account's plan limits as [harness] last reported them. */ + var limits by mutableStateOf>(emptyList()) + private set var lab by mutableStateOf(null) private set @@ -109,6 +134,7 @@ object AgentHost { /** The running Lab build was asked for by the current turn, so stopping the turn stops it. */ private var labFromTurn = false private var conversation: String? = null + private var turnPlanned = false private var loaded = false private var appContext: Context? = null @@ -124,7 +150,9 @@ object AgentHost { File(app.filesDir, "agent").mkdirs() harness = AgentHarness.byId(prefs(app).getString(HARNESS_KEY, null)) model = prefs(app).getString(modelKey(harness), null) + effort = prefs(app).getString(effortKey(harness), null)?.takeIf { it in harness.efforts } plan = prefs(app).getBoolean(PLAN_KEY, false) + limits = decodeLimits(prefs(app).getString(limitsKey(harness), null)) available = LinuxRuntime.hasRootfs(app) installed = harness.files.all { guestFileExists(app, it) } if (!installed) state = State.MISSING else if (state == State.MISSING) state = State.IDLE @@ -147,7 +175,9 @@ object AgentHost { conversation = loaded.conversation entries.clear() entries.addAll(loaded.entries) - context = 0 + val last = loaded.entries.lastOrNull { it is Entry.Finished && (it.usage?.context ?: 0) > 0 } as? Entry.Finished + context = last?.usage?.context ?: 0 + window = last?.usage?.window ?: 0 } /** Opens a kept conversation, switching to the CLI it belongs to. */ @@ -213,6 +243,11 @@ object AgentHost { prefs(context).edit().putString(modelKey(harness), id).apply() } + fun chooseEffort(context: Context, level: String?) { + effort = level + prefs(context).edit().putString(effortKey(harness), level).apply() + } + fun choosePlan(context: Context, on: Boolean) { plan = on prefs(context).edit().putBoolean(PLAN_KEY, on).apply() @@ -247,9 +282,15 @@ object AgentHost { AgentHostService.start(app) val current = harness val prompt = AgentAttachments.prompt(message, attached) - val command = current.turn(prompt, conversation, AgentHarness.Options(model, plan && current.plans, BRIEF)) + turnPlanned = plan && current.plans + val command = current.turn(prompt, conversation, AgentHarness.Options(model, turnPlanned, BRIEF, effort)) val workdir = workspace(app) + var threadConversation = conversation Thread({ + runCatching { current.prepare(LinuxRuntime.rootDir(app)) } + runCatching { AgentSetup.installHelpers(app) } + // Without a session nothing else keeps the userland's resolver current. + runCatching { com.droiddeck.launcher.runtime.LinuxNetworkLinkComponent(app, LinuxRuntime.rootDir(app)).publish() } val child = try { guest(app, command, workdir).start() } catch (e: Exception) { @@ -258,6 +299,7 @@ object AgentHost { return@Thread } val started = Turn(child, AgentProcesses.pidOf(child)) + OrphanReaper.keep(started.pid) main.post { if (generation == gen && state == State.WORKING && turn == null) turn = started else AgentProcesses.killTree(started.pid) } child.outputStream.close() var ended = false @@ -269,13 +311,18 @@ object AgentHost { runCatching { child.inputStream.bufferedReader().forEachLine { line -> runCatching { raw?.apply { write(line); newLine(); flush() } } - val event = current.parse(line) ?: return@forEachLine - if (event.entries.any { it is Entry.Finished }) ended = true + val parsed = current.parse(line) ?: return@forEachLine + parsed.conversation?.let { threadConversation = it } + val done = parsed.entries.any { it is Entry.Finished } + if (done) ended = true + val event = if (!done) parsed else runCatching { current.usage(LinuxRuntime.rootDir(app), threadConversation) }.getOrNull() + ?.let { parsed.copy(context = it.context ?: parsed.context, window = it.window ?: parsed.window, limits = it.limits ?: parsed.limits) } ?: parsed main.post { if (turn === started) apply(app, event) } } } runCatching { raw?.close() } val status = runCatching { child.waitFor() }.getOrDefault(-1) + OrphanReaper.release(started.pid) main.post { if (turn === started) { turn = null @@ -303,6 +350,16 @@ object AgentHost { queue.remove(item) } + /** Sends [item] now: the running turn stops where it is, and the rest of the queue waits for the next one. */ + fun sendNow(context: Context, item: Queued) { + val app = context.applicationContext + if (!queue.remove(item)) return + val rest = queue.toList() + stop(app) + queue.addAll(rest) + send(app, item.text, item.files) + } + /** Starts a new conversation; the current one stays in the history. */ fun forget(context: Context) { stop(context) @@ -311,6 +368,7 @@ object AgentHost { chat = null conversation = null this.context = 0 + window = 0 prefs(context).edit().remove(CHAT_KEY).apply() state = if (installed) State.IDLE else State.MISSING } @@ -320,10 +378,10 @@ object AgentHost { * proot over the installed rootfs, without a session. Loopback adb is connected first so * droiddeckctl reaches the app. */ - fun guest(app: Context, command: List, workdir: String = "/root", connectAdb: Boolean = true): ProcessBuilder { + fun guest(app: Context, command: List, workdir: String = "/root", connectAdb: Boolean = true, fakeRoot: Boolean = false): ProcessBuilder { val adb = AgentAdb.prepare(app) val env = listOf( - "/usr/bin/env", "HOME=/root", "PATH=/root/.local/bin:/usr/local/bin:/usr/bin:/bin", "LANG=C.UTF-8", + "/usr/bin/env", "HOME=/root", "PATH=$GUEST_PATH", "LANG=C.UTF-8", "ADB_SERIAL=${adb.serial}", "ADB_VENDOR_KEYS=${adb.vendorKeys}", "DD_AGENT=1", "DD_AGENT_INBOX=${File(app.filesDir, "agent").path}", "BROWSER=/root/.local/bin/android-open", "DD_BROWSER_DISPLAY=${AgentAdb.browserDisplay}", ) @@ -333,7 +391,7 @@ object AgentHost { (if (connectAdb) "adb start-server >/dev/null 2>&1; adb connect \"\$ADB_SERIAL\" >/dev/null 2>&1; " else "") + "cd \"$1\" 2>/dev/null; shift; exec \"$@\"", "sh", workdir, ) - val proot = LinuxRuntime.command(app, null, null, Environment.getExternalStorageDirectory(), env + shell + command) + val proot = LinuxRuntime.command(app, null, null, Environment.getExternalStorageDirectory(), null, env + shell + command, fakeRoot) return ProcessBuilder(proot).redirectErrorStream(true).apply { environment().apply { remove("LD_PRELOAD"); remove("LD_AUDIT"); remove("LD_LIBRARY_PATH") @@ -360,6 +418,11 @@ object AgentHost { event.text?.let { live += it } event.thinking?.let { liveThinking += it } event.context?.let { context = it } + event.window?.let { window = it } + event.limits?.let { reported -> + limits = (limits.filter { old -> reported.none { it.minutes == old.minutes } } + reported).sortedBy { it.minutes } + prefs(app).edit().putString(limitsKey(harness), encodeLimits(limits)).apply() + } for (entry in event.entries) when (entry) { is Entry.Finished -> finish(app, entry.error, usage = event.usage) else -> { @@ -377,7 +440,8 @@ object AgentHost { if (!stopped) labFromTurn = false live = "" liveThinking = "" - record(app, Entry.Finished(error, stopped, usage)) + val held = if (context > 0) (usage ?: Usage(0, 0.0, 0, 0)).copy(context = context, window = window) else usage + record(app, Entry.Finished(error, stopped, held, planned = turnPlanned && !stopped && error == null)) state = State.IDLE unseen = true failed = error != null @@ -498,9 +562,15 @@ object AgentHost { val child = guest(app, listOf("sh", "-c", "mkdir -p /root/.cache; DD_LAB_DETACHED=1 exec dd-lab-build \"\$@\" > /root/.cache/dd-lab-build.log 2>&1", "dd-lab-build") + args, cwd).start() main.post { labProcess = child } - child.outputStream.close() - child.inputStream.readBytes() - child.waitFor() + val pid = AgentProcesses.pidOf(child) + OrphanReaper.keep(pid) + try { + child.outputStream.close() + child.inputStream.readBytes() + child.waitFor() + } finally { + OrphanReaper.release(pid) + } }.onFailure { Log.w(TAG, "could not run a Lab build", it) } main.post { labProcess = null @@ -529,6 +599,19 @@ object AgentHost { private const val RETRY_MS = 3_000L private fun modelKey(harness: AgentHarness) = "model_${harness.id}" + private fun limitsKey(harness: AgentHarness) = "limits_${harness.id}" + + @VisibleForTesting + internal fun encodeLimits(list: List) = org.json.JSONArray(list.map { + org.json.JSONObject().put("minutes", it.minutes).put("used", it.usedPercent).put("resets", it.resetsAt) + }).toString() + + @VisibleForTesting + internal fun decodeLimits(text: String?): List = runCatching { + val a = org.json.JSONArray(text ?: return emptyList()) + (0 until a.length()).map { a.getJSONObject(it) }.map { Limit(it.optInt("minutes"), it.optInt("used"), it.optLong("resets")) } + }.getOrDefault(emptyList()) + private fun effortKey(harness: AgentHarness) = "effort_${harness.id}" internal fun prefs(context: Context) = context.getSharedPreferences("agent", Context.MODE_PRIVATE) } diff --git a/app/src/main/java/com/droiddeck/launcher/agent/AgentHostService.kt b/app/src/main/java/com/droiddeck/launcher/agent/AgentHostService.kt index e8f3036d16..66fed326ee 100644 --- a/app/src/main/java/com/droiddeck/launcher/agent/AgentHostService.kt +++ b/app/src/main/java/com/droiddeck/launcher/agent/AgentHostService.kt @@ -77,6 +77,9 @@ class AgentHostService : Service() { private fun describe(context: Context): String { val lab = AgentHost.lab?.takeIf { it.running } if (lab != null) return context.getString(R.string.agent_lab_progress, lab.permille / 10, minutes(lab.etaSeconds.toLong().coerceAtLeast(0))) + AgentSetup.detail[AgentSetup.Step.GITHUB]?.takeIf { + AgentSetup.status[AgentSetup.Step.GITHUB] == AgentSetup.Status.WORKING && it.startsWith("GitHub device code:") + }?.let { return it } if (AgentHost.state != AgentHost.State.WORKING) return context.getString(R.string.agent_setting_up) val tool = AgentHost.running() val elapsed = minutes((SystemClock.elapsedRealtime() - AgentHost.turnStarted) / 1000) diff --git a/app/src/main/java/com/droiddeck/launcher/agent/AgentSetup.kt b/app/src/main/java/com/droiddeck/launcher/agent/AgentSetup.kt index 47efab507d..a5f900d6f5 100644 --- a/app/src/main/java/com/droiddeck/launcher/agent/AgentSetup.kt +++ b/app/src/main/java/com/droiddeck/launcher/agent/AgentSetup.kt @@ -8,6 +8,7 @@ import androidx.compose.runtime.mutableStateMapOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import com.droiddeck.launcher.runtime.LinuxRuntime +import com.droiddeck.launcher.session.OrphanReaper import java.io.File import java.util.concurrent.TimeUnit @@ -39,7 +40,8 @@ object AgentSetup { private val main = Handler(Looper.getMainLooper()) private const val REPO = "https://github.com/Droid-Deck/DroidDeck.git" private const val CHECKOUT = "/root/DroidDeck" - private val HELPERS = listOf("android-open", "dd-gh-login") + private val HELPERS = listOf("android-open", "dd-gh-login", "droiddeckctl") + internal const val CTL = "/root/.local/share/droiddeck/ctl" private const val PROBE_TIMEOUT_S = 60L fun check(context: Context) { @@ -71,6 +73,8 @@ object AgentSetup { Thread({ for ((step, command) in probes) probe(app, harness, step, command) }, "agent-checks").start() } + fun runsAsRoot(step: Step) = step == Step.INSTALL + /** Runs [step]'s action. [CONNECTION] is the app's own pairing flow, so the caller opens it. */ fun run(context: Context, step: Step) { val app = context.applicationContext @@ -79,7 +83,8 @@ object AgentSetup { Step.CONNECTION -> return Step.INSTALL -> { listOf("sh", "-c", "set -e; export DEBIAN_FRONTEND=noninteractive; " + - "apt-get update; apt-get install -y --no-install-recommends git gh adb curl ca-certificates python3; ${harness.install}") + "dpkg --configure -a; apt-get update || echo 'Some package sources could not be refreshed; continuing'; apt-get -f install -y; " + + "apt-get install -y --no-install-recommends git gh adb curl ca-certificates python3; ${harness.install}") } Step.SIGN_IN -> harness.signIn Step.GITHUB -> listOf("dd-gh-login") @@ -93,13 +98,26 @@ object AgentSetup { Thread({ val result = runCatching { installHelpers(app) - val child = AgentHost.guest(app, command).start() - child.outputStream.close() - child.inputStream.bufferedReader().forEachLine { line -> - val text = line.trim() - if (text.isNotEmpty() && !noise(text)) main.post { detail[step] = text.take(160) } + runCatching { harness.prepare(LinuxRuntime.rootDir(app)) } + val child = AgentHost.guest(app, command, fakeRoot = runsAsRoot(step)).start() + val pid = AgentProcesses.pidOf(child) + OrphanReaper.keep(pid) + try { + child.outputStream.close() + logFile(app, step).apply { parentFile?.mkdirs() }.bufferedWriter().use { log -> + child.inputStream.bufferedReader().forEachLine { line -> + log.appendLine(line) + val text = line.trim() + if (text.isNotEmpty() && !noise(text)) main.post { + detail[step] = text.take(160) + if (step == Step.GITHUB && text.startsWith("GitHub device code:")) AgentHostService.update(app) + } + } + child.waitFor().also { log.appendLine("exit $it") } + } + } finally { + OrphanReaper.release(pid) } - child.waitFor() } main.post { AgentHostService.setupEnded(app) @@ -115,6 +133,9 @@ object AgentSetup { }, "agent-setup-${step.name.lowercase()}").start() } + /** The whole output of a step's last run; the card shows only its last line. */ + fun logFile(app: Context, step: Step) = File(app.filesDir, "agent/setup-${step.name.lowercase()}.log") + fun buildToolsInstalled(app: Context) = AgentHost.guestFileExists(app, "/root/aapt2/aapt2") && AgentHost.guestFileExists(app, "$CHECKOUT/.git") /** dd-lab-build compiled this install's commit, so a Lab build compiles only what changed. */ @@ -164,12 +185,16 @@ object AgentSetup { } /** Written before every step, so the helpers a step relies on are there and match this DroidDeck version. */ - private fun installHelpers(app: Context) { - val bin = File(LinuxRuntime.rootDir(app), "root/.local/bin").apply { mkdirs() } - for (name in HELPERS) { - val target = File(bin, name) - app.assets.open("agent/$name").use { input -> target.outputStream().use { input.copyTo(it) } } - target.setExecutable(true, false) - } + internal fun installHelpers(app: Context) { + val root = LinuxRuntime.rootDir(app) + val bin = File(root, "root/.local/bin").apply { mkdirs() } + for (name in HELPERS) copyAsset(app, "agent/$name", File(bin, name)) + val ctl = File(root, CTL.removePrefix("/")).apply { mkdirs() } + for (name in app.assets.list("agent/ctl").orEmpty()) copyAsset(app, "agent/ctl/$name", File(ctl, name)) + } + + private fun copyAsset(app: Context, asset: String, target: File) { + app.assets.open(asset).use { input -> target.outputStream().use { input.copyTo(it) } } + target.setExecutable(true, false) } } diff --git a/app/src/main/java/com/droiddeck/launcher/agent/AgentTab.kt b/app/src/main/java/com/droiddeck/launcher/agent/AgentTab.kt new file mode 100644 index 0000000000..7392473c72 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/agent/AgentTab.kt @@ -0,0 +1,23 @@ +package com.droiddeck.launcher.agent + +import android.content.Context +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import com.droiddeck.launcher.session.SessionPrefs + +object AgentTab { + var shown by mutableStateOf(true) + private set + + val visible: Boolean get() = shown && AgentHost.available + + fun load(context: Context) { + shown = SessionPrefs.agentTab(context) + } + + fun set(context: Context, show: Boolean) { + shown = show + SessionPrefs.setAgentTab(context, show) + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/core/AddonPack.kt b/app/src/main/java/com/droiddeck/launcher/core/AddonPack.kt index d3d5cf2c74..9e0452771d 100644 --- a/app/src/main/java/com/droiddeck/launcher/core/AddonPack.kt +++ b/app/src/main/java/com/droiddeck/launcher/core/AddonPack.kt @@ -3,6 +3,7 @@ package com.droiddeck.launcher.core import android.content.Context import android.util.Log import com.droiddeck.launcher.BuildConfig +import com.droiddeck.launcher.lab.LabOverlay import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob @@ -16,6 +17,7 @@ import java.io.FileInputStream internal class AddonPack( val name: String, private val sha256: String, val size: Long, private val required: List, private val reuseDeviceCopy: Boolean = sha256.isEmpty() && !BuildConfig.CI_BUILD, + private val labBuild: Boolean = LabOverlay.active != null, private val bundle: (Context) -> java.io.InputStream = { it.assets.open("packs/$name.tar.zst") }, ) { sealed interface State { @@ -42,7 +44,8 @@ internal class AddonPack( fun installed(context: Context): Boolean = version(context).isNotEmpty() && File(dir(context), COMPLETE).isFile - private fun version(context: Context): String = if (!reuseDeviceCopy) sha256 else deviceCopy(context).orEmpty() + private fun version(context: Context): String = + if (reuseDeviceCopy || labBuild) deviceCopy(context) ?: sha256 else sha256 private fun deviceCopy(context: Context): String? = root(context).listFiles().orEmpty() .filter { dir -> diff --git a/app/src/main/java/com/droiddeck/launcher/core/AppUiPrefs.kt b/app/src/main/java/com/droiddeck/launcher/core/AppUiPrefs.kt index 7b8536202d..3f308636db 100644 --- a/app/src/main/java/com/droiddeck/launcher/core/AppUiPrefs.kt +++ b/app/src/main/java/com/droiddeck/launcher/core/AppUiPrefs.kt @@ -27,6 +27,25 @@ object AppUiPrefs { context.getSharedPreferences("app-ui", Context.MODE_PRIVATE).edit().putInt("orientation", value).apply() } + const val HOME_PAGE_STEAM = "steam" + const val HOME_PAGE_APPS = "android-apps" + + val homePageOptions = listOf( + HOME_PAGE_STEAM to R.string.rail_steam, + HOME_PAGE_APPS to R.string.content_android_apps, + ) + + fun homePage(context: Context): String = + context.getSharedPreferences("app-ui", Context.MODE_PRIVATE) + .getString("home-page", null) + .takeIf { value -> homePageOptions.any { it.first == value } } + ?: HOME_PAGE_STEAM + + fun setHomePage(context: Context, value: String) { + require(homePageOptions.any { it.first == value }) + context.getSharedPreferences("app-ui", Context.MODE_PRIVATE).edit().putString("home-page", value).apply() + } + internal fun normalizeScale(percent: Int): Int = percent.takeIf { it in scales } ?: DEFAULT_SCALE fun scale(context: Context): Int = normalizeScale( diff --git a/app/src/main/java/com/droiddeck/launcher/core/GameEnvironment.kt b/app/src/main/java/com/droiddeck/launcher/core/GameEnvironment.kt index 26ffb499cc..53f152a60b 100644 --- a/app/src/main/java/com/droiddeck/launcher/core/GameEnvironment.kt +++ b/app/src/main/java/com/droiddeck/launcher/core/GameEnvironment.kt @@ -49,6 +49,16 @@ object GameEnvironment { return withScopeValue(config, scope, NO_STEAM, if (on) "1" else null) } + const val GAME_RESOLUTION = "DROIDDECK_GAME_RESOLUTION" + + fun gameResolution(config: Config, scope: String): GameResolution.Choice? = + if (scope.isEmpty()) null else GameResolution.parse(config.games[scope]?.get(GAME_RESOLUTION)) + + fun withGameResolution(config: Config, scope: String, choice: GameResolution.Choice?): Config { + require(scope.isNotEmpty() && validScope(scope)) + return withScopeValue(config, scope, GAME_RESOLUTION, choice?.let(GameResolution::format)) + } + fun effective(config: Config, preset: String, scope: String, forceSsbs: Boolean = false): Map = defaults(preset, forceSsbs) + config.shared + if (scope.isEmpty()) emptyMap() else config.games[scope].orEmpty() diff --git a/app/src/main/java/com/droiddeck/launcher/core/GameResolution.kt b/app/src/main/java/com/droiddeck/launcher/core/GameResolution.kt new file mode 100644 index 0000000000..0255d9616b --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/core/GameResolution.kt @@ -0,0 +1,70 @@ +package com.droiddeck.launcher.core + +object GameResolution { + sealed interface Choice + data class Fixed(val width: Int, val height: Int) : Choice + data class Scaled(val scale: Float) : Choice + + data class Aspect(val label: String, val sizes: List) + + val aspects = listOf( + Aspect("16:9", listOf(Fixed(960, 540), Fixed(1280, 720), Fixed(1600, 900), Fixed(1920, 1080), Fixed(2560, 1440))), + Aspect("16:10", listOf(Fixed(1280, 800), Fixed(1440, 900), Fixed(1680, 1050), Fixed(1920, 1200), Fixed(2560, 1600))), + Aspect("4:3", listOf(Fixed(640, 480), Fixed(800, 600), Fixed(1024, 768), Fixed(1280, 960), Fixed(1440, 1080))), + ) + + val scales = listOf(1.5f, 2f, 3f) + + const val MIN_WIDTH = 320 + const val MIN_HEIGHT = 240 + const val MAX_SIDE = 7680 + private const val SCALED_PREFIX = "/" + + fun parse(value: String?): Choice? { + val text = value?.trim().orEmpty() + if (text.startsWith(SCALED_PREFIX)) { + return text.removePrefix(SCALED_PREFIX).toFloatOrNull()?.takeIf { it > 1f && it <= 8f }?.let(::Scaled) + } + val parts = text.split('x', 'X', 'ร—').map { it.trim().toIntOrNull() } + if (parts.size != 2) return null + val (w, h) = parts + return if (w != null && h != null && valid(w, h)) Fixed(w and 1.inv(), h and 1.inv()) else null + } + + fun valid(width: Int, height: Int) = width in MIN_WIDTH..MAX_SIDE && height in MIN_HEIGHT..MAX_SIDE + + fun format(choice: Choice): String = when (choice) { + is Fixed -> "${choice.width}x${choice.height}" + is Scaled -> SCALED_PREFIX + formatScale(choice.scale) + } + + fun formatScale(scale: Float): String = + (Math.round(scale * 10) / 10f).let { if (it % 1f == 0f) it.toInt().toString() else it.toString() } + + fun resolve(choice: Choice, output: Pair): Pair = when (choice) { + is Fixed -> choice.width to choice.height + is Scaled -> (Math.round(output.first / choice.scale).coerceAtLeast(MIN_WIDTH) and 1.inv()) to + (Math.round(output.second / choice.scale).coerceAtLeast(MIN_HEIGHT) and 1.inv()) + } + + fun aspectLabel(width: Int, height: Int): String { + if (width <= 0 || height <= 0) return "" + val ratio = width.toFloat() / height + aspects.firstOrNull { a -> + val (w, h) = a.label.split(':').map(String::toFloat) + kotlin.math.abs(ratio - w / h) < 0.02f + }?.let { return it.label } + if (kotlin.math.abs(ratio - 64f / 27f) < 0.04f || kotlin.math.abs(ratio - 21f / 9f) < 0.04f) return "21:9" + val g = gcd(width, height) + return if (width / g <= 32) "${width / g}:${height / g}" else String.format(java.util.Locale.ROOT, "%.2f:1", ratio) + } + + fun sizesFor(aspect: Aspect, panel: Pair): List { + val long = maxOf(panel.first, panel.second) + val short = minOf(panel.first, panel.second) + val fit = aspect.sizes.filter { it.width <= long && it.height <= short } + return fit.ifEmpty { aspect.sizes.take(1) } + } + + private tailrec fun gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b) +} diff --git a/app/src/main/java/com/droiddeck/launcher/core/HostProcess.kt b/app/src/main/java/com/droiddeck/launcher/core/HostProcess.kt index 0757192461..114e337892 100644 --- a/app/src/main/java/com/droiddeck/launcher/core/HostProcess.kt +++ b/app/src/main/java/com/droiddeck/launcher/core/HostProcess.kt @@ -13,6 +13,11 @@ object HostProcess { @JvmStatic fun start(command: String, env: Array?, dir: File?, onExit: Consumer?, onLine: Consumer?, outputFile: File?): Int { + return start(command, env, dir, onExit, onLine, outputFile, null) + } + + @JvmStatic + fun start(command: String, env: Array?, dir: File?, onExit: Consumer?, onLine: Consumer?, outputFile: File?, onOutputComplete: Runnable?): Int { val argv = split(command) if (argv.isEmpty()) return -1 return try { @@ -35,6 +40,8 @@ object HostProcess { try { process.inputStream.bufferedReader().useLines { lines -> lines.forEach { onLine.accept(it) } } } catch (e: Exception) { + } finally { + onOutputComplete?.run() } }, "proc-out-$pid").apply { priority = Thread.NORM_PRIORITY - 1; isDaemon = true; start() } } diff --git a/app/src/main/java/com/droiddeck/launcher/core/SessionLogCapture.kt b/app/src/main/java/com/droiddeck/launcher/core/SessionLogCapture.kt index b9c0256dbf..c7b4a78c7c 100644 --- a/app/src/main/java/com/droiddeck/launcher/core/SessionLogCapture.kt +++ b/app/src/main/java/com/droiddeck/launcher/core/SessionLogCapture.kt @@ -5,6 +5,9 @@ import android.util.Log import java.io.BufferedWriter import java.io.File import java.io.FileOutputStream +import java.nio.file.Files +import java.nio.file.StandardCopyOption +import java.util.concurrent.atomic.AtomicInteger object SessionLogCapture { private const val TAG = "SessionLogCapture" @@ -104,4 +107,53 @@ object SessionLogCapture { Log.w(TAG, "could not dump the crash buffer", e) } } + + fun dumpMemoryPressure(target: File) { + var temporary: File? = null + try { + val staged = File.createTempFile(target.name, ".part", target.parentFile).also { temporary = it } + val lines = StringBuilder() + val done = java.util.concurrent.CountDownLatch(1) + val outputDone = java.util.concurrent.CountDownLatch(1) + val exitStatus = AtomicInteger(Int.MIN_VALUE) + val pid = HostProcess.start( + "/system/bin/logcat -b events -d -v threadtime -t 800", null, target.parentFile, + { status -> exitStatus.set(status); done.countDown() }, + { line -> synchronized(lines) { lines.append(line).append('\n') } }, + null, + outputDone::countDown, + ) + val deadline = System.nanoTime() + java.util.concurrent.TimeUnit.SECONDS.toNanos(10) + val finished = if (pid == -1) false else { + val exitTime = deadline - System.nanoTime() + exitTime > 0 && done.await(exitTime, java.util.concurrent.TimeUnit.NANOSECONDS) && + (deadline - System.nanoTime()).let { it > 0 && outputDone.await(it, java.util.concurrent.TimeUnit.NANOSECONDS) } + } + val body = synchronized(lines) { lines.toString() } + val status = exitStatus.get() + val pressure = runCatching { File("/proc/pressure/memory").readText() }.getOrDefault("unavailable\n") + val meminfo = runCatching { File("/proc/meminfo").readText() }.getOrDefault("unavailable\n") + val gpu = runCatching { File("/sys/class/kgsl/kgsl/page_alloc").readText() }.getOrDefault("unavailable\n") + staged.writeText( + "Android memory events:\n" + + when { + pid == -1 -> "(logcat could not be started at all)\n" + status != Int.MIN_VALUE && status != 0 -> "(logcat failed with exit status $status; no Android memory events were captured)\n" + + if (body.isEmpty()) "" else "\nlogcat command output:\n$body" + !finished -> if (body.isEmpty()) "(logcat did not finish within 10 s; nothing captured)\n" + else body + "(logcat did not finish within 10 s; later events may be missing)\n" + body.isNotEmpty() -> body + else -> "(no readable events were returned)\n" + } + + "\n/proc/pressure/memory:\n$pressure\n/proc/meminfo:\n$meminfo\n/sys/class/kgsl/kgsl/page_alloc:\n$gpu" + ) + Files.move( + staged.toPath(), target.toPath(), + StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE, + ) + } catch (e: Exception) { + temporary?.delete() + Log.w(TAG, "could not dump memory pressure diagnostics", e) + } + } } diff --git a/app/src/main/java/com/droiddeck/launcher/frontend/AddedGames.kt b/app/src/main/java/com/droiddeck/launcher/frontend/AddedGames.kt index c7d774bf2e..d0f4ea80a0 100644 --- a/app/src/main/java/com/droiddeck/launcher/frontend/AddedGames.kt +++ b/app/src/main/java/com/droiddeck/launcher/frontend/AddedGames.kt @@ -97,7 +97,7 @@ object AddedGames { return File(LinuxRuntime.rootDir(context), guest.removePrefix("/")) } - fun candidates(folder: File): List = rank(folder).exes + fun candidates(folder: File, reuse: Boolean = false): List = rank(folder, reuse).exes fun rank(folder: File, reuse: Boolean = false): GameExePicker.Ranking { val key = "${folder.path}|${folder.lastModified()}" @@ -418,6 +418,7 @@ object AddedGames { private fun scanGame(context: Context, folder: File, out: MutableList, single: AddedExes.Entry? = null, reuse: Boolean = false) { run { val sidecar = StoreGameSidecar.read(folder)?.let { com.droiddeck.launcher.stores.StoreLaunch.adopt(folder, it) } + if (sidecar?.store == Store.ROCKSTAR && sidecar.launcher != com.droiddeck.launcher.stores.StoreLaunch.LAUNCHER) return sidecar?.takeIf { it.id.isNotEmpty() }?.let { SessionPrefs.followStoreGame(context, "${it.store.id}:${it.id}", folder.path) { old -> !File(old).exists() } } val ranking = rank(folder, reuse) val candidates = ranking.exes @@ -433,6 +434,7 @@ object AddedGames { val autoName = sidecar?.title ?: identifiedName(folder, found) ?: folder.name val crc = CRC32().apply { update(("\"${foundGuest.replaceFirst(Regex("^$LIBRARY/"), "$LEGACY_LIBRARY/")}\"" + autoName).toByteArray()) }.value val appId = SessionPrefs.addedGameAppId(context, folder.path, crc or 0x80000000L) + if (sidecar?.store == Store.ROCKSTAR) com.droiddeck.launcher.stores.rockstar.RockstarLaunch.applyDefaults(context, sidecar.id, appId) val config = accountConfig(SessionPrefs.activeSteamRoot(context)) val record = config?.let { shortcutRecord(it, appId) } val rev = record?.optInt("rev", 0) ?: 0 diff --git a/app/src/main/java/com/droiddeck/launcher/frontend/AddedSoundtracks.kt b/app/src/main/java/com/droiddeck/launcher/frontend/AddedSoundtracks.kt new file mode 100644 index 0000000000..635941cb7a --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/frontend/AddedSoundtracks.kt @@ -0,0 +1,69 @@ +package com.droiddeck.launcher.frontend + +import android.content.Context +import org.json.JSONArray +import org.json.JSONObject +import java.io.File + +object AddedSoundtracks { + private fun file(context: Context) = File(context.filesDir, "added-soundtracks.json") + + class Entry(val path: String, val name: String, val id: Int = 0) + + internal fun assignIds(list: List): List { + val used = list.filter { it.id != 0 }.map { it.id }.toMutableSet() + return list.map { e -> + if (e.id != 0) e else { + var id = idOf(e.path) + while (id == 0 || !used.add(id)) id = (id + 1) or Int.MIN_VALUE + Entry(e.path, e.name, id) + } + } + } + + @Synchronized + fun entries(context: Context): List = runCatching { + val f = file(context).takeIf { it.isFile } ?: return emptyList() + val array = JSONArray(f.readText()) + val raw = List(array.length()) { i -> array.getJSONObject(i).let { Entry(it.getString("path"), it.getString("name"), it.optInt("id", 0)) } } + val ready = assignIds(raw) + if (raw.any { it.id == 0 }) save(context, ready) + ready + }.getOrDefault(emptyList()) + + @Synchronized + private fun save(context: Context, list: List): Boolean = + runCatching { + val array = JSONArray() + list.forEach { array.put(JSONObject().put("path", it.path).put("name", it.name).put("id", it.id)) } + val f = file(context) + val tmp = File(f.path + ".tmp") + tmp.writeText(array.toString()) + if (tmp.renameTo(f)) true else { tmp.delete(); false } + }.getOrDefault(false) + + fun add(context: Context, folder: File): Boolean { + if (!folder.isDirectory || Soundtrack.audioFiles(folder).isEmpty()) return false + return synchronized(this) { + val list = entries(context) + list.any { it.path == folder.path } || save(context, assignIds(list + Entry(folder.path, folder.name))) + } + } + + fun remove(context: Context, path: String): Boolean = + synchronized(this) { save(context, entries(context).filterNot { it.path == path }) } + + internal fun idOf(path: String): Int = path.hashCode() or Int.MIN_VALUE + + fun games(context: Context): List = entries(context).mapNotNull { e -> + val dir = File(e.path).takeIf { it.isDirectory } ?: return@mapNotNull null + game(context, e, dir, e.id) + } + + private fun game(context: Context, e: Entry, dir: File, id: Int): Library.SteamGame { + return Library.SteamGame( + appId = id, name = e.name, art = SoundtrackCollectionArt.chosen(context, id) ?: Soundtrack.firstCover(context, dir), library = Library.ADDED, gameId = id.toLong() and 0xFFFFFFFFL, + gameFiles = dir, source = Library.ADDED, soundtrack = true, + ) + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/frontend/GameRemoval.kt b/app/src/main/java/com/droiddeck/launcher/frontend/GameRemoval.kt index 388448e184..a35c71342b 100644 --- a/app/src/main/java/com/droiddeck/launcher/frontend/GameRemoval.kt +++ b/app/src/main/java/com/droiddeck/launcher/frontend/GameRemoval.kt @@ -21,7 +21,7 @@ object GameRemoval { fun steamFiles(game: Library.SteamGame): SteamFiles? { val dir = game.gameFiles ?: return null val common = dir.parentFile ?: return null - if (common.name != "common") return null + if (common.name != (if (game.soundtrack) "music" else "common")) return null val steamapps = common.parentFile ?: return null if (steamapps.name != "steamapps") return null val manifest = File(steamapps, "appmanifest_${game.appId}.acf") diff --git a/app/src/main/java/com/droiddeck/launcher/frontend/Library.kt b/app/src/main/java/com/droiddeck/launcher/frontend/Library.kt index b303ecc71e..8acbbe18b0 100644 --- a/app/src/main/java/com/droiddeck/launcher/frontend/Library.kt +++ b/app/src/main/java/com/droiddeck/launcher/frontend/Library.kt @@ -19,9 +19,10 @@ object Library { val storeId: String? = null, val logo: File? = null, val installedAt: Long = 0L, + val soundtrack: Boolean = false, ) { fun withArt(art: File?, hero: File?, icon: File?, logo: File? = this.logo) = - SteamGame(appId, name, art, library, gameId, hero, lastPlayed, gameFiles, protonPrefix, icon, source, storeId, logo, installedAt) + SteamGame(appId, name, art, library, gameId, hero, lastPlayed, gameFiles, protonPrefix, icon, source, storeId, logo, installedAt, soundtrack) val gameIdString: String get() = java.lang.Long.toUnsignedString(gameId) val launchKey: String get() = if (storeId != null) "$source:$storeId" else gameIdString @@ -38,6 +39,7 @@ object Library { const val BATTLENET_LAUNCHER = "battlenet-launcher" const val XBOX_CLOUD = "xbox-cloud" const val SOURCE_STEAM = "steam" + const val SOURCE_COLLECTION = "collection" 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) { @@ -123,9 +125,13 @@ object Library { .distinctBy { runCatching { it.canonicalPath }.getOrDefault(it.absolutePath) } } + fun soundtracks(context: Context, arch: String = SessionPrefs.activeSteamClientArch(context)): List = + steamGames(context, arch = arch, withShared = false, soundtracks = true, soundtracksOnly = true) + fun steamGames( context: Context, strictRead: Boolean = false, arch: String = SessionPrefs.activeSteamClientArch(context), - withShared: Boolean = true, + withShared: Boolean = true, soundtracks: Boolean = false, soundtracksOnly: Boolean = false, + onlyAppIds: Set? = null, ): List { val root = SessionPrefs.steamRoot(context, arch) val cache = File(root, "appcache/librarycache") @@ -138,21 +144,26 @@ object Library { if (strictRead && steamapps.isDirectory) check(manifests != null) { context.getString(R.string.game_sync_err_manifests) } manifests?.sortedBy { it.name }?.forEach { manifest -> val appId = manifest.name.removePrefix("appmanifest_").removeSuffix(".acf").toIntOrNull() ?: return@forEach - if (appId in NOT_GAMES || out.containsKey(appId)) return@forEach + if (appId in NOT_GAMES || out.containsKey(appId) || + (onlyAppIds != null && appId !in onlyAppIds) + ) return@forEach val text = try { manifest.readText() } catch (e: Exception) { if (strictRead) throw e; return@forEach } val name = NAME.find(text)?.groupValues?.get(1)?.trim().orEmpty() val flags = STATE.find(text)?.groupValues?.get(1)?.toIntOrNull() ?: 0 if (name.isEmpty() || flags and 4 == 0) return@forEach + 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) } + val musicFiles = if (gameFiles == null) installDir?.let { File(steamapps, "music/$it").takeIf(File::isDirectory) } else null + if (musicFiles != null && !soundtracks) return@forEach + if (soundtracksOnly && musicFiles == null) return@forEach val images = SteamCacheImages(File(cache, appId.toString())) val art = images.find(STEAM_CAPSULES) val hero = images.find(STEAM_HEROES) val lastPlayed = LAST_PLAYED.find(text)?.groupValues?.get(1)?.toLongOrNull() ?: 0L - 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] = SteamGameArt.withOverrides(context, SteamGame( - appId, name, art, label, hero = hero, lastPlayed = lastPlayed, - gameFiles = gameFiles, + appId, name, art ?: musicFiles?.let { Soundtrack.firstCover(context, it) }, label, hero = hero, lastPlayed = lastPlayed, + gameFiles = gameFiles ?: musicFiles, soundtrack = musicFiles != null, protonPrefix = protonPrefix(context, appId.toLong(), library, roots), icon = images.icon(), logo = images.find(STEAM_LOGOS), @@ -161,16 +172,42 @@ object Library { } if (withShared) { val other = if (arch == "x86_64") "arm64" else "x86_64" - val shared = sharedApps(context, arch) - out.keys - if (shared.isNotEmpty()) runCatching { steamGames(context, arch = other, withShared = false) }.getOrDefault(emptyList()) - .filter { it.appId in shared }.forEach { out[it.appId] = it } + val shared = try { + sharedApps(context, arch) - out.keys + } catch (e: IllegalStateException) { + if (strictRead) throw e + emptySet() + } + if (shared.isNotEmpty()) { + val otherGames = try { + steamGames( + context, + strictRead = strictRead, + arch = other, + withShared = false, + soundtracks = soundtracks, + onlyAppIds = shared, + ) + } catch (e: Exception) { + if (strictRead) throw e + emptyList() + } + otherGames.forEach { out[it.appId] = it } + } } return out.values.toList() } internal fun sharedApps(context: Context, arch: String): Set { val view = File(LinuxRuntime.rootDir(context), "root/.droiddeck-x64/shared/${if (arch == "x86_64") "arm64" else "x86-64"}/steamapps") - return view.list().orEmpty().mapNotNull { Regex("appmanifest_(\\d+)\\.acf").matchEntire(it)?.groupValues?.get(1)?.toIntOrNull() }.toSet() + val entries = view.list() + if (entries == null) { + if (!view.exists()) return emptySet() + throw IllegalStateException("Unable to read the shared Steam library.") + } + return entries.mapNotNull { + Regex("appmanifest_(\\d+)\\.acf").matchEntire(it)?.groupValues?.get(1)?.toIntOrNull() + }.toSet() } fun steamLibraryArt(context: Context): List> { diff --git a/app/src/main/java/com/droiddeck/launcher/frontend/Soundtrack.kt b/app/src/main/java/com/droiddeck/launcher/frontend/Soundtrack.kt new file mode 100644 index 0000000000..7f66f20962 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/frontend/Soundtrack.kt @@ -0,0 +1,308 @@ +package com.droiddeck.launcher.frontend + +import android.content.Context +import android.media.MediaMetadataRetriever +import org.json.JSONArray +import org.json.JSONObject +import java.io.File + +object Soundtrack { + class Track( + val file: File, val title: String, val disc: Int, val number: Int, val durationMs: Long, val artist: String = "", + val discLabel: String = disc.toString(), + ) { + val id: String get() = file.path + } + + class Album(val disc: Map>, val artist: String, val cover: File?) { + val tracks: List get() = disc.values.flatten() + val discs: List get() = disc.keys.toList() + val multiDisc: Boolean get() = disc.size > 1 + val totalMs: Long get() = tracks.sumOf { it.durationMs } + } + + class Raw( + val file: File, val folder: String, val tagDisc: Int?, val tagTrack: Int?, val tagTitle: String?, val tagArtist: String?, + val durationMs: Long, val size: Long = file.length(), + ) + + val EXTENSIONS = setOf("mp3", "flac", "ogg", "oga", "opus", "wav", "m4a", "aac") + private val LOSSLESS = setOf("flac", "wav") + private val COVERS = listOf("AlbumArtwork", "albumartwork", "cover", "Cover", "folder", "Folder", "front", "Front", "artwork", "Artwork") + internal val COVER_EXT = listOf("png", "jpg", "jpeg", "webp") + private val LEADING = Regex("^\\s*\\d+\\s*[.\\-_)]*\\s+") + private val DIGITS = Regex("^\\s*(\\d+)") + + fun isAudio(file: File): Boolean = file.isFile && file.extension.lowercase() in EXTENSIONS + + fun cleanTitle(fileName: String): String { + val base = fileName.substringBeforeLast('.', fileName).trim() + val tail = if (" - " in base) base.substringAfterLast(" - ") else base + val stripped = tail.replace(LEADING, "").trim() + return stripped.ifEmpty { tail.ifEmpty { base } } + } + + internal fun leadingNumber(fileName: String): Int? = DIGITS.find(fileName.substringAfterLast(" - "))?.groupValues?.get(1)?.toIntOrNull() + + private fun identity(r: Raw): String { + val d = r.tagDisc + val t = r.tagTrack + if (d != null && t != null) return "n:$d:$t" + val title = (r.tagTitle?.takeIf { it.isNotBlank() } ?: cleanTitle(r.file.name)).lowercase().filter { it.isLetterOrDigit() } + return "t:$title:${leadingNumber(r.file.name)}" + } + + private fun better(a: Raw, b: Raw): Raw { + val la = a.file.extension.lowercase() in LOSSLESS + val lb = b.file.extension.lowercase() in LOSSLESS + return when { + la != lb -> if (la) a else b + a.size != b.size -> if (a.size > b.size) a else b + else -> if (a.file.path <= b.file.path) a else b + } + } + + fun group(raws: List): Map> { + if (raws.isEmpty()) return emptyMap() + val unique = LinkedHashMap() + val home = HashMap() + val disc = HashMap() + val track = HashMap() + val title = HashMap() + for (r in raws) { + val id = identity(r) + unique[id] = unique[id]?.let { better(it, r) } ?: r + if (r.folder.isNotEmpty() && home[id].isNullOrEmpty()) home[id] = r.folder + r.tagDisc?.let { disc.putIfAbsent(id, it) } + r.tagTrack?.let { track.putIfAbsent(id, it) } + r.tagTitle?.takeIf { it.isNotBlank() }?.let { title.putIfAbsent(id, it) } + } + val kept = unique.map { (id, r) -> + Raw( + r.file, home[id] ?: r.folder, disc[id] ?: r.tagDisc, track[id] ?: r.tagTrack, title[id] ?: r.tagTitle, r.tagArtist, + r.durationMs, r.size, + ) + } + val folders = kept.filter { it.tagDisc == null }.map { it.folder }.distinct().sortedWith(naturalOrder) + val discs = kept.groupBy { r -> + r.tagDisc ?: if (folders.size <= 1 && kept.none { it.tagDisc != null }) 0 else folders.indexOf(r.folder) + 1 + } + return discs.toSortedMap().mapValues { (disc, list) -> + list.sortedWith( + compareBy({ leadingNumber(it.file.name) ?: it.tagTrack ?: Int.MAX_VALUE }, { it.tagTrack ?: Int.MAX_VALUE }, { it.file.name.lowercase() }), + ).mapIndexed { i, r -> + Track( + r.file, r.tagTitle?.takeIf { it.isNotBlank() } ?: cleanTitle(r.file.name), disc, i + 1, + r.durationMs, r.tagArtist.orEmpty(), labelOf(r, disc), + ) + } + } + } + + private val FOLDER_LABEL = Regex("[0-9][0-9 +&,.\\-]*") + + private fun labelOf(r: Raw, disc: Int): String { + if (r.tagDisc != null) return disc.toString() + val name = r.folder.substringAfterLast('/') + return if (FOLDER_LABEL.matches(name)) name else disc.toString() + } + + private val naturalOrder = Comparator { a, b -> + val x = Regex("\\d+|\\D+").findAll(a.lowercase()).map { it.value }.toList() + val y = Regex("\\d+|\\D+").findAll(b.lowercase()).map { it.value }.toList() + var i = 0 + var out = 0 + while (out == 0 && i < minOf(x.size, y.size)) { + val nx = x[i].toBigIntegerOrNull() + val ny = y[i].toBigIntegerOrNull() + out = if (nx != null && ny != null) nx.compareTo(ny) else x[i].compareTo(y[i]) + i++ + } + if (out != 0) out else x.size.compareTo(y.size) + } + + fun cover(dir: File): File? { + for (name in COVERS) for (ext in COVER_EXT) File(dir, "$name.$ext").takeIf { it.isFile }?.let { return it } + return dir.listFiles()?.filter { it.isFile && it.extension.lowercase() in COVER_EXT }?.minByOrNull { it.name.lowercase() } + } + + private fun parseNumber(value: String?): Int? = value?.substringBefore('/')?.trim()?.toIntOrNull() + + private fun read(file: File, root: File): Raw { + val folder = file.parentFile?.let { parent -> + if (parent.path == root.path) "" else parent.path.removePrefix(root.path).trimStart('/') + }.orEmpty() + val retriever = MediaMetadataRetriever() + return try { + retriever.setDataSource(file.path) + Raw( + file, folder, + parseNumber(retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DISC_NUMBER)), + parseNumber(retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_CD_TRACK_NUMBER)), + retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE), + retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST) + ?: retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ALBUMARTIST), + retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)?.toLongOrNull() ?: 0L, + ) + } catch (e: Exception) { + Raw(file, folder, null, null, null, null, 0L) + } finally { + runCatching { retriever.release() } + } + } + + private fun cacheFile(context: Context, root: File) = File(context.filesDir, "soundtrack-index/${root.path.hashCode().toUInt()}.json") + + private fun fromCache(context: Context, root: File, files: List): List? = runCatching { + val f = cacheFile(context, root).takeIf { it.isFile } ?: return null + val json = JSONObject(f.readText()) + if (json.optString("root") != root.path) return null + val rows = json.getJSONArray("rows") + val byPath = HashMap() + for (i in 0 until rows.length()) rows.getJSONObject(i).let { byPath[it.getString("p")] = it } + if (byPath.size != files.size) return null + files.map { file -> + val row = byPath[file.path] ?: return null + if (row.getLong("s") != file.length() || row.getLong("m") != file.lastModified()) return null + Raw( + file, row.getString("f"), row.optInt("d", -1).takeIf { it >= 0 }, row.optInt("n", -1).takeIf { it >= 0 }, + row.optString("t").takeIf { it.isNotEmpty() }, row.optString("a").takeIf { it.isNotEmpty() }, row.optLong("l"), + ) + } + }.getOrNull() + + private fun toCache(context: Context, root: File, raws: List) { + runCatching { + val rows = JSONArray() + for (r in raws) rows.put( + JSONObject().put("p", r.file.path).put("s", r.file.length()).put("m", r.file.lastModified()).put("f", r.folder) + .put("d", r.tagDisc ?: -1).put("n", r.tagTrack ?: -1).put("t", r.tagTitle.orEmpty()).put("a", r.tagArtist.orEmpty()) + .put("l", r.durationMs), + ) + val f = cacheFile(context, root) + f.parentFile?.mkdirs() + val tmp = File(f.path + ".tmp") + tmp.writeText(JSONObject().put("root", root.path).put("rows", rows).toString()) + if (!tmp.renameTo(f)) tmp.delete() + } + } + + fun audioFiles(root: File): List { + val out = ArrayList() + fun walk(dir: File, depth: Int) { + val children = dir.listFiles() ?: return + for (c in children.sortedBy { it.name.lowercase() }) { + if (c.isDirectory) { if (depth < 4) walk(c, depth + 1) } else if (isAudio(c)) out += c + } + } + walk(root, 0) + return out + } + + private fun coverCache(context: Context, root: File): File { + val digest = java.security.MessageDigest.getInstance("SHA-256").digest(root.path.toByteArray(Charsets.UTF_8)) + val key = digest.take(16).joinToString("") { "%02x".format(it) } + return File(context.filesDir, "soundtrack-index/cover-$key.jpg") + } + + fun cachedCover(context: Context, root: File): File? = coverCache(context, root).takeIf { it.isFile && it.length() > 0L } + + private fun embeddedBytes(file: File): ByteArray? = runCatching { + val retriever = MediaMetadataRetriever() + try { + retriever.setDataSource(file.path) + retriever.embeddedPicture + } finally { + runCatching { retriever.release() } + } + }.getOrNull()?.takeIf { it.isNotEmpty() } + + private fun hashOf(bytes: ByteArray): String = + java.security.MessageDigest.getInstance("SHA-256").digest(bytes).take(16).joinToString("") { "%02x".format(it) } + + private fun embeddedCover(context: Context, root: File, files: List): File? { + cachedCover(context, root)?.let { return it } + val miss = File(coverCache(context, root).path + ".none") + val probed = files.take(8) + val signature = hashOf(probed.joinToString("\n") { "${it.path}|${it.length()}|${it.lastModified()}" }.toByteArray(Charsets.UTF_8)) + if (runCatching { miss.isFile && miss.readText().trim() == signature }.getOrDefault(false)) return null + for (file in probed) { + val bytes = embeddedBytes(file) ?: continue + val out = coverCache(context, root) + runCatching { + out.parentFile?.mkdirs() + out.writeBytes(bytes) + }.onSuccess { return out } + } + runCatching { + miss.parentFile?.mkdirs() + miss.writeText(signature) + } + return null + } + + fun firstCover(context: Context, root: File): File? = cover(root) ?: embeddedCover(context, root, audioFiles(root)) + + @Synchronized + fun trackCover(context: Context, file: File): File? { + val dir = File(context.filesDir, "soundtrack-index/track-covers") + val marker = File(dir, "t-" + hashOf("${file.path}|${file.length()}|${file.lastModified()}".toByteArray(Charsets.UTF_8))) + if (marker.isFile) { + val name = runCatching { marker.readText().trim() }.getOrDefault("") + if (name.isEmpty()) return null + File(dir, name).takeIf { it.isFile && it.length() > 0L }?.let { + val now = System.currentTimeMillis() + marker.setLastModified(now) + it.setLastModified(now) + return it + } + } + val bytes = embeddedBytes(file) + return runCatching { + dir.mkdirs() + if (bytes == null) { + marker.writeText("") + prune(dir, setOf(marker.name)) + null + } else { + val out = File(dir, "c-" + hashOf(bytes) + ".jpg") + if (!out.isFile || out.length() == 0L) out.writeBytes(bytes) + marker.writeText(out.name) + prune(dir, setOf(marker.name, out.name)) + out + } + }.getOrNull() + } + + private const val TRACK_COVER_BYTES = 64L * 1024 * 1024 + private const val TRACK_COVER_FILES = 2000 + + private fun prune(dir: File, keep: Set) { + val all = dir.listFiles()?.filter { it.isFile } ?: return + var bytes = all.sumOf { it.length() } + var count = all.size + for (f in all.sortedBy { it.lastModified() }) { + if (bytes <= TRACK_COVER_BYTES && count <= TRACK_COVER_FILES) break + if (f.name in keep) continue + bytes -= f.length() + count-- + f.delete() + } + } + + fun load(context: Context, root: File, coverHint: File? = null): Album { + val files = audioFiles(root) + val raws = fromCache(context, root, files) ?: files.map { read(it, root) }.also { toCache(context, root, it) } + val disc = SoundtrackOrder.apply(context, root, group(raws)) + val artist = disc.values.flatten().map { it.artist }.filter { it.isNotBlank() }.groupingBy { it }.eachCount().maxByOrNull { it.value }?.key.orEmpty() + return Album(disc, artist, coverHint ?: cover(root) ?: embeddedCover(context, root, files)) + } + + fun formatLength(ms: Long): String { + val total = ms / 1000 + val h = total / 3600 + val m = (total % 3600) / 60 + val s = total % 60 + return if (h > 0) "%d:%02d:%02d".format(h, m, s) else "%d:%02d".format(m, s) + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/frontend/SoundtrackCollectionArt.kt b/app/src/main/java/com/droiddeck/launcher/frontend/SoundtrackCollectionArt.kt new file mode 100644 index 0000000000..44274fb55b --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/frontend/SoundtrackCollectionArt.kt @@ -0,0 +1,50 @@ +package com.droiddeck.launcher.frontend + +import android.content.Context +import java.io.File + +object SoundtrackCollectionArt { + internal fun dir(context: Context, id: Int) = File(context.filesDir, "soundtrack-art/$id") + + private fun sourceFile(context: Context, id: Int) = File(dir(context, id), "source") + + fun chosen(context: Context, id: Int): File? = dir(context, id).takeIf { it.isDirectory }?.let { AddedGameArt.chosen(it, AddedGameArt.Slot.COVER) } + + fun source(context: Context, id: Int): String = + sourceFile(context, id).takeIf { it.isFile }?.readText()?.trim().orEmpty().substringAfter('|', "") + + fun options(context: Context, id: Int, root: File?): List { + val paths = if (root != null) { + val images = root.listFiles()?.filter { it.isFile && it.extension.lowercase() in Soundtrack.COVER_EXT }?.sortedBy { it.name.lowercase() }.orEmpty() + (images + listOfNotNull(Soundtrack.firstCover(context, root))).map { it.path } + } else SoundtrackCollections.tracksOf(id).map { it.cover } + return paths.filter { it.isNotEmpty() && File(it).isFile }.distinct().map { AddedGameArt.Option(AddedGameArt.FOLDER, it, it) } + } + + fun choose(context: Context, id: Int, option: AddedGameArt.Option): Boolean { + val folder = dir(context, id) + val fresh = AddedGameArt.storeNew(folder, AddedGameArt.Slot.COVER, option) ?: return false + AddedGameArt.dropOlder(folder, AddedGameArt.Slot.COVER, fresh) + sourceFile(context, id).writeText(option.group + "|" + option.full) + return true + } + + fun reset(context: Context, id: Int) { + chosen(context, id)?.delete() + sourceFile(context, id).delete() + } + + fun describe(context: Context, id: Int, root: File? = null): List { + val own = chosen(context, id) + val state = if (own != null) AddedGameArt.SlotState(AddedGameArt.Slot.COVER, own, AddedGameArt.FILE, true) + else { + val auto = if (root != null) Soundtrack.firstCover(context, root) else SoundtrackCollections.autoCover(id) + AddedGameArt.SlotState(AddedGameArt.Slot.COVER, auto, if (auto != null) AddedGameArt.FOLDER else AddedGameArt.AUTO, false) + } + return listOf(state) + } + + fun clear(context: Context, id: Int) { + dir(context, id).deleteRecursively() + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/frontend/SoundtrackCollections.kt b/app/src/main/java/com/droiddeck/launcher/frontend/SoundtrackCollections.kt new file mode 100644 index 0000000000..d680ae0709 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/frontend/SoundtrackCollections.kt @@ -0,0 +1,191 @@ +package com.droiddeck.launcher.frontend + +import android.content.Context +import androidx.compose.runtime.mutableStateOf +import org.json.JSONArray +import org.json.JSONObject +import java.io.File +import java.util.concurrent.Executors + +object SoundtrackCollections { + const val FAVORITES_ID = 2_000_000_000 + + class TrackRef(val path: String, val title: String, val artist: String, val album: String, val durationMs: Long, val cover: String = "") + class Collection(val id: Int, val name: String, val tracks: List) + class Snapshot(val favorites: List, val collections: List) + + private val state = mutableStateOf(Snapshot(emptyList(), emptyList())) + private var loaded = false + private val writer = Executors.newSingleThreadExecutor { r -> Thread(r, "soundtrack-collections").apply { isDaemon = true } } + + val snapshot: Snapshot get() = state.value + + private fun file(context: Context) = File(context.filesDir, "soundtrack-collections.json") + + internal fun toggled(list: List, ref: TrackRef): List = + if (list.any { it.path == ref.path }) list.filterNot { it.path == ref.path } else list + ref + + internal fun merged(list: List, add: List): List { + val have = list.mapTo(HashSet()) { it.path } + return list + add.filter { have.add(it.path) } + } + + internal fun cleanName(raw: String): String = raw.trim().replace(Regex("\\s+"), " ") + + internal fun nameTaken(collections: List, name: String, except: Int? = null): Boolean = + collections.any { it.id != except && it.name.equals(name, ignoreCase = true) } + + internal fun nextId(collections: List): Int = + (collections.maxOfOrNull { it.id } ?: FAVORITES_ID).coerceAtLeast(FAVORITES_ID) + 1 + + private fun encode(s: Snapshot): String { + fun refs(list: List) = JSONArray().also { array -> + list.forEach { + array.put( + JSONObject().put("path", it.path).put("title", it.title).put("artist", it.artist).put("album", it.album) + .put("duration", it.durationMs).put("cover", it.cover), + ) + } + } + val collections = JSONArray() + s.collections.forEach { collections.put(JSONObject().put("id", it.id).put("name", it.name).put("tracks", refs(it.tracks))) } + return JSONObject().put("favorites", refs(s.favorites)).put("collections", collections).toString() + } + + private fun decode(text: String): Snapshot { + fun refs(array: JSONArray?): List = if (array == null) emptyList() else List(array.length()) { i -> + array.getJSONObject(i).let { + TrackRef(it.getString("path"), it.optString("title"), it.optString("artist"), it.optString("album"), it.optLong("duration"), it.optString("cover")) + } + } + val root = JSONObject(text) + val collections = root.optJSONArray("collections") + return Snapshot( + refs(root.optJSONArray("favorites")), + if (collections == null) emptyList() else List(collections.length()) { i -> + collections.getJSONObject(i).let { Collection(it.getInt("id"), it.getString("name"), refs(it.optJSONArray("tracks"))) } + }, + ) + } + + @Synchronized + fun load(context: Context) { + if (loaded) return + loaded = true + val f = file(context) + if (f.isFile) runCatching { state.value = decode(f.readText()) } + } + + private fun commit(context: Context, next: Snapshot) { + state.value = next + val f = file(context) + val json = encode(next) + writer.execute { + runCatching { + val tmp = File(f.path + ".tmp") + tmp.writeText(json) + if (!tmp.renameTo(f)) tmp.delete() + } + } + } + + fun tracksOf(id: Int): List = + if (id == FAVORITES_ID) snapshot.favorites else snapshot.collections.firstOrNull { it.id == id }?.tracks.orEmpty() + + fun isFavorite(path: String): Boolean = snapshot.favorites.any { it.path == path } + + @Synchronized + fun toggleFavorite(context: Context, ref: TrackRef) { + load(context) + val s = snapshot + commit(context, Snapshot(toggled(s.favorites, ref), s.collections)) + } + + @Synchronized + fun create(context: Context, rawName: String, tracks: List): Int? { + load(context) + val s = snapshot + val name = cleanName(rawName) + if (name.isEmpty() || nameTaken(s.collections, name)) return null + val id = nextId(s.collections) + commit(context, Snapshot(s.favorites, s.collections + Collection(id, name, merged(emptyList(), tracks)))) + return id + } + + @Synchronized + fun rename(context: Context, id: Int, rawName: String): Boolean { + load(context) + val s = snapshot + val name = cleanName(rawName) + if (id == FAVORITES_ID || name.isEmpty() || nameTaken(s.collections, name, id)) return false + commit(context, Snapshot(s.favorites, s.collections.map { if (it.id == id) Collection(id, name, it.tracks) else it })) + return true + } + + @Synchronized + fun delete(context: Context, id: Int) { + load(context) + val s = snapshot + if (id == FAVORITES_ID) return + commit(context, Snapshot(s.favorites, s.collections.filterNot { it.id == id })) + SoundtrackCollectionArt.clear(context, id) + } + + @Synchronized + fun add(context: Context, id: Int, tracks: List) { + load(context) + val s = snapshot + if (id == FAVORITES_ID) commit(context, Snapshot(merged(s.favorites, tracks), s.collections)) + else commit(context, Snapshot(s.favorites, s.collections.map { if (it.id == id) Collection(id, it.name, merged(it.tracks, tracks)) else it })) + } + + @Synchronized + fun remove(context: Context, id: Int, paths: Set) { + load(context) + val s = snapshot + if (id == FAVORITES_ID) commit(context, Snapshot(s.favorites.filterNot { it.path in paths }, s.collections)) + else commit(context, Snapshot(s.favorites, s.collections.map { if (it.id == id) Collection(id, it.name, it.tracks.filterNot { t -> t.path in paths }) else it })) + } + + @Synchronized + fun reorder(context: Context, id: Int, ordered: List) { + load(context) + val s = snapshot + fun arrange(list: List): List { + val byPath = list.associateBy { it.path } + val placed = ordered.mapNotNull { byPath[it] } + val named = ordered.toSet() + val rest = list.filter { it.path !in named } + return placed + rest + } + if (id == FAVORITES_ID) commit(context, Snapshot(arrange(s.favorites), s.collections)) + else commit(context, Snapshot(s.favorites, s.collections.map { if (it.id == id) Collection(id, it.name, arrange(it.tracks)) else it })) + } + + @Synchronized + fun refresh() { + state.value = Snapshot(state.value.favorites, state.value.collections) + } + + internal fun autoCover(id: Int): File? = coverOf(tracksOf(id)) + + private fun coverOf(tracks: List): File? = + tracks.firstNotNullOfOrNull { t -> t.cover.takeIf { it.isNotEmpty() }?.let { File(it) }?.takeIf { it.isFile } } + + private fun game(context: Context, id: Int, name: String, tracks: List): Library.SteamGame = Library.SteamGame( + appId = id, name = name, art = SoundtrackCollectionArt.chosen(context, id) ?: coverOf(tracks), library = Library.ADDED, gameId = id.toLong(), + source = Library.SOURCE_COLLECTION, soundtrack = true, + ) + + fun games(context: Context, favoritesLabel: String): List { + val s = snapshot + return listOf(game(context, FAVORITES_ID, favoritesLabel, s.favorites)) + s.collections.map { game(context, it.id, it.name, it.tracks) } + } + + fun album(context: Context, id: Int): Soundtrack.Album { + val tracks = tracksOf(id).filter { File(it.path).isFile }.mapIndexed { i, t -> + Soundtrack.Track(File(t.path), t.title, 1, i + 1, t.durationMs, t.artist) + } + return Soundtrack.Album(mapOf(1 to tracks), "", SoundtrackCollectionArt.chosen(context, id)) + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/frontend/SoundtrackIndex.kt b/app/src/main/java/com/droiddeck/launcher/frontend/SoundtrackIndex.kt new file mode 100644 index 0000000000..8da6a884df --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/frontend/SoundtrackIndex.kt @@ -0,0 +1,32 @@ +package com.droiddeck.launcher.frontend + +import android.content.Context + +object SoundtrackIndex { + class Hit(val ref: SoundtrackCollections.TrackRef, val game: Library.SteamGame) + + private var cacheKey = "" + private var cache: List = emptyList() + + private fun fingerprint(dir: java.io.File?): Long = + if (dir == null) 0L else Soundtrack.audioFiles(dir).fold(17L) { h, f -> 31 * (31 * (31 * h + f.path.hashCode()) + f.length()) + f.lastModified() } + + fun build(context: Context, games: List): List { + val roots = games.filter { it.gameFiles != null } + val key = roots.joinToString("|") { "${it.appId}:${it.gameFiles?.path}:${it.art?.path}:${fingerprint(it.gameFiles)}" } + synchronized(this) { if (key == cacheKey) return cache } + val hits = roots.flatMap { g -> + val dir = g.gameFiles ?: return@flatMap emptyList() + val album = Soundtrack.load(context, dir, g.art) + val cover = (g.art ?: album.cover)?.path.orEmpty() + album.tracks.map { t -> + Hit(SoundtrackCollections.TrackRef(t.file.path, t.title, t.artist.ifBlank { album.artist }, g.name, t.durationMs, cover), g) + } + } + synchronized(this) { + cacheKey = key + cache = hits + } + return hits + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/frontend/SoundtrackOrder.kt b/app/src/main/java/com/droiddeck/launcher/frontend/SoundtrackOrder.kt new file mode 100644 index 0000000000..a8018825ce --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/frontend/SoundtrackOrder.kt @@ -0,0 +1,67 @@ +package com.droiddeck.launcher.frontend + +import android.content.Context +import androidx.compose.runtime.mutableIntStateOf +import org.json.JSONArray +import org.json.JSONObject +import java.io.File +import java.util.concurrent.Executors + +object SoundtrackOrder { + private val changes = mutableIntStateOf(0) + private var cache: Map>? = null + private val writer = Executors.newSingleThreadExecutor { r -> Thread(r, "soundtrack-order").apply { isDaemon = true } } + + val version: Int get() = changes.intValue + + private fun file(context: Context) = File(context.filesDir, "soundtrack-order.json") + + @Synchronized + private fun read(context: Context): Map> { + cache?.let { return it } + val out = HashMap>() + val f = file(context) + if (f.isFile) runCatching { + val json = JSONObject(f.readText()) + for (key in json.keys()) { + val array = json.getJSONArray(key) + out[key] = List(array.length()) { array.getString(it) } + } + } + cache = out + return out + } + + @Synchronized + fun set(context: Context, root: File, paths: List) { + val next = HashMap(read(context)) + next[root.path] = paths + cache = next + val body = JSONObject().also { json -> next.forEach { (k, v) -> json.put(k, JSONArray(v)) } }.toString() + val target = file(context) + writer.execute { + val tmp = File(target.path + ".tmp") + runCatching { + tmp.writeText(body) + if (!tmp.renameTo(target)) tmp.delete() + } + } + changes.intValue++ + } + + internal fun ordered(disc: Map>, order: List): Map> { + if (order.isEmpty()) return disc + val index = HashMap() + order.forEachIndexed { i, p -> index.putIfAbsent(p, i) } + return disc.mapValues { (_, list) -> + list.sortedBy { index[it.file.path] ?: Int.MAX_VALUE }.mapIndexed { i, t -> + Soundtrack.Track(t.file, t.title, t.disc, i + 1, t.durationMs, t.artist, t.discLabel) + } + } + } + + fun apply(context: Context, root: File, disc: Map>): Map> { + val order = read(context)[root.path] ?: return disc + return ordered(disc, order) + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/frontend/SoundtrackShortcuts.kt b/app/src/main/java/com/droiddeck/launcher/frontend/SoundtrackShortcuts.kt new file mode 100644 index 0000000000..c85940cd16 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/frontend/SoundtrackShortcuts.kt @@ -0,0 +1,41 @@ +package com.droiddeck.launcher.frontend + +import android.app.Activity +import android.content.Context +import android.content.Intent +import android.content.pm.ShortcutInfo +import android.content.pm.ShortcutManager +import android.graphics.drawable.Icon +import android.net.Uri +import android.widget.Toast +import com.droiddeck.launcher.FrontEndActivity +import com.droiddeck.launcher.LauncherIcon +import com.droiddeck.launcher.R + +object SoundtrackShortcuts { + private val linkPattern = Regex("droiddeck://soundtrack/(-?[0-9]{1,11})") + + fun uri(appId: Int): String = "droiddeck://soundtrack/$appId" + + fun parse(link: String?): Int? = link?.let { linkPattern.matchEntire(it)?.groupValues?.get(1)?.toIntOrNull() } + + fun read(intent: Intent): Int? = if (intent.action == Intent.ACTION_VIEW) parse(intent.dataString) else null + + private fun info(context: Context, game: Library.SteamGame): ShortcutInfo { + val name = game.name.ifBlank { context.getString(R.string.app_name) } + val icon = GameShortcuts.iconBitmap(game)?.let(Icon::createWithBitmap) ?: Icon.createWithResource(context, R.mipmap.ic_launcher) + val intent = Intent(Intent.ACTION_VIEW, Uri.parse(uri(game.appId)), context, FrontEndActivity::class.java) + .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP) + return ShortcutInfo.Builder(context, "soundtrack:${game.appId}") + .setActivity(LauncherIcon.activity(context)) + .setShortLabel(name.take(40)).setLongLabel(name).setIcon(icon).setIntent(intent).build() + } + + fun pin(activity: Activity, game: Library.SteamGame) { + val manager = activity.getSystemService(ShortcutManager::class.java) + val requested = runCatching { + manager.isRequestPinShortcutSupported && manager.requestPinShortcut(info(activity, game), null) + }.getOrDefault(false) + if (!requested) Toast.makeText(activity, R.string.game_shortcut_unsupported, Toast.LENGTH_LONG).show() + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/frontend/SoundtrackTracks.kt b/app/src/main/java/com/droiddeck/launcher/frontend/SoundtrackTracks.kt new file mode 100644 index 0000000000..744614710d --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/frontend/SoundtrackTracks.kt @@ -0,0 +1,30 @@ +package com.droiddeck.launcher.frontend + +object SoundtrackTracks { + enum class Sort { DEFAULT, TITLE_ASC, TITLE_DESC, LONGEST, SHORTEST } + + fun sort(items: List, sort: Sort, title: (T) -> String, duration: (T) -> Long): List = when (sort) { + Sort.DEFAULT -> items + Sort.TITLE_ASC -> items.sortedWith(compareBy(String.CASE_INSENSITIVE_ORDER, title)) + Sort.TITLE_DESC -> items.sortedWith(compareByDescending(String.CASE_INSENSITIVE_ORDER, title)) + Sort.LONGEST -> items.sortedByDescending(duration) + Sort.SHORTEST -> items.sortedBy(duration) + } + + fun matches(query: String, vararg fields: String): Boolean { + val words = query.trim().lowercase().split(' ').filter { it.isNotEmpty() } + if (words.isEmpty()) return true + val haystack = fields.map { it.lowercase() } + return words.all { word -> haystack.any { it.contains(word) } } + } + + fun rank(query: String, title: String): Int { + val q = query.trim().lowercase() + val t = title.lowercase() + return when { + t == q -> 0 + t.startsWith(q) -> 1 + else -> 2 + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/frontend/SteamGameArt.kt b/app/src/main/java/com/droiddeck/launcher/frontend/SteamGameArt.kt index 25a3cb8fb5..d7a6522742 100644 --- a/app/src/main/java/com/droiddeck/launcher/frontend/SteamGameArt.kt +++ b/app/src/main/java/com/droiddeck/launcher/frontend/SteamGameArt.kt @@ -24,11 +24,7 @@ object SteamGameArt { val icon = chosenFile(context, game.appId, AddedGameArt.Slot.ICON) val logo = chosenFile(context, game.appId, AddedGameArt.Slot.LOGO) if (cover == null && hero == null && icon == null && logo == null) return game - return Library.SteamGame( - game.appId, game.name, cover ?: game.art, game.library, game.gameId, - hero ?: game.hero, game.lastPlayed, game.gameFiles, game.protonPrefix, icon ?: game.icon, game.source, game.storeId, - logo ?: game.logo, - ) + return game.withArt(cover ?: game.art, hero ?: game.hero, icon ?: game.icon, logo ?: game.logo) } fun chosenSource(context: Context, appId: Int, slot: AddedGameArt.Slot): Pair { diff --git a/app/src/main/java/com/droiddeck/launcher/gpu/FrameGen.kt b/app/src/main/java/com/droiddeck/launcher/gpu/FrameGen.kt index c31cd348e8..1623c10106 100644 --- a/app/src/main/java/com/droiddeck/launcher/gpu/FrameGen.kt +++ b/app/src/main/java/com/droiddeck/launcher/gpu/FrameGen.kt @@ -28,12 +28,38 @@ object FrameGen { fun engine(context: Context): String = mode(context).engine - fun mode(context: Context): Mode { + fun mode(context: Context): Mode = mode(context, null) + + fun mode(context: Context, appId: String?): Mode { val prefs = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE) - val engine = prefs.getString("engine", ENGINE_OFF).let { if (it == LEGACY_ENGINE_WINFG) ENGINE_DDFG else it ?: ENGINE_OFF } - val target = prefs.getInt("target", 0) + val gamePrefix = appId?.takeIf { it.isNotBlank() }?.let { "game.$it." } + ?.takeIf { prefs.contains(it + "engine") } ?: "" + val engine = prefs.getString(gamePrefix + "engine", ENGINE_OFF) + .let { if (it == LEGACY_ENGINE_WINFG) ENGINE_DDFG else it ?: ENGINE_OFF } + val target = prefs.getInt(gamePrefix + "target", 0) if (engine == ENGINE_LSFG && target in ADAPTIVE_TARGETS) return Mode(engine, target = target) - return Mode(engine, prefs.getInt("multiplier", 2).coerceIn(2, 4)) + return Mode(engine, prefs.getInt(gamePrefix + "multiplier", 2).coerceIn(2, 4)) + } + + fun hasGameOverride(context: Context, appId: String): Boolean = + context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).contains("game.$appId.engine") + + fun setForGame(context: Context, appId: String, mode: Mode) { + val prefix = "game.$appId." + context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit() + .putString(prefix + "engine", mode.engine) + .putInt(prefix + "multiplier", mode.multiplier) + .putInt(prefix + "target", mode.target) + .apply() + } + + fun clearGame(context: Context, appId: String) { + val prefix = "game.$appId." + context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit() + .remove(prefix + "engine") + .remove(prefix + "multiplier") + .remove(prefix + "target") + .apply() } fun set(context: Context, mode: Mode) { @@ -41,6 +67,11 @@ object FrameGen { .putString("engine", mode.engine).putInt("multiplier", mode.multiplier).putInt("target", mode.target).apply() } + fun clearGlobal(context: Context) { + context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit() + .remove("engine").remove("multiplier").remove("target").apply() + } + fun label(context: Context): String = label(context, mode(context)) fun label(context: Context, mode: Mode): String = when { @@ -50,14 +81,32 @@ object FrameGen { else -> context.getString(R.string.frame_gen_off) } - fun apply(context: Context, refreshHz: Float): String? = apply(context, mode(context), refreshHz) + data class PreparedApply internal constructor( + val mode: Mode, + internal val lsfgStatus: Int? = null, + internal val lsfgCachePath: String? = null, + ) - fun apply(context: Context, mode: Mode, refreshHz: Float): String? { + fun prepareApply(context: Context, mode: Mode): PreparedApply { + if (mode.engine != ENGINE_LSFG) return PreparedApply(mode) + val status = Lossless.sync(context) + val cachePath = Lossless.cacheFile(context)?.absolutePath + return PreparedApply(mode, status, cachePath) + } + + fun apply(context: Context, refreshHz: Float): String? = + apply(context, mode(context), refreshHz) + + fun apply(context: Context, mode: Mode, refreshHz: Float): String? = + applyPrepared(context, prepareApply(context, mode), refreshHz) + + fun applyPrepared(context: Context, prepared: PreparedApply, refreshHz: Float): String? { + val mode = prepared.mode when (mode.engine) { ENGINE_LSFG -> { - val status = Lossless.sync(context) - val cache = Lossless.cacheFile(context) - if (status != LsfgNative.STATUS_OK || cache == null) { + val status = prepared.lsfgStatus ?: LsfgNative.STATUS_NOT_INSTALLED + val cachePath = prepared.lsfgCachePath + if (status != LsfgNative.STATUS_OK || cachePath == null) { WaylandCompositor.nativeSetFrameGenArmed(false, 0, 0) val problem = context.getString( if (status == LsfgNative.STATUS_NOT_INSTALLED) R.string.lsfg_problem_missing else R.string.lsfg_problem_failed, @@ -66,7 +115,7 @@ object FrameGen { return problem } WaylandCompositor.nativeSetFrameGenEngine(WaylandCompositor.FG_ENGINE_LSFG) - WaylandCompositor.nativeSetLsfgCachePath(cache.absolutePath) + WaylandCompositor.nativeSetLsfgCachePath(cachePath) WaylandCompositor.nativeSetFrameGenTuning(FLOW_SCALE_LSFG, refreshHz) WaylandCompositor.nativeSetFrameGenArmed(true, mode.multiplier, mode.target) } diff --git a/app/src/main/java/com/droiddeck/launcher/hud/DroidDeckHudHost.kt b/app/src/main/java/com/droiddeck/launcher/hud/DroidDeckHudHost.kt index f612477f33..e2ddefc692 100644 --- a/app/src/main/java/com/droiddeck/launcher/hud/DroidDeckHudHost.kt +++ b/app/src/main/java/com/droiddeck/launcher/hud/DroidDeckHudHost.kt @@ -10,11 +10,9 @@ import android.view.View import android.view.animation.PathInterpolator import android.view.ViewGroup import android.widget.FrameLayout -import com.droiddeck.launcher.gpu.FrameGen import com.droiddeck.launcher.gpu.GpuInfo import com.droiddeck.launcher.runtime.LinuxRuntime import com.droiddeck.launcher.session.SessionPrefs -import com.droiddeck.launcher.session.SessionService import com.droiddeck.launcher.session.SessionState import com.droiddeck.launcher.ui.Motion import com.droiddeck.launcher.wayland.WaylandCompositor @@ -24,7 +22,7 @@ import kotlin.math.roundToInt class DroidDeckHudHost(context: Context) { private val context = context.applicationContext private val handler = Handler(Looper.getMainLooper()) - private val feed = GameFrameFeed(File(LinuxRuntime.rootDir(this.context), HudFrames.PATH)) + private val feed = GameFrameFeed.forRoot(LinuxRuntime.rootDir(this.context)) private val readings = MangoReadings(File(this.context.filesDir, "session"), LinuxRuntime.rootDir(this.context)) private var view: DroidDeckHudView? = null private var parent: ViewGroup? = null @@ -39,6 +37,8 @@ class DroidDeckHudHost(context: Context) { private var snapping = false private var previewFade: ValueAnimator? = null private var flingX = 0f + private var flingY = 0f + private var throwSpring: com.droiddeck.launcher.ui.FlingSpring? = null private var engine = "" private var gpuName = "" private var protonPid = 0 @@ -95,18 +95,22 @@ class DroidDeckHudHost(context: Context) { stopMotion(hud) shrinkPastEdge(hud, rawX, rawY) } - hud.setOnFlungListener { vx, _ -> flingX = vx } + hud.setOnFlungListener { vx, vy -> flingX = vx; flingY = vy } hud.setOnTabDraggedListener { x, y -> dragTab(hud, x, y) } hud.setOnTabDroppedListener { dropTab(hud) } hud.setOnTabDragCancelledListener { snapping = false; keepOnScreen(hud) } hud.setOnMovedListener { x, y -> wantX = x; wantY = y val vx = flingX + val vy = flingY flingX = 0f - dockEdgeFor(hud)?.let { edge -> setDock(hud, edge); return@setOnMovedListener } + flingY = 0f + // A throw only carries the strip into its tab; a floating HUD flung across goes to the other side. + val coast = hud.isStrip + dockEdgeFor(hud, if (coast) vx else 0f, if (coast) vy else 0f)?.let { edge -> setDock(hud, edge); return@setOnMovedListener } stopMotion(hud) fadeDockPreview(hud) - if (snaps && !hud.isStrip) { snapToAnchor(hud, vx); return@setOnMovedListener } + if (snaps && !hud.isStrip) { snapToAnchor(hud, vx, vy); return@setOnMovedListener } val fromX = hud.x; val fromY = hud.y keepOnScreen(hud) wantX = hud.x; wantY = hud.y @@ -179,9 +183,8 @@ class DroidDeckHudHost(context: Context) { private fun applyShown() { if (!running) return val show = !hidden && !backgrounded - val visible = show && SessionState.mode != SessionService.MODE_DESKTOP - view?.visibility = if (visible) View.VISIBLE else View.GONE - showing = visible + view?.visibility = if (show) View.VISIBLE else View.GONE + showing = show if (show != polling) { polling = show if (show) Choreographer.getInstance().postFrameCallback(frameCallback) @@ -238,28 +241,36 @@ class DroidDeckHudHost(context: Context) { } private fun presentedFps(): Float { - if (FrameGen.mode(context).engine == FrameGen.ENGINE_OFF) return 0f - val stats = runCatching { WaylandCompositor.nativeFrameGenStats() }.getOrNull() ?: return 0f + if (!runCatching { WaylandCompositor.nativeFrameGenActive() } + .getOrDefault(false)) return 0f + + val stats = runCatching { + WaylandCompositor.nativeFrameGenStats() + }.getOrNull() ?: return 0f + return if (stats.size > 3 && stats[3] > 1f) stats[3] else 0f } - private fun dockEdgeFor(v: View): DroidDeckHudDock? { - val over = overhang(v) ?: return null + /** The edge the HUD tucks into: one it hangs far enough over, or would once a throw at [vx], [vy] coasts out. */ + private fun dockEdgeFor(v: View, vx: Float = 0f, vy: Float = 0f): DroidDeckHudDock? { + val over = overhang(v, vx * com.droiddeck.launcher.ui.EdgeFling.COAST_S, vy * com.droiddeck.launcher.ui.EdgeFling.COAST_S) ?: return null return over.key.takeIf { over.value >= DOCK_OVERHANG } } - private fun overhang(v: View): Map.Entry? { + private fun overhang(v: View, dx: Float = 0f, dy: Float = 0f): Map.Entry? { val p = v.parent as? View ?: return null if (p.width <= 0 || p.height <= 0 || v.width <= 0 || v.height <= 0) return null val strip = (v as? DroidDeckHudView)?.isStrip == true val density = v.resources.displayMetrics.density val w = if (strip) minOf(v.width.toFloat(), STRIP_PULL_ACROSS_DP * density) else v.width.toFloat() val h = if (strip) maxOf(v.height.toFloat(), STRIP_PULL_OFF_DP * density) else v.height.toFloat() + val x = v.x + dx + val y = v.y + dy return mapOf( - DroidDeckHudDock.LEFT to -v.x / w, - DroidDeckHudDock.RIGHT to (v.x + v.width - p.width) / w, - DroidDeckHudDock.TOP to -v.y / h, - DroidDeckHudDock.BOTTOM to (v.y + v.height - p.height) / h, + DroidDeckHudDock.LEFT to -x / w, + DroidDeckHudDock.RIGHT to (x + v.width - p.width) / w, + DroidDeckHudDock.TOP to -y / h, + DroidDeckHudDock.BOTTOM to (y + v.height - p.height) / h, ).maxByOrNull { it.value } } @@ -294,6 +305,7 @@ class DroidDeckHudHost(context: Context) { } private fun stopMotion(hud: DroidDeckHudView) { + throwSpring?.cancel() hud.animate().setUpdateListener(null) hud.animate().cancel() } @@ -323,23 +335,21 @@ class DroidDeckHudHost(context: Context) { } } - private fun snapToAnchor(hud: DroidDeckHudView, vx: Float) { + /** Sends the HUD to a side the way a chat head goes: by where the throw would carry it, springing on from its speed. */ + private fun snapToAnchor(hud: DroidDeckHudView, vx: Float, vy: Float) { val p = hud.parent as? View ?: return val maxX = (p.width - hud.width).toFloat().coerceAtLeast(0f) val maxY = (p.height - hud.height).toFloat().coerceAtLeast(0f) - anchorX = if (hud.x + vx * FLING_REACH_S < maxX / 2f) 0f else 1f + val right = com.droiddeck.launcher.ui.EdgeFling.toRight(hud.x + hud.width / 2f, p.width.toFloat(), vx, context.resources.displayMetrics.density) + anchorX = if (right) 1f else 0f wantX = anchorX * maxX - wantY = hud.y.coerceIn(0f, maxY) + wantY = com.droiddeck.launcher.ui.EdgeFling.restY(hud.y, vy, 0f, maxY) SessionPrefs.setDroidDeckHudPosition(context, wantX, wantY) stopMotion(hud) - if (Motion.scale == 0f) { - hud.scaleX = 1f; hud.scaleY = 1f - hud.x = wantX; hud.y = wantY - return - } + hud.scaleX = 1f; hud.scaleY = 1f snapping = true - hud.animate().x(wantX).y(wantY).scaleX(1f).scaleY(1f).setDuration(Motion.ms(260).toLong()).setInterpolator(EASE) - .withEndAction { snapping = false; keepOnScreen(hud) }.start() + val spring = throwSpring ?: com.droiddeck.launcher.ui.FlingSpring { sx, sy -> hud.x = sx; hud.y = sy }.also { throwSpring = it } + spring.start(hud.x, hud.y, vx, vy, wantX, wantY) { snapping = false; keepOnScreen(hud) } } private fun shrinkPastEdge(hud: DroidDeckHudView, rawX: Float, rawY: Float) { @@ -496,10 +506,9 @@ class DroidDeckHudHost(context: Context) { companion object { private const val DOCK_OVERHANG = 0.4f - private const val FLING_REACH_S = 0.18f private const val PREVIEW_FROM = 0.55f - private const val STRIP_PULL_ACROSS_DP = 600f - private const val STRIP_PULL_OFF_DP = 150f + private const val STRIP_PULL_ACROSS_DP = 360f + private const val STRIP_PULL_OFF_DP = 100f private const val EXPAND_FADE = 0.5f private val EASE = PathInterpolator(0.2f, 0.8f, 0.2f, 1f) diff --git a/app/src/main/java/com/droiddeck/launcher/hud/GameFrames.kt b/app/src/main/java/com/droiddeck/launcher/hud/GameFrames.kt index 2aba209ded..db5f74e4cf 100644 --- a/app/src/main/java/com/droiddeck/launcher/hud/GameFrames.kt +++ b/app/src/main/java/com/droiddeck/launcher/hud/GameFrames.kt @@ -1,6 +1,7 @@ package com.droiddeck.launcher.hud import java.io.File +import java.io.RandomAccessFile import kotlin.math.roundToInt internal class FrameStats { @@ -159,7 +160,11 @@ internal class FrameStats { } } -internal class GameFrameFeed(private val file: File, val stats: FrameStats = FrameStats()) { +internal class GameFrameFeed( + private val file: File, + val stats: FrameStats = FrameStats(), + private val clockControl: File? = null, +) { private var handle = 0L private var nextOpenNs = 0L private var lastRingFrameNs = 0L @@ -171,6 +176,8 @@ internal class GameFrameFeed(private val file: File, val stats: FrameStats = Fra private var lastCompositorNs = 0L @Volatile private var compositorFrames = 0L private var seenCompositorFrames = 0L + private var clockShiftNs = 0L + private var clockShiftReadNs = Long.MIN_VALUE @Volatile var engine = "" private set @@ -199,6 +206,9 @@ internal class GameFrameFeed(private val file: File, val stats: FrameStats = Fra } val n = HudFrames.nativePoll(handle, frametimes, times) if (n > 0) { + var shift = guestClockShift(nowNs, SHIFT_NS) + if (nowNs - (times[n - 1] + shift) > LIVE_NS) shift = guestClockShift(nowNs, SHIFT_RECHECK_NS) + for (i in 0 until n) times[i] += shift if (!fromGamescope) { stats.reset() fromGamescope = true @@ -216,6 +226,16 @@ internal class GameFrameFeed(private val file: File, val stats: FrameStats = Fra return n > 0 || compositorAdded } + internal fun guestClockShift(nowNs: Long, maxAgeNs: Long): Long { + val control = clockControl ?: return 0L + if (clockShiftReadNs != Long.MIN_VALUE && nowNs - clockShiftReadNs < maxAgeNs) return clockShiftNs + clockShiftReadNs = nowNs + clockShiftNs = runCatching { + RandomAccessFile(control, "r").use { if (it.length() < Long.SIZE_BYTES) 0L else java.lang.Long.reverseBytes(it.readLong()) } + }.getOrDefault(0L).coerceAtLeast(0L) + return clockShiftNs + } + fun onCompositorFrame(nowNs: Long) { if (fromGamescope) { lastCompositorNs = 0L @@ -253,6 +273,11 @@ internal class GameFrameFeed(private val file: File, val stats: FrameStats = Fra private const val LIVE_NS = 2_000_000_000L private const val STALE_NS = 5_000_000_000L private const val INFO_NS = 500_000_000L + private const val SHIFT_NS = 1_000_000_000L + private const val SHIFT_RECHECK_NS = 100_000_000L + private const val CLOCK_CONTROL_PATH = "tmp/.bl-clock" + + fun forRoot(root: File) = GameFrameFeed(File(root, HudFrames.PATH), clockControl = File(root, CLOCK_CONTROL_PATH)) fun engineLabel(name: String): String = when (name) { "DXVK" -> "DXVK" diff --git a/app/src/main/java/com/droiddeck/launcher/hud/HudLockController.java b/app/src/main/java/com/droiddeck/launcher/hud/HudLockController.java index 98c34df7ce..b4c1cfc7ea 100644 --- a/app/src/main/java/com/droiddeck/launcher/hud/HudLockController.java +++ b/app/src/main/java/com/droiddeck/launcher/hud/HudLockController.java @@ -50,6 +50,7 @@ public class HudLockController { private final Callbacks cb; private final GestureDetector detector; private final ScaleGestureDetector scaleDetector; + private final android.view.VelocityTracker velocity = android.view.VelocityTracker.obtain(); private boolean locked = false; @@ -86,8 +87,18 @@ public class HudLockController { public boolean onTouchEvent(MotionEvent event) { scaleDetector.onTouchEvent(event); detector.onTouchEvent(event); + // The HUD moves under the finger, so the throw is measured on the screen, not in the HUD. + MotionEvent onScreen = MotionEvent.obtain(event); + onScreen.setLocation(event.getRawX(), event.getRawY()); + if (event.getActionMasked() == MotionEvent.ACTION_DOWN) velocity.clear(); + velocity.addMovement(onScreen); + onScreen.recycle(); int action = event.getActionMasked(); if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL) { + if (dragging && !locked && !pinched && action == MotionEvent.ACTION_UP) { + velocity.computeCurrentVelocity(1000); + cb.onFlung(velocity.getXVelocity(), velocity.getYVelocity()); + } if (dragging && !locked) cb.onMoved(view.getX(), view.getY()); dragging = false; } @@ -124,12 +135,6 @@ public class HudLockController { return true; } - @Override - public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { - if (dragging && !locked && !pinched) cb.onFlung(velocityX, velocityY); - return true; - } - @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { if (pinched) return true; diff --git a/app/src/main/java/com/droiddeck/launcher/hud/HudMetrics.java b/app/src/main/java/com/droiddeck/launcher/hud/HudMetrics.java index 51a4e42608..1dc5a39bcd 100644 --- a/app/src/main/java/com/droiddeck/launcher/hud/HudMetrics.java +++ b/app/src/main/java/com/droiddeck/launcher/hud/HudMetrics.java @@ -651,15 +651,10 @@ public class HudMetrics { return currentRawToAmps(raw); } - public Integer getCpuClockMhz() { - int cores = Runtime.getRuntime().availableProcessors(); - long maxKhz = 0; - for (int i = 0; i < cores; i++) { - Long cur = readLongFromLine("/sys/devices/system/cpu/cpu" + i + "/cpufreq/scaling_cur_freq"); - if (cur != null && cur > maxKhz) maxKhz = cur; - } - if (maxKhz <= 0) return null; - return (int) (maxKhz / 1000L); + static Integer fastestCoreMhz(int[] perCoreMhz) { + int max = 0; + for (int mhz : perCoreMhz) max = Math.max(max, mhz); + return max > 0 ? max : null; } private List gpuClockPathsCache = null; @@ -809,7 +804,8 @@ public class HudMetrics { if (mango != null) return mangoSnapshot(mango); Integer cpu = getCpuUsagePercent(); Integer gpu = getGpuUsagePercent(); - Integer cpuClk = getCpuClockMhz(); + int[] perCoreClk = getPerCoreClockMhz(); + Integer cpuClk = fastestCoreMhz(perCoreClk); Integer gpuClk = getGpuClockMhz(); Integer cpuTemp = getCpuTempC(); Integer gpuTemp = getGpuTempC(); @@ -829,7 +825,6 @@ public class HudMetrics { Battery battery = collectBattery(); int[] perCorePct = readPerCorePercent(); - int[] perCoreClk = getPerCoreClockMhz(); long[] swap = getSwapBytes(); long[] net = readNetRateBps(); @@ -850,24 +845,63 @@ public class HudMetrics { Battery battery = bat == null ? android : new Battery(bat.getWatts(), bat.getCharging(), bat.getPercent() != null ? bat.getPercent() : android.percent, android.tempC, android.runtimeText); long[] net = readNetRateBps(); - return new Snapshot(cpu != null ? cpu.getPercent() : null, m.gpuPercent(), getCpuClockMhz(), m.gpuClockMhz(), + int[] perCoreClk = getPerCoreClockMhz(); + return new Snapshot(cpu != null ? cpu.getPercent() : null, m.gpuPercent(), fastestCoreMhz(perCoreClk), m.gpuClockMhz(), m.cpuTempC(), m.gpuTempC(), used, total, total > 0 ? used * 100f / total : 0f, m.vramBytes(), battery, - cpu != null ? cpu.getPerCore() : new int[0], getPerCoreClockMhz(), + cpu != null ? cpu.getPerCore() : new int[0], perCoreClk, mem != null && mem.getSwapTotalBytes() > 0 ? mem.getSwapUsedBytes() : null, mem != null && mem.getSwapTotalBytes() > 0 ? mem.getSwapTotalBytes() : null, net == null ? null : net[0], net == null ? null : net[1]); } - public int[] getPerCoreClockMhz() { + private final java.util.Map lastTimeInState = new java.util.HashMap<>(); + + public synchronized int[] getPerCoreClockMhz() { int cores = Runtime.getRuntime().availableProcessors(); int[] out = new int[Math.max(0, cores)]; for (int i = 0; i < out.length; i++) { - Long cur = readLongFromLine("/sys/devices/system/cpu/cpu" + i + "/cpufreq/scaling_cur_freq"); - out[i] = (cur != null && cur > 0) ? (int) (cur / 1000L) : 0; + long[][] table = readTimeInState("/sys/devices/system/cpu/cpu" + i + "/cpufreq/stats/time_in_state"); + long khz = table == null ? -1L : averageKhz(lastTimeInState.put(i, table), table); + if (khz <= 0L) { + Long cur = readLongFromLine("/sys/devices/system/cpu/cpu" + i + "/cpufreq/scaling_cur_freq"); + khz = cur != null ? cur : 0L; + } + out[i] = khz > 0L ? (int) (khz / 1000L) : 0; } return out; } + static long averageKhz(long[][] before, long[][] after) { + if (before == null || after == null || !java.util.Arrays.equals(before[0], after[0])) return -1L; + long weighted = 0L, time = 0L; + for (int i = 0; i < after[0].length; i++) { + long dt = after[1][i] - before[1][i]; + if (dt <= 0L) continue; + weighted += after[0][i] * dt; + time += dt; + } + return time > 0L ? weighted / time : -1L; + } + + private static long[][] readTimeInState(String path) { + List rows = new ArrayList<>(); + try (BufferedReader r = new BufferedReader(new FileReader(path))) { + String line; + while ((line = r.readLine()) != null) { + String[] parts = line.trim().split("\\s+"); + if (parts.length < 2) continue; + try { rows.add(new long[] { Long.parseLong(parts[0]), Long.parseLong(parts[1]) }); } + catch (NumberFormatException ignored) {} + } + } catch (Exception e) { + return null; + } + if (rows.isEmpty()) return null; + long[][] table = new long[2][rows.size()]; + for (int i = 0; i < rows.size(); i++) { table[0][i] = rows.get(i)[0]; table[1][i] = rows.get(i)[1]; } + return table; + } + private long[] lastCoreTotal = null; private long[] lastCoreIdle = null; private static final int PER_CORE_STAT = 1, PER_CORE_ESTIMATE = 2; diff --git a/app/src/main/java/com/droiddeck/launcher/input/PadBridge.java b/app/src/main/java/com/droiddeck/launcher/input/PadBridge.java index c7dd27a271..c75602585c 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/PadBridge.java +++ b/app/src/main/java/com/droiddeck/launcher/input/PadBridge.java @@ -56,6 +56,7 @@ public final class PadBridge { private final FakeInputWriter[] playerWriters = new FakeInputWriter[SLOTS]; private final PadState[] playerStates = new PadState[SLOTS]; private final float[][] rawSticks = new float[SLOTS][4]; + private final boolean[][] keyTriggers = new boolean[SLOTS][2]; private final int[] retainedSticks = new int[SLOTS]; private final PadState effectiveState = new PadState(); private final PadState homeGuideReport = new PadState(); @@ -289,7 +290,10 @@ public final class PadBridge { } public static boolean isControllerKeyEvent(KeyEvent event) { - InputDevice device = event.getDevice(); + return isControllerKeyEvent(event, event.getDevice()); + } + + static boolean isControllerKeyEvent(KeyEvent event, InputDevice device) { if (device == null || device.isVirtual() || isSystemVirtualInputName(device.getName())) return false; if (KeyEvent.isGamepadButton(event.getKeyCode())) { return device.supportsSource(InputDevice.SOURCE_GAMEPAD) @@ -314,7 +318,10 @@ public final class PadBridge { } public static boolean isControllerMotionEvent(MotionEvent event) { - InputDevice device = event.getDevice(); + return isControllerMotionEvent(event, event.getDevice()); + } + + static boolean isControllerMotionEvent(MotionEvent event, InputDevice device) { return event.isFromSource(InputDevice.SOURCE_JOYSTICK) && device != null && !device.isVirtual() && !isSystemVirtualInputName(device.getName()) && (device.supportsSource(InputDevice.SOURCE_GAMEPAD) @@ -375,10 +382,11 @@ public final class PadBridge { } public synchronized boolean onKeyEvent(KeyEvent event) { - if (!isControllerKeyEvent(event) || excluded.test(event.getDeviceId())) return false; - int slot = slotFor(event.getDevice()); + InputDevice device = event.getDevice(); + if (!isControllerKeyEvent(event, device) || excluded.test(event.getDeviceId())) return false; + int slot = slotFor(device); if (slot < 0) return false; - int side = JoyCon.side(event.getDevice()); + int side = JoyCon.side(device); if (side >= 0 && partners[slot] != NO_CONTROLLER && JoyCon.isRail(side, event.getScanCode())) return true; long timing = InputTiming.begin(); PadState pad = stateFor(slot); @@ -400,18 +408,18 @@ public final class PadBridge { case KeyEvent.KEYCODE_HOME: case KeyEvent.KEYCODE_MOVE_HOME: pad.press(PadState.GUIDE, pressed); break; case KeyEvent.KEYCODE_BUTTON_Z: - if (isPrimary(event)) DeckControls.INSTANCE.setGrip(isNovaController(event.getDevice()) ? DeckControls.R4 : DeckControls.L4, pressed); + if (isPrimary(event)) DeckControls.INSTANCE.setGrip(isNovaController(device) ? DeckControls.R4 : DeckControls.L4, pressed); break; case KeyEvent.KEYCODE_BUTTON_C: - if (isPrimary(event)) DeckControls.INSTANCE.setGrip(isNovaController(event.getDevice()) ? DeckControls.L4 : DeckControls.R4, pressed); + if (isPrimary(event)) DeckControls.INSTANCE.setGrip(isNovaController(device) ? DeckControls.L4 : DeckControls.R4, pressed); break; case KeyEvent.KEYCODE_BUTTON_L2: pad.leftTrigger = keyTrigger(pad.leftTrigger, pressed, event.getRepeatCount(), - analogTrigger(event.getDevice(), MotionEvent.AXIS_LTRIGGER, MotionEvent.AXIS_BRAKE)); + analogTrigger(device, MotionEvent.AXIS_LTRIGGER, MotionEvent.AXIS_BRAKE), keyTriggers[slot], 0); break; case KeyEvent.KEYCODE_BUTTON_R2: pad.rightTrigger = keyTrigger(pad.rightTrigger, pressed, event.getRepeatCount(), - analogTrigger(event.getDevice(), MotionEvent.AXIS_RTRIGGER, MotionEvent.AXIS_GAS)); + analogTrigger(device, MotionEvent.AXIS_RTRIGGER, MotionEvent.AXIS_GAS), keyTriggers[slot], 1); break; case KeyEvent.KEYCODE_DPAD_UP: pad.up = pressed; break; case KeyEvent.KEYCODE_DPAD_RIGHT: pad.right = pressed; break; @@ -419,7 +427,7 @@ public final class PadBridge { case KeyEvent.KEYCODE_DPAD_LEFT: pad.left = pressed; break; default: return false; } - noteDevice(event.getDevice(), slot); + noteDevice(device, slot); if (pressed && event.getRepeatCount() == 0 && !event.isCanceled()) noteChordInput(slot); if (pressed) notePlayerInput(); statButtons++; @@ -471,6 +479,7 @@ public final class PadBridge { stateFor(slot).clear(); retainedSticks[slot] = 0; Arrays.fill(rawSticks[slot], 0f); + Arrays.fill(keyTriggers[slot], false); } private void mutateState(java.util.function.Consumer mutation) { @@ -489,16 +498,16 @@ public final class PadBridge { } public synchronized boolean onMotionEvent(MotionEvent event) { - if (!isControllerMotionEvent(event) || excluded.test(event.getDeviceId())) return false; + InputDevice device = event.getDevice(); + if (!isControllerMotionEvent(event, device) || excluded.test(event.getDeviceId())) return false; if (event.getAction() != MotionEvent.ACTION_MOVE) return false; - int slot = slotFor(event.getDevice()); + int slot = slotFor(device); if (slot < 0) return false; long timing = InputTiming.begin(); PadState pad = stateFor(slot); - noteDevice(event.getDevice(), slot); + noteDevice(device, slot); statAxes++; scheduleStats(); - InputDevice device = event.getDevice(); int side = JoyCon.side(device); if (side >= 0) { int[] stick = JoyCon.stickAxes(side, device, event.getSource()); @@ -515,7 +524,7 @@ public final class PadBridge { } float lx = event.getAxisValue(MotionEvent.AXIS_X); float ly = event.getAxisValue(MotionEvent.AXIS_Y); - boolean wired = wiredXboxLayout(event); + boolean wired = wiredXboxLayout(device, event.getSource()); float rx = event.getAxisValue(wired ? MotionEvent.AXIS_RX : MotionEvent.AXIS_Z); float ry = event.getAxisValue(wired ? MotionEvent.AXIS_RY : MotionEvent.AXIS_RZ); retainStick(slot, JoyCon.LEFT, lx, ly); @@ -525,11 +534,11 @@ public final class PadBridge { float lt = 0f; float rt = 0f; if (wired || hasAxis(device, source, MotionEvent.AXIS_LTRIGGER, MotionEvent.AXIS_BRAKE)) { - lt = leftTrigger(event, wired); + lt = axisTrigger(leftTrigger(event, wired), keyTriggers[slot], 0); pad.leftTrigger = lt; } if (wired || hasAxis(device, source, MotionEvent.AXIS_RTRIGGER, MotionEvent.AXIS_GAS)) { - rt = rightTrigger(event, wired); + rt = axisTrigger(rightTrigger(event, wired), keyTriggers[slot], 1); pad.rightTrigger = rt; } if (hasAxis(device, source, MotionEvent.AXIS_HAT_X)) { @@ -553,9 +562,27 @@ public final class PadBridge { return true; } - static float keyTrigger(float current, boolean pressed, int repeatCount, boolean analog) { - if (analog || repeatCount > 0) return current; - return pressed ? 1f : 0f; + static float keyTrigger(float current, boolean pressed, int repeatCount, boolean analog, boolean[] held, int side) { + if (repeatCount > 0) return current; + if (!analog) { + held[side] = pressed; + return pressed ? 1f : 0f; + } + if (pressed) { + if (current != 0f) return current; + held[side] = true; + return 1f; + } + if (!held[side]) return current; + held[side] = false; + return 0f; + } + + static float axisTrigger(float value, boolean[] held, int side) { + if (!held[side]) return value; + if (value == 0f) return 1f; + held[side] = false; + return value; } static boolean analogTrigger(InputDevice device, int... axes) { @@ -987,7 +1014,7 @@ public final class PadBridge { } private boolean isPrimary(KeyEvent event) { - int id = event.getDevice().getId(); + int id = event.getDeviceId(); int first = firstPlayerSlot(); return owners[first] == id || partners[first] == id; } diff --git a/app/src/main/java/com/droiddeck/launcher/playback/SoundtrackController.kt b/app/src/main/java/com/droiddeck/launcher/playback/SoundtrackController.kt new file mode 100644 index 0000000000..7242fd6615 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/playback/SoundtrackController.kt @@ -0,0 +1,288 @@ +package com.droiddeck.launcher.playback + +import android.content.ComponentName +import android.content.Context +import android.os.Bundle +import android.net.Uri +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableLongStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.core.content.ContextCompat +import androidx.media3.common.MediaItem +import androidx.media3.common.MediaMetadata +import androidx.media3.common.PlaybackParameters +import androidx.media3.common.Player +import androidx.media3.session.MediaController +import androidx.media3.session.SessionToken +import com.droiddeck.launcher.frontend.Soundtrack +import com.google.common.util.concurrent.ListenableFuture +import java.io.File + +object SoundtrackController { + var playing by mutableStateOf(false) + private set + var currentId by mutableStateOf(null) + private set + var title by mutableStateOf("") + private set + var shuffle by mutableStateOf(false) + private set + var repeat by mutableStateOf(Player.REPEAT_MODE_OFF) + private set + var durationMs by mutableStateOf(0L) + private set + var buffering by mutableStateOf(false) + private set + var volume by mutableStateOf(1f) + private set + + var activeCollection by mutableStateOf(null) + private set + + var sleepEndsAt by mutableLongStateOf(0L) + private set + var sleepTrackEnd by mutableStateOf(false) + private set + + private var app: Context? = null + private val removed: MutableSet = java.util.Collections.synchronizedSet(HashSet()) + private var activeRoot: String? = null + private var savedId: String? = null + private var future: ListenableFuture? = null + private var controller: MediaController? = null + private val pending = ArrayList<(MediaController) -> Unit>() + + private val listener = object : Player.Listener { + override fun onEvents(player: Player, events: Player.Events) = sync(player) + } + + private val disconnect = object : MediaController.Listener { + override fun onDisconnected(controller: MediaController) { + if (this@SoundtrackController.controller === controller) { + this@SoundtrackController.controller = null + future = null + reset() + } + } + } + + private fun reset() { + playing = false + currentId = null + title = "" + durationMs = 0L + buffering = false + volume = 1f + activeCollection = null + } + + private fun sync(player: Player) { + playing = player.isPlaying + buffering = player.playbackState == Player.STATE_BUFFERING + currentId = player.currentMediaItem?.mediaId?.takeIf { player.mediaItemCount > 0 } + title = player.mediaMetadata.title?.toString().orEmpty() + shuffle = player.shuffleModeEnabled + repeat = player.repeatMode + durationMs = player.duration.takeIf { it > 0 } ?: 0L + volume = player.volume + if (!player.playWhenReady) sleepTrackEnd = false + persistResume(player) + } + + private fun persistResume(player: Player) { + val context = app ?: return + val id = currentId ?: return + if (activeCollection != null) return + val root = activeRoot ?: SoundtrackSettings.resume(context)?.root?.takeIf { id.startsWith("$it/") }?.also { activeRoot = it } ?: return + if (id != savedId || !player.isPlaying) { + savedId = id + SoundtrackSettings.saveResume(context, root, id, if (player.playbackState == Player.STATE_ENDED) 0L else player.currentPosition) + } + } + + private fun applySettings(c: MediaController) { + val context = app ?: return + SoundtrackSettings.load(context) + c.setPlaybackParameters(PlaybackParameters(SoundtrackSettings.speed, SoundtrackSettings.pitch)) + c.sendCustomCommand(SoundtrackService.SKIP_SILENCE, Bundle().apply { putBoolean(SoundtrackService.ARG_ON, SoundtrackSettings.skipSilence) }) + sendEqualizer(c) + c.sendCustomCommand(SoundtrackService.INGAME, Bundle().apply { putBoolean(SoundtrackService.ARG_ON, com.droiddeck.launcher.session.SessionPrefs.soundtracksIngame(context)) }) + } + + private fun sendEqualizer(c: MediaController) { + c.sendCustomCommand( + SoundtrackService.EQUALIZER, + Bundle().apply { + putBoolean(SoundtrackService.ARG_ON, SoundtrackSettings.eqOn) + putIntArray(SoundtrackService.ARG_BANDS, SoundtrackSettings.bands.toIntArray()) + putInt(SoundtrackService.ARG_BASS, SoundtrackSettings.bass) + }, + ) + } + + private fun run(context: Context, block: (MediaController) -> Unit) { + app = context.applicationContext + val live = controller + if (live != null) { block(live); return } + pending += block + if (future != null) return + val app = context.applicationContext + val token = SessionToken(app, ComponentName(app, SoundtrackService::class.java)) + val built = MediaController.Builder(app, token).setListener(disconnect) + .setConnectionHints(Bundle().apply { putBoolean(SoundtrackService.HINT_OWNER, true) }).buildAsync() + future = built + built.addListener({ + val ready = runCatching { built.get() }.getOrNull() + if (ready == null) { + future = null + pending.clear() + return@addListener + } + controller = ready + ready.addListener(listener) + applySettings(ready) + sync(ready) + val queued = pending.toList() + pending.clear() + queued.forEach { it(ready) } + }, ContextCompat.getMainExecutor(app)) + } + + fun connect(context: Context) = run(context) { } + + fun position(): Long = controller?.currentPosition ?: 0L + + fun belongsCollection(id: Int): Boolean = activeCollection == id && currentId != null + + fun belongs(root: File?): Boolean { + if (activeCollection != null) return false + val id = currentId ?: return false + return root != null && id.startsWith(root.path + "/") + } + + private fun items(album: Soundtrack.Album, albumTitle: String): List { + val cover = album.cover?.let { Uri.fromFile(it) } + return album.tracks.map { t -> + MediaItem.Builder() + .setMediaId(t.file.path) + .setMediaMetadata( + MediaMetadata.Builder() + .setTitle(t.title) + .setArtist(t.artist.ifBlank { album.artist }.ifBlank { null }) + .setAlbumTitle(albumTitle) + .setTrackNumber(t.number) + .setDiscNumber(t.disc.takeIf { it > 0 }) + .setArtworkUri(cover) + .setIsPlayable(true) + .build(), + ) + .build() + } + } + + fun play( + context: Context, album: Soundtrack.Album, albumTitle: String, startId: String?, shuffled: Boolean? = null, + root: File? = null, startMs: Long = 0L, collection: Int? = null, + ) { + val list = items(album, albumTitle) + if (list.isEmpty()) return + run(context) { c -> + if (root != null && root.path in removed) return@run + val start = list.indexOfFirst { it.mediaId == startId }.coerceAtLeast(0) + root?.let { activeRoot = it.path } + activeCollection = collection + c.setMediaItems(list, start, startMs) + shuffled?.let { c.shuffleModeEnabled = it } + c.prepare() + c.play() + } + } + + fun allow(paths: Collection) { + removed.removeAll(paths.toSet()) + } + + fun toggle(context: Context, album: Soundtrack.Album, albumTitle: String, root: File?, collection: Int? = null) { + run(context) { c -> + if (root != null && root.path in removed) return@run + val mine = if (collection != null) belongsCollection(collection) else belongs(root) + if (mine && c.mediaItemCount > 0) { + if (c.isPlaying) c.pause() else { + if (c.playbackState == Player.STATE_ENDED) c.seekToDefaultPosition(0) + c.play() + } + } else { + val saved = if (collection != null) null else root?.let { r -> SoundtrackSettings.resume(context)?.takeIf { it.root == r.path && album.tracks.any { t -> t.id == it.id } } } + play(context, album, albumTitle, saved?.id ?: album.tracks.firstOrNull()?.id, root = root, startMs = saved?.positionMs ?: 0L, collection = collection) + } + } + } + + fun pause(context: Context) { + val live = controller + if (live != null) live.pause() else if (future != null) pending += { it.pause() } + } + + fun next(context: Context) = run(context) { it.seekToNext() } + fun previous(context: Context) = run(context) { c -> if (c.currentPosition > 3000L) c.seekTo(0) else c.seekToPrevious() } + fun seekTo(context: Context, ms: Long) = run(context) { it.seekTo(ms) } + fun setShuffle(context: Context, on: Boolean) = run(context) { it.shuffleModeEnabled = on } + fun cycleRepeat(context: Context) = run(context) { + it.repeatMode = when (it.repeatMode) { + Player.REPEAT_MODE_OFF -> Player.REPEAT_MODE_ALL + Player.REPEAT_MODE_ALL -> Player.REPEAT_MODE_ONE + else -> Player.REPEAT_MODE_OFF + } + } + fun setVolume(context: Context, volume: Float) = run(context) { it.volume = volume.coerceIn(0f, 1f) } + + fun setSpeed(context: Context, value: Float) { + SoundtrackSettings.load(context) + SoundtrackSettings.setSpeed(context, value) + run(context) { it.setPlaybackParameters(PlaybackParameters(SoundtrackSettings.speed, SoundtrackSettings.pitch)) } + } + + fun setPitch(context: Context, value: Float) { + SoundtrackSettings.load(context) + SoundtrackSettings.setPitch(context, value) + run(context) { it.setPlaybackParameters(PlaybackParameters(SoundtrackSettings.speed, SoundtrackSettings.pitch)) } + } + + fun setSkipSilence(context: Context, on: Boolean) { + SoundtrackSettings.load(context) + SoundtrackSettings.setSkipSilence(context, on) + run(context) { it.sendCustomCommand(SoundtrackService.SKIP_SILENCE, Bundle().apply { putBoolean(SoundtrackService.ARG_ON, on) }) } + } + + fun setEqualizer(context: Context, on: Boolean, bands: List, bass: Int) { + SoundtrackSettings.load(context) + SoundtrackSettings.setEqualizer(context, on, bands, bass) + run(context) { sendEqualizer(it) } + } + + fun setIngame(context: Context, on: Boolean) { + run(context) { it.sendCustomCommand(SoundtrackService.INGAME, Bundle().apply { putBoolean(SoundtrackService.ARG_ON, on) }) } + } + + fun setSleep(context: Context, minutes: Int) { + sleepEndsAt = if (minutes > 0) System.currentTimeMillis() + minutes * 60_000L else 0L + sleepTrackEnd = minutes < 0 + run(context) { it.sendCustomCommand(SoundtrackService.SLEEP, Bundle().apply { putInt(SoundtrackService.ARG_MINUTES, minutes) }) } + } + + fun sleepRemainingMs(): Long { + val left = sleepEndsAt - System.currentTimeMillis() + if (sleepEndsAt > 0L && left <= 0L) sleepEndsAt = 0L + return left.coerceAtLeast(0L) + } + + fun stopIf(context: Context, root: File?) { + root?.let { removed.add(it.path) } + if (root == null || currentId?.startsWith(root.path + "/") != true) return + run(context) { c -> + c.stop() + c.clearMediaItems() + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/playback/SoundtrackService.kt b/app/src/main/java/com/droiddeck/launcher/playback/SoundtrackService.kt new file mode 100644 index 0000000000..083b935cd5 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/playback/SoundtrackService.kt @@ -0,0 +1,282 @@ +package com.droiddeck.launcher.playback + +import android.app.PendingIntent +import android.content.Context +import android.content.Intent +import android.media.audiofx.BassBoost +import android.media.audiofx.Equalizer +import android.net.Uri +import android.os.Bundle +import android.os.Handler +import android.os.Looper +import android.os.Process +import androidx.media3.common.AudioAttributes +import androidx.media3.common.C +import androidx.media3.common.MediaItem +import androidx.media3.common.Player +import androidx.media3.exoplayer.ExoPlayer +import androidx.media3.session.CommandButton +import androidx.media3.session.DefaultMediaNotificationProvider +import androidx.media3.session.MediaSession +import androidx.media3.session.MediaSessionService +import androidx.media3.session.SessionCommand +import androidx.media3.session.SessionResult +import com.droiddeck.launcher.R +import com.droiddeck.launcher.frontend.Soundtrack +import com.google.common.collect.ImmutableList +import com.google.common.util.concurrent.Futures +import com.google.common.util.concurrent.ListenableFuture +import java.io.File + +private class EdgeButtonsProvider(context: Context) : DefaultMediaNotificationProvider(context) { + override fun getMediaButtons( + session: MediaSession, playerCommands: Player.Commands, customLayout: ImmutableList, showPauseButton: Boolean, + ): ImmutableList { + val all = super.getMediaButtons(session, playerCommands, customLayout, showPauseButton) + val custom = all.filter { it.sessionCommand != null } + if (custom.size < 2) return all + return ImmutableList.builder() + .add(custom.first()) + .addAll(all.filter { it.sessionCommand == null }) + .addAll(custom.drop(1)) + .build() + } +} + +class SoundtrackService : MediaSessionService() { + private var session: MediaSession? = null + private var exo: ExoPlayer? = null + private var equalizer: Equalizer? = null + private var bassBoost: BassBoost? = null + private var effectsSession = C.AUDIO_SESSION_ID_UNSET + private var eqOn = false + private var eqBands = IntArray(0) + private var eqBass = 0 + private var sleepAtTrackEnd = false + private val handler = Handler(Looper.getMainLooper()) + private val sleepRunnable = Runnable { session?.player?.pause() } + private val covers = java.util.concurrent.Executors.newSingleThreadExecutor { r -> Thread(r, "soundtrack-cover").apply { isDaemon = true } } + + override fun onCreate() { + super.onCreate() + val player = ExoPlayer.Builder(this) + .setAudioAttributes(mediaAttributes(), !com.droiddeck.launcher.session.SessionPrefs.soundtracksIngame(this)) + .setHandleAudioBecomingNoisy(true) + .setWakeMode(androidx.media3.common.C.WAKE_MODE_LOCAL) + .build() + exo = player + val sessionIntent = packageManager.getLaunchIntentForPackage(packageName)?.let { + PendingIntent.getActivity(this, 0, it, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE) + } + player.addListener(object : Player.Listener { + override fun onShuffleModeEnabledChanged(shuffleModeEnabled: Boolean) = refreshButtons() + override fun onRepeatModeChanged(repeatMode: Int) = refreshButtons() + override fun onAudioSessionIdChanged(audioSessionId: Int) = applyEffects() + override fun onPlayWhenReadyChanged(playWhenReady: Boolean, reason: Int) { + if (!playWhenReady) sleepAtTrackEnd = false + } + override fun onMediaItemTransition(mediaItem: MediaItem?, reason: Int) { + refreshTrackCover(mediaItem) + val ended = reason == Player.MEDIA_ITEM_TRANSITION_REASON_AUTO || reason == Player.MEDIA_ITEM_TRANSITION_REASON_REPEAT + if (sleepAtTrackEnd && ended) { + sleepAtTrackEnd = false + player.pause() + } + } + }) + session = MediaSession.Builder(this, player).setCallback(Resolver()).apply { sessionIntent?.let { setSessionActivity(it) } }.build() + setMediaNotificationProvider(EdgeButtonsProvider(this).apply { setSmallIcon(R.drawable.ic_soundtrack) }) + } + + private fun mediaAttributes(): AudioAttributes = + AudioAttributes.Builder().setUsage(C.USAGE_MEDIA).setContentType(C.AUDIO_CONTENT_TYPE_MUSIC).build() + + private fun buttons(player: Player): ImmutableList = ImmutableList.of( + CommandButton.Builder() + .setDisplayName(getString(R.string.soundtracks_shuffle)) + .setIconResId(if (player.shuffleModeEnabled) R.drawable.ic_shuffle_on else R.drawable.ic_shuffle_off) + .setSessionCommand(SHUFFLE) + .build(), + CommandButton.Builder() + .setDisplayName( + getString( + when (player.repeatMode) { + Player.REPEAT_MODE_ALL -> R.string.soundtracks_repeat_all + Player.REPEAT_MODE_ONE -> R.string.soundtracks_repeat_one + else -> R.string.soundtracks_repeat_off + }, + ), + ) + .setIconResId( + when (player.repeatMode) { + Player.REPEAT_MODE_ALL -> R.drawable.ic_repeat_all + Player.REPEAT_MODE_ONE -> R.drawable.ic_repeat_one + else -> R.drawable.ic_repeat_off + }, + ) + .setSessionCommand(REPEAT) + .build(), + ) + + private fun hasPinnedArt(item: MediaItem): Boolean = + item.mediaMetadata.artworkUri?.path.orEmpty().let { it.contains("/steam-art/") || it.contains("/soundtrack-art/") } + + private fun refreshTrackCover(item: MediaItem?) { + val current = item ?: return + if (hasPinnedArt(current)) return + val file = File(current.mediaId) + covers.execute { + val art = Soundtrack.trackCover(this, file) ?: return@execute + handler.post { + val player = exo ?: return@post + val live = player.currentMediaItem ?: return@post + val uri = Uri.fromFile(art) + if (live.mediaId != current.mediaId || live.mediaMetadata.artworkUri == uri || hasPinnedArt(live)) return@post + player.replaceMediaItem( + player.currentMediaItemIndex, + live.buildUpon().setMediaMetadata(live.mediaMetadata.buildUpon().setArtworkUri(uri).build()).build(), + ) + } + } + } + + private fun releaseEffects() { + runCatching { equalizer?.release() } + runCatching { bassBoost?.release() } + equalizer = null + bassBoost = null + effectsSession = C.AUDIO_SESSION_ID_UNSET + } + + private fun applyEffects() { + val id = exo?.audioSessionId ?: C.AUDIO_SESSION_ID_UNSET + if (!eqOn || id == C.AUDIO_SESSION_ID_UNSET) { + releaseEffects() + return + } + if (id != effectsSession) { + releaseEffects() + effectsSession = id + equalizer = runCatching { Equalizer(0, id) }.getOrNull() + bassBoost = runCatching { BassBoost(0, id) }.getOrNull() + } + runCatching { + equalizer?.let { eq -> + val range = eq.bandLevelRange + for (band in 0 until minOf(eq.numberOfBands.toInt(), eqBands.size)) { + eq.setBandLevel(band.toShort(), eqBands[band].coerceIn(range[0].toInt(), range[1].toInt()).toShort()) + } + eq.enabled = true + } + } + runCatching { + bassBoost?.let { boost -> + if (boost.strengthSupported) boost.setStrength(eqBass.coerceIn(0, 1000).toShort()) + boost.enabled = eqBass > 0 + } + } + } + + private fun setSleep(minutes: Int) { + handler.removeCallbacks(sleepRunnable) + sleepAtTrackEnd = false + if (minutes > 0) handler.postDelayed(sleepRunnable, minutes * 60_000L) + else if (minutes < 0) sleepAtTrackEnd = true + } + + private fun refreshButtons() { + val live = session ?: return + live.setCustomLayout(buttons(live.player)) + } + + override fun onGetSession(controllerInfo: MediaSession.ControllerInfo): MediaSession? = session + + override fun onTaskRemoved(rootIntent: Intent?) { + val player = session?.player + if (player == null || !player.playWhenReady || player.mediaItemCount == 0 || player.playbackState == Player.STATE_ENDED) stopSelf() + } + + override fun onDestroy() { + handler.removeCallbacks(sleepRunnable) + covers.shutdownNow() + releaseEffects() + session?.let { + it.player.release() + it.release() + } + session = null + super.onDestroy() + } + + companion object { + const val HINT_OWNER = "droiddeck.owner" + private val SHUFFLE = SessionCommand("droiddeck.shuffle", Bundle.EMPTY) + private val REPEAT = SessionCommand("droiddeck.repeat", Bundle.EMPTY) + val SKIP_SILENCE = SessionCommand("droiddeck.skipsilence", Bundle.EMPTY) + val EQUALIZER = SessionCommand("droiddeck.equalizer", Bundle.EMPTY) + val SLEEP = SessionCommand("droiddeck.sleep", Bundle.EMPTY) + val INGAME = SessionCommand("droiddeck.ingame", Bundle.EMPTY) + const val ARG_ON = "on" + const val ARG_BANDS = "bands" + const val ARG_BASS = "bass" + const val ARG_MINUTES = "minutes" + } + + private inner class Resolver : MediaSession.Callback { + private fun isOwner(controller: MediaSession.ControllerInfo) = + controller.uid == Process.myUid() && controller.connectionHints.getBoolean(HINT_OWNER, false) + + override fun onConnect(session: MediaSession, controller: MediaSession.ControllerInfo): MediaSession.ConnectionResult = + if (controller.uid == Process.myUid() || controller.isTrusted) { + MediaSession.ConnectionResult.AcceptedResultBuilder(session) + .setAvailableSessionCommands( + MediaSession.ConnectionResult.DEFAULT_SESSION_COMMANDS.buildUpon().add(SHUFFLE).add(REPEAT).add(SKIP_SILENCE).add(EQUALIZER).add(SLEEP).add(INGAME).build(), + ) + .setCustomLayout(buttons(session.player)) + .build() + } else { + MediaSession.ConnectionResult.reject() + } + + override fun onCustomCommand( + session: MediaSession, controller: MediaSession.ControllerInfo, customCommand: SessionCommand, args: Bundle, + ): ListenableFuture { + val player = session.player + when (customCommand.customAction) { + SHUFFLE.customAction -> player.shuffleModeEnabled = !player.shuffleModeEnabled + REPEAT.customAction -> player.repeatMode = when (player.repeatMode) { + Player.REPEAT_MODE_OFF -> Player.REPEAT_MODE_ALL + Player.REPEAT_MODE_ALL -> Player.REPEAT_MODE_ONE + else -> Player.REPEAT_MODE_OFF + } + SKIP_SILENCE.customAction, EQUALIZER.customAction, SLEEP.customAction, INGAME.customAction -> { + if (!isOwner(controller)) return Futures.immediateFuture(SessionResult(SessionResult.RESULT_ERROR_PERMISSION_DENIED)) + when (customCommand.customAction) { + SKIP_SILENCE.customAction -> exo?.skipSilenceEnabled = args.getBoolean(ARG_ON) + INGAME.customAction -> exo?.setAudioAttributes(mediaAttributes(), !args.getBoolean(ARG_ON)) + EQUALIZER.customAction -> { + eqOn = args.getBoolean(ARG_ON) + eqBands = args.getIntArray(ARG_BANDS) ?: IntArray(0) + eqBass = args.getInt(ARG_BASS) + applyEffects() + } + else -> setSleep(args.getInt(ARG_MINUTES)) + } + } + else -> return Futures.immediateFuture(SessionResult(SessionResult.RESULT_ERROR_NOT_SUPPORTED)) + } + return Futures.immediateFuture(SessionResult(SessionResult.RESULT_SUCCESS)) + } + + override fun onAddMediaItems( + mediaSession: MediaSession, controller: MediaSession.ControllerInfo, mediaItems: MutableList, + ): ListenableFuture> { + if (!isOwner(controller)) return Futures.immediateFailedFuture(SecurityException("Only DroidDeck can queue soundtrack files")) + val resolved = mediaItems.mapNotNull { item -> + val file = File(item.mediaId) + if (Soundtrack.isAudio(file)) item.buildUpon().setUri(Uri.fromFile(file)).build() else null + }.toMutableList() + return Futures.immediateFuture(resolved) + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/playback/SoundtrackSettings.kt b/app/src/main/java/com/droiddeck/launcher/playback/SoundtrackSettings.kt new file mode 100644 index 0000000000..c34af1e32e --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/playback/SoundtrackSettings.kt @@ -0,0 +1,78 @@ +package com.droiddeck.launcher.playback + +import android.content.Context +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableFloatStateOf +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue + +object SoundtrackSettings { + const val MIN_RATE = 0.5f + const val MAX_RATE = 2f + + var speed by mutableFloatStateOf(1f) + private set + var pitch by mutableFloatStateOf(1f) + private set + var skipSilence by mutableStateOf(false) + private set + var eqOn by mutableStateOf(false) + private set + var bands by mutableStateOf>(emptyList()) + private set + var bass by mutableIntStateOf(0) + private set + + class Resume(val root: String, val id: String, val positionMs: Long) + + private var loaded = false + + private fun prefs(context: Context) = context.applicationContext.getSharedPreferences("soundtrack_settings", Context.MODE_PRIVATE) + + @Synchronized + fun load(context: Context) { + if (loaded) return + loaded = true + val p = prefs(context) + speed = p.getFloat("speed", 1f).coerceIn(MIN_RATE, MAX_RATE) + pitch = p.getFloat("pitch", 1f).coerceIn(MIN_RATE, MAX_RATE) + skipSilence = p.getBoolean("skipSilence", false) + eqOn = p.getBoolean("eqOn", false) + bands = p.getString("bands", "").orEmpty().split(',').mapNotNull { it.trim().toIntOrNull() } + bass = p.getInt("bass", 0).coerceIn(0, 1000) + } + + fun setSpeed(context: Context, value: Float) { + speed = value.coerceIn(MIN_RATE, MAX_RATE) + prefs(context).edit().putFloat("speed", speed).apply() + } + + fun setPitch(context: Context, value: Float) { + pitch = value.coerceIn(MIN_RATE, MAX_RATE) + prefs(context).edit().putFloat("pitch", pitch).apply() + } + + fun setSkipSilence(context: Context, on: Boolean) { + skipSilence = on + prefs(context).edit().putBoolean("skipSilence", on).apply() + } + + fun setEqualizer(context: Context, on: Boolean, levels: List, bassStrength: Int) { + eqOn = on + bands = levels + bass = bassStrength.coerceIn(0, 1000) + prefs(context).edit().putBoolean("eqOn", on).putString("bands", levels.joinToString(",")).putInt("bass", bass).apply() + } + + fun resume(context: Context): Resume? { + val p = prefs(context) + val root = p.getString("resumeRoot", null) ?: return null + val id = p.getString("resumeId", null) ?: return null + return Resume(root, id, p.getLong("resumePosition", 0L)) + } + + fun saveResume(context: Context, root: String, id: String, positionMs: Long) { + prefs(context).edit().putString("resumeRoot", root).putString("resumeId", id).putLong("resumePosition", positionMs.coerceAtLeast(0L)).apply() + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/BattleNet.kt b/app/src/main/java/com/droiddeck/launcher/runtime/BattleNet.kt index a98e3d0cfa..eeab317afe 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/BattleNet.kt +++ b/app/src/main/java/com/droiddeck/launcher/runtime/BattleNet.kt @@ -232,11 +232,24 @@ object BattleNet { } internal fun hostFolder(context: Context, path: String): File? { - val drive = Regex("""^([CcZz]):[\\/](.*)$""").matchEntire(path.trim()) ?: return null + val drive = Regex("""^([A-Za-z]):[\\/](.*)$""").matchEntire(path.trim()) ?: return null val relative = drive.groupValues[2].replace('\\', '/').trim('/') if (relative.isEmpty() || relative.split('/').any { it == ".." }) return null - return if (drive.groupValues[1].equals("c", ignoreCase = true)) File(prefix(context), "pfx/drive_c/$relative") - else com.droiddeck.launcher.frontend.AddedGames.hostPath(context, "/$relative") + val letter = drive.groupValues[1].lowercase() + if (letter == "c") return File(prefix(context), "pfx/drive_c/$relative") + val link = File(prefix(context), "pfx/dosdevices/$letter:").toPath() + val mapped = runCatching { java.nio.file.Files.readSymbolicLink(link).toString() }.getOrNull() + val target = when { + mapped == null -> if (letter == "z") "/" else return null + mapped.startsWith("/") -> mapped + else -> { + val rootfs = LinuxRuntime.rootDir(context).toPath().toAbsolutePath().normalize() + val resolved = link.toAbsolutePath().parent.resolve(mapped).normalize() + if (!resolved.startsWith(rootfs)) return null + "/" + rootfs.relativize(resolved).joinToString("/") + } + }.trimEnd('/') + return com.droiddeck.launcher.frontend.AddedGames.hostPath(context, "$target/$relative") } private val KEY = Regex("""^\[(.+)\](?:\s+\d+)?\s*$""") @@ -361,7 +374,7 @@ object BattleNet { val guestPrefix = added.guestPath(context, prefix(context)) ?: return null val crc = java.util.zip.CRC32().apply { update("\"$guestExe\"${game.name}".toByteArray()) }.value val appId = com.droiddeck.launcher.session.SessionPrefs.addedGameAppId(context, game.folder.path, crc or 0x80000000L) - val exe = added.candidates(game.folder).firstOrNull() ?: client + val exe = added.candidates(game.folder, reuse = true).firstOrNull() ?: client return com.droiddeck.launcher.frontend.AddedGames.Game( game.folder, game.name, exe, guestExe, guestDir, appId, (appId shl 32) or 0x02000000L, listOf(exe), source = com.droiddeck.launcher.stores.Store.BATTLENET.id, storeId = game.uid, diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/LinuxNetworkLinkComponent.kt b/app/src/main/java/com/droiddeck/launcher/runtime/LinuxNetworkLinkComponent.kt index 7081d88114..46c29aadb8 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/LinuxNetworkLinkComponent.kt +++ b/app/src/main/java/com/droiddeck/launcher/runtime/LinuxNetworkLinkComponent.kt @@ -157,9 +157,7 @@ class LinuxNetworkLinkComponent( synchronized(lock) { try { file.parentFile?.mkdirs() - val staged = File(file.path + ".staged") - staged.writeText(describe(properties, capabilities)) - if (!staged.renameTo(file)) throw IOException("Could not replace $file") + replace(file, describe(properties, capabilities)) } catch (e: IOException) { Log.w(TAG, "Could not publish the network link", e) } @@ -241,9 +239,7 @@ class LinuxNetworkLinkComponent( } try { val file = File(rootDir, "etc/droiddeck-network.json") - val staged = File(file.path + ".staged") - staged.writeText(state.toString()) - if (!staged.renameTo(file)) throw IOException("Could not replace network state") + replace(file, state.toString()) } catch (e: IOException) { Log.w(TAG, "Could not publish the network state", e) } @@ -272,6 +268,19 @@ class LinuxNetworkLinkComponent( return Pair(servers.sortedWith(order), gateways.sortedWith(order)) } + /** + * Writes [text] to [file] through a staged copy. The copy is synced before the rename, or a + * crash or power cut can keep the rename and lose the data, leaving a file of NUL bytes. + */ + private fun replace(file: File, text: String) { + val staged = File(file.path + ".staged") + java.io.FileOutputStream(staged).use { out -> + out.write(text.toByteArray()) + out.fd.sync() + } + if (!staged.renameTo(file)) throw IOException("Could not replace $file") + } + private fun writeResolver(properties: LinkProperties?) { val own = properties?.dnsServers.orEmpty() .filter { !it.isLinkLocalAddress && !it.isLoopbackAddress && !it.isAnyLocalAddress } @@ -286,9 +295,7 @@ class LinuxNetworkLinkComponent( } try { val etc = File(rootDir, "etc") - val staged = File(etc, "resolv.conf.staged") - staged.writeText(text) - if (!staged.renameTo(File(etc, "resolv.conf"))) throw IOException("Could not replace resolv.conf") + replace(File(etc, "resolv.conf"), text) val hosts = File(etc, "hosts") if (!hosts.isFile || !hosts.readText().contains("localhost")) { hosts.writeText("127.0.0.1 localhost\n::1 localhost\n") diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/LinuxRuntime.java b/app/src/main/java/com/droiddeck/launcher/runtime/LinuxRuntime.java index 0253604021..0e5c2d6715 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/LinuxRuntime.java +++ b/app/src/main/java/com/droiddeck/launcher/runtime/LinuxRuntime.java @@ -139,15 +139,26 @@ public final class LinuxRuntime { public static List command(Context context, File sessionRoot, File runtimeDir, File externalStorage, List extraBinds, List guestCommand) { + return command(context, sessionRoot, runtimeDir, externalStorage, extraBinds, guestCommand, false); + } + + public static List command(Context context, File sessionRoot, File runtimeDir, + File externalStorage, List extraBinds, + List guestCommand, boolean fakeRoot) { File root = rootDir(context); List binds = binds(context, sessionRoot, runtimeDir, externalStorage, extraBinds); if (sessionRoot != null) lastBinds = binds; - return commandWithBinds(context, root, binds, guestCommand); + return commandWithBinds(context, root, binds, guestCommand, fakeRoot); } public static List commandWithBinds(Context context, File root, List binds, List guestCommand) { - List cmd = prootPrefix(context, root, "/root"); + return commandWithBinds(context, root, binds, guestCommand, false); + } + + public static List commandWithBinds(Context context, File root, List binds, + List guestCommand, boolean fakeRoot) { + List cmd = fakeRoot ? rootPrefix(context, root, "/root") : prootPrefix(context, root, "/root"); for (String spec : binds) bind(cmd, spec); cmd.addAll(guestCommand); return cmd; @@ -170,6 +181,12 @@ public final class LinuxRuntime { return prootPrefix(context, root, cwd, false); } + public static List rootPrefix(Context context, File root, String cwd) { + List cmd = prootPrefix(context, root, cwd, true); + cmd.add(1, "--link2symlink"); + return cmd; + } + public static List prootPrefix(Context context, File root, String cwd, boolean fakeRoot) { List cmd = new ArrayList<>(); cmd.add(prootBinary(context).getPath()); diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/RootSpawner.kt b/app/src/main/java/com/droiddeck/launcher/runtime/RootSpawner.kt index a96ff46f38..16228be728 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/RootSpawner.kt +++ b/app/src/main/java/com/droiddeck/launcher/runtime/RootSpawner.kt @@ -120,8 +120,7 @@ object RootSpawner { val builder = if (NativeGuest.forSession(context)) { NativeGuest.processBuilder(context, root, binds, guest, cwd) } else { - val cmd = LinuxRuntime.prootPrefix(context, root, cwd, true) - cmd.add(1, "--link2symlink") + val cmd = LinuxRuntime.rootPrefix(context, root, cwd) binds.forEach { cmd.add("-b"); cmd.add(it) } cmd.addAll(guest) ProcessBuilder(cmd).directory(root).also { b -> diff --git a/app/src/main/java/com/droiddeck/launcher/session/BuildWatermarkSetting.kt b/app/src/main/java/com/droiddeck/launcher/session/BuildWatermarkSetting.kt new file mode 100644 index 0000000000..98239f8eb0 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/session/BuildWatermarkSetting.kt @@ -0,0 +1,44 @@ +package com.droiddeck.launcher.session + +import android.content.Context +import android.content.Intent +import android.util.AtomicFile +import java.io.File + +internal object BuildWatermarkSetting { + const val CHANGED = "com.droiddeck.launcher.BUILD_WATERMARK_CHANGED" + + private fun file(context: Context) = AtomicFile(File(context.filesDir, "build-watermark")) + + private val processLock = Any() + + private fun locked(context: Context, action: () -> T): T = synchronized(processLock) { + File(context.filesDir, "build-watermark.lock").outputStream().channel.use { channel -> + channel.lock().use { action() } + } + } + + fun enabled(context: Context): Boolean = try { + locked(context) { + // SharedPreferences caches are process-local; read the shared file on every refresh. + file(context).readFully().decodeToString() != "off" + } + } catch (_: java.io.IOException) { + context.getSharedPreferences("session", Context.MODE_PRIVATE).getBoolean("buildWatermark", true) + } + + fun setEnabled(context: Context, on: Boolean) { + locked(context) { + val target = file(context) + val stream = target.startWrite() + try { + stream.write((if (on) "on" else "off").toByteArray()) + target.finishWrite(stream) + } catch (error: Throwable) { + target.failWrite(stream) + throw error + } + } + context.sendBroadcast(Intent(CHANGED).setPackage(context.packageName)) + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/session/GameEnvironmentStore.kt b/app/src/main/java/com/droiddeck/launcher/session/GameEnvironmentStore.kt index 2a19f39abc..81dc109d67 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/GameEnvironmentStore.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/GameEnvironmentStore.kt @@ -79,6 +79,13 @@ object GameEnvironmentStore { return config } + @Synchronized + fun setGameResolution(context: Context, scope: String, choice: com.droiddeck.launcher.core.GameResolution.Choice?): GameEnvironment.Config { + val config = GameEnvironment.withGameResolution(read(context), scope, choice) + save(context, config) + return config + } + @Synchronized fun setDefault(context: Context, scope: String, name: String, value: String): Boolean { val config = read(context) diff --git a/app/src/main/java/com/droiddeck/launcher/session/GameStorage.kt b/app/src/main/java/com/droiddeck/launcher/session/GameStorage.kt index 5bf25103b0..e9ecb7443c 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/GameStorage.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/GameStorage.kt @@ -90,11 +90,11 @@ object GameStorage { fun gamesFolderLibraries(context: Context): List { if (SessionPrefs.gameStorage(context).isNotEmpty()) return emptyList() - val card = effective(context)?.let { canonical(File(it.path)) } - val added = SteamLibraries.list(context).map { canonical(it.host) } + val card = effective(context)?.let { SteamLibraries.canonical(File(it.path)) } + val added = SteamLibraries.list(context).map { SteamLibraries.canonical(it.host) } val sm = context.getSystemService(StorageManager::class.java) return AddedGames.roots(context).mapNotNull { root -> - val host = canonical(root.host) + val host = SteamLibraries.canonical(root.host) if (!hasInstalledGames(root.host)) return@mapNotNull null if ('"' in root.guest || '\\' in root.guest || !root.host.isDirectory || !root.host.canWrite()) return@mapNotNull null if (card != null && (host == card || host.startsWith("$card/") || card.startsWith("$host/"))) return@mapNotNull null @@ -109,8 +109,6 @@ object GameStorage { internal fun hasInstalledGames(root: File): Boolean = File(root, "steamapps").listFiles { f -> f.isFile && f.name.startsWith("appmanifest_") && f.name.endsWith(".acf") }?.isNotEmpty() == true - private fun canonical(file: File): String = runCatching { file.canonicalPath }.getOrDefault(file.absolutePath) - fun labelFor(context: Context, path: String): String = options(context).firstOrNull { it.path == path }?.name ?: File(path).name.ifEmpty { context.getString(R.string.gstore_folder) } diff --git a/app/src/main/java/com/droiddeck/launcher/session/NoSteamLaunch.kt b/app/src/main/java/com/droiddeck/launcher/session/NoSteamLaunch.kt index 8d8070f875..a1f39ae470 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/NoSteamLaunch.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/NoSteamLaunch.kt @@ -30,6 +30,25 @@ object NoSteamLaunch { GameEnvironment.gameNoSteam(GameEnvironmentStore.read(context), (appId and 0xFFFFFFFFL).toString()) }.getOrDefault(false) + fun scopeOf(program: String?, args: List, battleNetTitle: (String) -> String? = { null }): String? = when (program) { + EPIC -> EpicClient.shortcutAppId.toString() + BATTLENET -> args.getOrNull(args.indexOf("launch") + 1)?.takeIf { args.contains("launch") }?.let(battleNetTitle) + ?: com.droiddeck.launcher.runtime.BattleNet.APP_ID.toString() + PROTON_RUN -> args.getOrNull(args.indexOf("--app") + 1)?.takeIf { args.contains("--app") } + else -> null + }?.takeIf { it.isNotEmpty() && GameEnvironment.validScope(it) } + + fun battleNetTitleScope(context: Context, code: String): String? = + AddedGames.scan(context).firstOrNull { game -> + game.source == com.droiddeck.launcher.stores.Store.BATTLENET.id && + game.storeId?.let(com.droiddeck.launcher.runtime.BattleNet::title)?.code == code + }?.let { settingsId(it).toString() } + + fun resolution(config: GameEnvironment.Config, scope: String?, output: Pair): Pair? { + val choice = scope?.let { GameEnvironment.gameResolution(config, it) } ?: return null + return com.droiddeck.launcher.core.GameResolution.resolve(choice, output) + } + fun command(game: Library.SteamGame, added: AddedGames.Game?): Command? = when { game.library == Library.EPIC_LAUNCHER -> Command(EPIC, listOf("run"), game.name) game.library == Library.ADDED && game.source == com.droiddeck.launcher.stores.Store.BATTLENET.id -> diff --git a/app/src/main/java/com/droiddeck/launcher/session/OrphanReaper.kt b/app/src/main/java/com/droiddeck/launcher/session/OrphanReaper.kt index cbcd904bc1..a6c5117665 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/OrphanReaper.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/OrphanReaper.kt @@ -11,6 +11,9 @@ object OrphanReaper { fun release(pid: Int) { kept.remove(pid) } + /** Kept processes and everything they started, which session cleanups must leave running. */ + fun spared(): Set = descendants(kept) + fun hasOtherProcesses(): Boolean = hasOtherProcesses( File("/proc").list()?.mapNotNull { it.toIntOrNull() }, android.os.Process.myPid(), ) { pid -> @@ -30,7 +33,7 @@ object OrphanReaper { fun reap(reason: String, matching: (String) -> Boolean = { true }): Int { val me = android.os.Process.myPid() val uid = android.os.Process.myUid() - val spared = descendants(kept) + val spared = spared() var killed = 0 File("/proc").listFiles()?.forEach { entry -> val pid = entry.name.toIntOrNull() ?: return@forEach diff --git a/app/src/main/java/com/droiddeck/launcher/session/SelectedGameProfile.kt b/app/src/main/java/com/droiddeck/launcher/session/SelectedGameProfile.kt index 41eeac38f6..c3df4a97c4 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SelectedGameProfile.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SelectedGameProfile.kt @@ -3,6 +3,7 @@ package com.droiddeck.launcher.session import com.droiddeck.launcher.core.FexPreset import com.droiddeck.launcher.core.GameEnvironment import com.droiddeck.launcher.frontend.Library +import com.droiddeck.launcher.gpu.FrameGen data class ProfileValue(val value: String, val inherited: Boolean) @@ -17,6 +18,8 @@ data class SelectedGameProfile( val environmentOverrides: Int, val windowsComponentNames: List, val startWithoutSteam: Boolean = false, + val frameGen: FrameGen.Mode = FrameGen.Mode.OFF, + val frameGenInherited: Boolean = true, ) { val hasOverrides: Boolean get() = !fexPreset.inherited || @@ -24,7 +27,8 @@ data class SelectedGameProfile( components.values.any { !it.inherited } || environmentOverrides > 0 || windowsComponentNames.isNotEmpty() || - startWithoutSteam + startWithoutSteam || + !frameGenInherited companion object { fun resolve( @@ -38,6 +42,8 @@ data class SelectedGameProfile( gameProtonId: String?, gameComponents: Map, gameWindowsComponents: List, + frameGenMode: FrameGen.Mode = FrameGen.Mode.OFF, + frameGenInherited: Boolean = true, ): SelectedGameProfile? { val game = games.firstOrNull { it.profileKey == selectedAppId.toString() } ?: return null val fexOverride = GameEnvironment.gameFexPreset(environment, game.profileKey) @@ -53,7 +59,7 @@ data class SelectedGameProfile( ) } val otherEnvironment = environment.games[game.profileKey].orEmpty().keys - FexPreset.environmentKeys - - GameEnvironment.NO_STEAM + GameEnvironment.NO_STEAM - GameEnvironment.GAME_RESOLUTION return SelectedGameProfile( appId = selectedAppId, name = game.name, @@ -68,6 +74,8 @@ data class SelectedGameProfile( environmentOverrides = otherEnvironment.size, windowsComponentNames = gameWindowsComponents.map(WinComponentNames::of), startWithoutSteam = GameEnvironment.gameNoSteam(environment, game.profileKey), + frameGen = frameGenMode, + frameGenInherited = frameGenInherited, ) } } diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionArtifacts.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionArtifacts.kt index cb766a2de3..3ac0ef8ab6 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionArtifacts.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionArtifacts.kt @@ -77,6 +77,7 @@ object SessionArtifacts { copySteamLogs(context, dir, record, steamArch) VacDiagnostics.collect(context, dir) SessionLogCapture.dumpCrashBuffer(File(dir, "crash.log")) + SessionLogCapture.dumpMemoryPressure(File(dir, "memory-pressure.log")) val scrubbed = markScrubbed(scrubTree(record)) SessionEvents.record("session.artifacts_collected", mapOf("reason" to reason), dir) if (scrubbed) File(dir, COMPLETE_MARKER).writeText("collected: $reason at ${now()}\n") @@ -594,6 +595,10 @@ object SessionArtifacts { if (!crashLog.exists()) { SessionLogCapture.dumpCrashBuffer(crashLog) } + val memoryLog = File(dir, "memory-pressure.log") + if (newest && !memoryLog.exists()) { + SessionLogCapture.dumpMemoryPressure(memoryLog) + } if (stopWhenSessionStarts && SessionState.running) { record.failed = true record.deferred = true diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt index 8c5e7431b1..13348cef74 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt @@ -70,6 +70,8 @@ object SessionFiles { GameEnvironmentStore.publish(context) WinComponents.publish(context) val files = arrayOf( + "rockstar/helpers/Launcher32.exe" to "usr/local/lib/droiddeck-rockstar/Launcher32.exe", + "rockstar/helpers/Launcher64.exe" to "usr/local/lib/droiddeck-rockstar/Launcher64.exe", "usr/local/bin/droiddeck-game-env" to "usr/local/bin/droiddeck-game-env", "usr/local/bin/droiddeck-game-gpu" to "usr/local/bin/droiddeck-game-gpu", "usr/local/bin/droiddeck-diagnostic-inventory" to "usr/local/bin/droiddeck-diagnostic-inventory", @@ -241,7 +243,7 @@ object SessionFiles { var installed = false try { target.parentFile?.mkdirs() - context.assets.open("linuxfs/$asset").use { input -> + (if (asset.startsWith("rockstar/")) requireNotNull(javaClass.getResourceAsStream("/$asset")) else context.assets.open("linuxfs/$asset")).use { input -> staged.outputStream().use { output -> FileUtils.copy(input, output) } } installed = staged.setExecutable(true, false) && staged.renameTo(target) diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionPipController.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionPipController.kt index 1b26e7de29..f32fe2abbf 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionPipController.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionPipController.kt @@ -21,6 +21,7 @@ class SessionPipController( private set private var suppressAuto = false private var visit = false + private var requested = false private var lastParams = "" val floating get() = transitioning || activity.isInPictureInPictureMode @@ -47,7 +48,7 @@ class SessionPipController( return builder.build() } - fun enter() { + fun enter(explicit: Boolean = true) { if (!eligible()) { Toast.makeText(activity, R.string.pip_not_ready, Toast.LENGTH_SHORT).show() return @@ -59,8 +60,10 @@ class SessionPipController( return } prepare() + requested = explicit val entered = runCatching { activity.enterPictureInPictureMode(params(bounds())) }.getOrDefault(false) if (!entered) { + requested = false restore() Toast.makeText(activity, R.string.pip_unavailable, Toast.LENGTH_SHORT).show() } @@ -68,7 +71,7 @@ class SessionPipController( fun leaving() { if (!automatic() || !allowed()) return - if (Build.VERSION.SDK_INT < 31) enter() else prepare() + if (Build.VERSION.SDK_INT < 31) enter(explicit = false) else prepare() } private fun prepare() { @@ -85,6 +88,8 @@ class SessionPipController( showPipUi(true) SessionService.beginPip(activity) SessionService.setActivityVisible(activity, true) + if (requested) runCatching { com.droiddeck.launcher.HomeApp.showFrontEnd(activity) } + requested = false } else restore() refresh(true) } diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt index 4b0a94f7b6..4c567fd1b6 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt @@ -201,6 +201,18 @@ object SessionPrefs { prefs(context).edit().putBoolean("gameStoresEnabled", on).apply() } + fun soundtracksEnabled(context: Context): Boolean = prefs(context).getBoolean("soundtracksEnabled", true) + + fun setSoundtracksEnabled(context: Context, on: Boolean) { + prefs(context).edit().putBoolean("soundtracksEnabled", on).apply() + } + + fun soundtracksIngame(context: Context): Boolean = prefs(context).getBoolean("soundtracksIngame", false) + + fun setSoundtracksIngame(context: Context, on: Boolean) { + prefs(context).edit().putBoolean("soundtracksIngame", on).apply() + } + fun gameStoresSpeedTier(context: Context): String = prefs(context).getString("gameStoresSpeedTier", "fast") ?: "fast" fun setGameStoresSpeedTier(context: Context, tier: String) { @@ -253,6 +265,12 @@ object SessionPrefs { prefs(context).edit().putBoolean("railLabels", show).apply() } + fun agentTab(context: Context): Boolean = prefs(context).getBoolean("agentTab", true) + + fun setAgentTab(context: Context, show: Boolean) { + prefs(context).edit().putBoolean("agentTab", show).apply() + } + fun libraryShowUninstalled(context: Context): Boolean = prefs(context).getBoolean("libraryShowUninstalled", false) fun setLibraryShowUninstalled(context: Context, show: Boolean) { @@ -271,6 +289,24 @@ object SessionPrefs { prefs(context).edit().putString("storesTabHidden", hidden.joinToString(",")).apply() } + fun navTabOrder(context: Context): List = idList(prefs(context).getString("navTabOrder", null)) + + fun setNavTabOrder(context: Context, order: List) { + prefs(context).edit().putString("navTabOrder", order.joinToString(",")).apply() + } + + fun navTabShelved(context: Context): Set = idList(prefs(context).getString("navTabShelved", "soundtracks,agent")).toSet() + + fun setNavTabShelved(context: Context, keys: Set) { + prefs(context).edit().putString("navTabShelved", keys.joinToString(",")).apply() + } + + fun navTabHidden(context: Context): Set = idList(prefs(context).getString("navTabHidden", null)).toSet() + + fun setNavTabHidden(context: Context, keys: Set) { + prefs(context).edit().putString("navTabHidden", keys.joinToString(",")).apply() + } + private fun idList(raw: String?): List = raw.orEmpty().split(',').map { it.trim() }.filter { it.isNotEmpty() } val STORES_SORTS = listOf("lastPlayed", "recentlyInstalled", "titleAsc", "titleDesc", "sizeDesc", "sizeAsc", "releaseDateDesc") @@ -1048,6 +1084,13 @@ object SessionPrefs { prefs(context).edit().putBoolean("vac_diagnostics", on).apply() } + fun buildWatermarkEnabled(context: Context): Boolean = + BuildWatermarkSetting.enabled(context) + + fun setBuildWatermarkEnabled(context: Context, on: Boolean) { + BuildWatermarkSetting.setEnabled(context, on) + } + private fun resolutionCap(context: Context, mode: String): Int = prefs(context).getInt("resolutionCap.$mode", 720) fun resolutionChosen(context: Context, mode: String): Boolean = diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt index 4faa870866..3e7f30b15f 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt @@ -588,6 +588,14 @@ class SessionService : Service() { guest.add("BL_WIDTH=" + size.first) guest.add("BL_HEIGHT=" + size.second) + if (noSteamGame()) runCatching { + val scope = NoSteamLaunch.scopeOf(SessionState.program, SessionState.programArgs) { NoSteamLaunch.battleNetTitleScope(this, it) } + NoSteamLaunch.resolution(GameEnvironmentStore.read(this), scope, size) + }.onFailure { Log.w(TAG, "game resolution", it) }.getOrNull()?.let { (w, h) -> + guest.add("BL_GAME_WIDTH=$w") + guest.add("BL_GAME_HEIGHT=$h") + Log.i(TAG, "game resolution: ${w}x$h on a ${size.first}x${size.second} output") + } if (SessionState.followScreen || size.first < size.second || SessionPrefs.orientation(this) == android.content.pm.ActivityInfo.SCREEN_ORIENTATION_USER) guest.add("BL_FOLLOW_OUTPUT=1") @@ -822,6 +830,7 @@ class SessionService : Service() { }, zramControl = File(filesDir, "${LinuxRuntime.DIR}/tmp/.bl-zram"), clockControl = File(filesDir, "${LinuxRuntime.DIR}/tmp/.bl-clock"), + mapClockControl = { WaylandCompositor.nativeSetClockControl(it.path) }, pagedOut = { processes, unacknowledged, residentKb, swapKb, swapBeforeKb, millis -> Log.i(TAG, "paged out $processes processes ($unacknowledged unacknowledged) in $millis ms: " + "resident ${residentKb / 1024} MB, zram ${swapBeforeKb / 1024} -> ${swapKb / 1024} MB") @@ -1606,10 +1615,11 @@ class SessionService : Service() { 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 + val spared = OrphanReaper.spared() var killed = 0 for (proc in procs) { val pid = proc.name.toIntOrNull() ?: continue - if (pid == me) continue + if (pid == me || pid in spared) continue val exe = try { File(proc, "exe").canonicalPath } catch (e: Exception) { continue } if (!exe.startsWith(rootfs)) continue android.os.Process.killProcess(pid) @@ -1621,10 +1631,11 @@ class SessionService : Service() { private fun killStragglers() { val me = android.os.Process.myPid() val procs = File("/proc").listFiles { f -> f.name.all { it.isDigit() } } ?: return + val spared = OrphanReaper.spared() var killed = 0 for (proc in procs) { val pid = proc.name.toIntOrNull() ?: continue - if (pid == me) continue + if (pid == me || pid in spared) continue val cmdline = try { File(proc, "cmdline").readBytes().toString(Charsets.UTF_8).replace('\u0000', ' ') } catch (e: Exception) { diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionSuspendController.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionSuspendController.kt index b0a6852144..ad7360d8ee 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionSuspendController.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionSuspendController.kt @@ -23,6 +23,7 @@ internal class SessionSuspendController( private val executor: ExecutorService = Executors.newSingleThreadExecutor(), private val zramControl: File? = null, private val clockControl: File? = null, + private val mapClockControl: (File) -> Unit = {}, private val nowNanos: () -> Long = System::nanoTime, private val pagedOut: (processes: Int, unacknowledged: Int, residentKb: Long, swapKb: Long, swapBeforeKb: Long, millis: Long) -> Unit = { _, _, _, _, _, _ -> }, @@ -154,6 +155,7 @@ internal class SessionSuspendController( frozenSince = null val control = clockControl?.takeIf { it.isFile && it.length() >= Long.SIZE_BYTES } ?: return try { + mapClockControl(control) RandomAccessFile(control, "rw").use { file -> val bytes = ByteArray(Long.SIZE_BYTES) file.readFully(bytes) diff --git a/app/src/main/java/com/droiddeck/launcher/session/SettingsReset.kt b/app/src/main/java/com/droiddeck/launcher/session/SettingsReset.kt index 67f013b78f..7e4053a14a 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SettingsReset.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SettingsReset.kt @@ -14,16 +14,16 @@ object SettingsReset { internal val SESSION_KEYS = setOf( "orientation", "launcherFullscreen", "animations", "lowStorageWarning", "theme", "runSteamAtStartup", "startupSession", "addedGamesArt", "dualScreenMode", "dualScreenSessionMode", "dualScreenLauncher", "dualScreenSessionControls", "androidTextFieldKeyboard", - "gameStoresEnabled", "gameStoresSpeedTier", "gameStoresParallel", "storesOpenTab", "storesShowMature", + "gameStoresEnabled", "soundtracksEnabled", "soundtracksIngame", "gameStoresSpeedTier", "gameStoresParallel", "storesOpenTab", "storesShowMature", "storesInstallLanguage", "hud", "hudDeck", "hudFps", "hudBattery", "hudGraph", "hudColor", "hudOpacity", "__KEEP_droidDeckHud__", "__KEEP_droidDeckHudPos__", "backHold", "backActionsInverted", "backDoubleTapMs", "touch", "osc", "shape", "steamController", "gamepadLeft", "gamepadRight", "pipAutoEnter", "unfoldedControls", "unfoldedControlsWithController", - "stretch16x9", "picturePosition", "railLabels", "pcKeyboardSize", "pcKeyboardOpacity", "pcKeyboardHiddenKeys", + "stretch16x9", "picturePosition", "railLabels", "agentTab", "navTabOrder", "navTabShelved", "navTabHidden", "pcKeyboardSize", "pcKeyboardOpacity", "pcKeyboardHiddenKeys", "gpuDriverMode", "androidDriver", "linuxDriver", "linuxDriver.steam", "linuxDriver.desktop", "tuSysmem", "glThread", "noGlError", "zinkLazy", "mangoapp", "gpuClockPin", "gamescopeRealtime", "ramCapMb", "vramCapMb", "zramClient", "directAudio", "mic", "wifiDiscovery", "clientCpusOverride", "clientCpus", "gameCpus", "noXalia", "fastSync", "fsyncFirst", "syncFallback", "prootNoSeccomp", "prootFastPath", "nativeUserland", "cursorComposite", - "guestHostname", "fexPreset", "forceSsbs", "logs", "gameDebugLogsEnabled", "enhancedDiagnosticsNext", "storageDiagnostics", + "guestHostname", "fexPreset", "forceSsbs", "logs", "gameDebugLogsEnabled", "enhancedDiagnosticsNext", "storageDiagnostics", "buildWatermark", "upscaler", "upscaleSharpness", "screenEffects", "textureAnisotropy", "textureLodBias", "steamDownloadsInBackground", "steam_offline", "bootMovie", "bootMovieSound", "bootMovieVolume", "bootMovieSeconds", "bootMovieApplyNext", "bootMovieSteamSeen", @@ -43,6 +43,7 @@ object SettingsReset { var ok = true val session = context.getSharedPreferences("session", Context.MODE_PRIVATE) session.edit().apply { session.all.keys.filter { isSessionSetting(it) }.forEach { remove(it) } }.commit() + BuildWatermarkSetting.setEnabled(context, true) ControllerPrefs.resetAll(context) InputProfiles.resetAll(context) context.getSharedPreferences("app-ui", Context.MODE_PRIVATE).edit().clear().commit() diff --git a/app/src/main/java/com/droiddeck/launcher/session/SteamLibraries.kt b/app/src/main/java/com/droiddeck/launcher/session/SteamLibraries.kt index 0846763599..8b219470c8 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SteamLibraries.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SteamLibraries.kt @@ -82,13 +82,14 @@ object SteamLibraries { /** Reads storage; call off the main thread. */ fun found(context: Context): List { val entries = list(context) - val taken = taken(context, entries) + AddedGames.roots(context).map { canonical(it.host) } + val taken = taken(context, entries) + GameStorage.gamesFolderLibraries(context).map { canonical(it.host) } + val gamesFolders = AddedGames.roots(context).map { canonical(it.host) } val hits = ArrayList>() for (root in StorageRoots.list(context)) { if (!root.readable) continue for (dir in candidates(rawView(root.dir), SCAN_DEPTH)) { val games = gameCount(dir) - if (games > 0 && File(dir, "steamapps").canWrite() && taken.none { overlaps(it, canonical(dir)) }) hits += dir to games + if (games > 0 && File(dir, "steamapps").canWrite() && offered(taken, gamesFolders, canonical(dir))) hits += dir to games } } val picked = ArrayList>() @@ -101,6 +102,9 @@ object SteamLibraries { } } + internal fun offered(taken: List, gamesFolders: List, dir: String): Boolean = + taken.none { overlaps(it, dir) } && gamesFolders.none { it != dir && overlaps(it, dir) } + /** The FUSE view under /storage hides files other apps wrote unless DroidDeck has all files access; the raw card mount does not. */ private fun rawView(dir: File): File { if (!dir.path.startsWith("/storage/") || dir.path.startsWith("/storage/emulated")) return dir @@ -171,7 +175,7 @@ object SteamLibraries { internal fun overlaps(a: String, b: String): Boolean = a == b || a.startsWith("$b/") || b.startsWith("$a/") - private fun canonical(file: File): String = UsbLink.storagePath(runCatching { file.canonicalPath }.getOrDefault(file.absolutePath)) + internal fun canonical(file: File): String = UsbLink.storagePath(runCatching { file.canonicalPath }.getOrDefault(file.absolutePath)) private const val SCAN_DEPTH = 2 private const val SCAN_LIMIT = 4000 diff --git a/app/src/main/java/com/droiddeck/launcher/storage/SteamStorage.kt b/app/src/main/java/com/droiddeck/launcher/storage/SteamStorage.kt index de3648e83c..2111bfdee1 100644 --- a/app/src/main/java/com/droiddeck/launcher/storage/SteamStorage.kt +++ b/app/src/main/java/com/droiddeck/launcher/storage/SteamStorage.kt @@ -11,6 +11,8 @@ object SteamStorage { const val PROTON_11_ARM = 4628740 const val REDISTRIBUTABLES = 228980 const val FEX = 3127680 + const val EAC_RUNTIME = 1826330 + const val BATTLEYE_RUNTIME = 1161040 const val ARM_TOOL = "droiddeck-proton-arm64" const val ARM_11_TOOL = "droiddeck-proton-11-arm64" @@ -18,7 +20,7 @@ object SteamStorage { private val VALVE_TOOLS = setOf( 858280, 961940, 1054830, 1113280, 1245040, 1420170, 1493710, 1580130, 1887720, 2180100, 2348590, 2805730, 3029110, 3658110, 4183110, 4628710, 4690330, - SCOUT, SOLDIER, SNIPER, ARM_RUNTIME, PROTON_ARM, PROTON_11_ARM, REDISTRIBUTABLES, FEX, + SCOUT, SOLDIER, SNIPER, ARM_RUNTIME, PROTON_ARM, PROTON_11_ARM, REDISTRIBUTABLES, FEX, EAC_RUNTIME, BATTLEYE_RUNTIME, ) private val APP_ID = Regex("^\\s*\"appid\"\\s*\"(\\d+)\"", RegexOption.MULTILINE) @@ -93,6 +95,7 @@ object SteamStorage { val dir = m.installDir.orEmpty() return when { m.appId == SCOUT || m.appId == SOLDIER || dir == "SteamLinuxRuntime" || dir == "SteamLinuxRuntime_soldier" -> Kind.OLD_RUNTIME + m.appId == EAC_RUNTIME || m.appId == BATTLEYE_RUNTIME -> Kind.REQUIRED dir.startsWith("Proton") && "ARM64" in dir -> Kind.ARM_PROTON m.appId == PROTON_ARM || m.appId == PROTON_11_ARM -> Kind.ARM_PROTON dir.startsWith("Proton ") -> Kind.X86_PROTON diff --git a/app/src/main/java/com/droiddeck/launcher/storage/StorageScan.kt b/app/src/main/java/com/droiddeck/launcher/storage/StorageScan.kt index 9c5fff91a9..3a7c52db38 100644 --- a/app/src/main/java/com/droiddeck/launcher/storage/StorageScan.kt +++ b/app/src/main/java/com/droiddeck/launcher/storage/StorageScan.kt @@ -26,7 +26,7 @@ class GameUsage( } enum class ToolState { IN_USE, REQUIRED, UNUSED } -enum class ToolReason { DEFAULT_PROTON, PROTON, FEX_RUNTIME, ARM_RUNTIME, REDISTRIBUTABLES, FEX, STEAM_TOOL, OLD_RUNTIME, X86_PROTON, CUSTOM, CUSTOM_UNKNOWN, X64_CLIENT } +enum class ToolReason { DEFAULT_PROTON, PROTON, FEX_RUNTIME, ARM_RUNTIME, REDISTRIBUTABLES, FEX, ANTICHEAT_RUNTIME, STEAM_TOOL, OLD_RUNTIME, X86_PROTON, CUSTOM, CUSTOM_UNKNOWN, X64_CLIENT } class ToolUsage( val key: String, val name: String, val bytes: Long, val state: ToolState, val reason: ToolReason, @@ -153,6 +153,7 @@ object StorageScan { SteamStorage.ARM_RUNTIME -> ToolReason.ARM_RUNTIME SteamStorage.REDISTRIBUTABLES -> ToolReason.REDISTRIBUTABLES SteamStorage.FEX -> ToolReason.FEX + SteamStorage.EAC_RUNTIME, SteamStorage.BATTLEYE_RUNTIME -> ToolReason.ANTICHEAT_RUNTIME else -> ToolReason.STEAM_TOOL } } diff --git a/app/src/main/java/com/droiddeck/launcher/stores/CloudSaves.kt b/app/src/main/java/com/droiddeck/launcher/stores/CloudSaves.kt index f68ab0ce62..106719d559 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/CloudSaves.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/CloudSaves.kt @@ -87,7 +87,7 @@ object CloudSaves { val item = sidecar.extra["catalogItemId"].orEmpty() if (ns.isEmpty() || item.isEmpty()) "" else EpicApiClient.getCustomAttribute(token, ns, item, "CloudSaveFolder") } - Store.AMAZON, Store.ITCH, Store.GAMEJOLT, Store.XBOX, Store.BATTLENET, Store.EA, Store.UBISOFT -> "" + Store.AMAZON, Store.ITCH, Store.GAMEJOLT, Store.XBOX, Store.BATTLENET, Store.EA, Store.UBISOFT, Store.ROCKSTAR -> "" } ?: return null p.edit() .putString("cloud_template_$id", fetched.ifEmpty { TEMPLATE_NONE }) @@ -148,7 +148,7 @@ object CloudSaves { val dir = when (store) { Store.GOG -> CloudSavePaths.gog(template, pfx, folder) Store.EPIC -> CloudSavePaths.epic(template, pfx, folder, EpicCredentialStore.load(context)?.accountId.orEmpty(), id) - Store.AMAZON, Store.ITCH, Store.GAMEJOLT, Store.XBOX, Store.BATTLENET, Store.EA, Store.UBISOFT -> null + Store.AMAZON, Store.ITCH, Store.GAMEJOLT, Store.XBOX, Store.BATTLENET, Store.EA, Store.UBISOFT, Store.ROCKSTAR -> null } return dir to (if (dir == null) "unresolved" else "ok") } @@ -173,7 +173,7 @@ object CloudSaves { val account = EpicCredentialStore.load(context)?.accountId.orEmpty() if (token == null || account.isEmpty()) null else EpicCloud(account, id, token) } - Store.AMAZON, Store.ITCH, Store.GAMEJOLT, Store.XBOX, Store.BATTLENET, Store.EA, Store.UBISOFT -> null + Store.AMAZON, Store.ITCH, Store.GAMEJOLT, Store.XBOX, Store.BATTLENET, Store.EA, Store.UBISOFT, Store.ROCKSTAR -> null } private fun gogScopedToken(context: Context, id: String, clientId: String): String? { diff --git a/app/src/main/java/com/droiddeck/launcher/stores/LoginFlows.kt b/app/src/main/java/com/droiddeck/launcher/stores/LoginFlows.kt index 980f496b26..a1b54088eb 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/LoginFlows.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/LoginFlows.kt @@ -15,6 +15,7 @@ internal object LoginFlows { Store.GAMEJOLT -> gameJoltFlow(browserUserAgent) Store.UBISOFT -> ubisoftFlow(browserUserAgent) Store.EA -> eaFlow(browserUserAgent) + Store.ROCKSTAR -> rockstarFlow(browserUserAgent) Store.ITCH, Store.XBOX, Store.BATTLENET -> null } @@ -22,6 +23,7 @@ internal object LoginFlows { @Volatile var amazonFlow: () -> StoreLoginActivity.Flow? = { null } @Volatile var ubisoftFlow: (String) -> StoreLoginActivity.Flow? = { null } @Volatile var eaFlow: (String) -> StoreLoginActivity.Flow? = { null } + @Volatile var rockstarFlow: (String) -> StoreLoginActivity.Flow? = { null } @Volatile var gameJoltFlow: (String) -> StoreLoginActivity.Flow? = { null } private class GogFlow(private val state: String, override val userAgent: String) : StoreLoginActivity.Flow { diff --git a/app/src/main/java/com/droiddeck/launcher/stores/Store.kt b/app/src/main/java/com/droiddeck/launcher/stores/Store.kt index b8a6e8931e..b48530fbea 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/Store.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/Store.kt @@ -9,7 +9,8 @@ enum class Store(val id: String, val label: String, val shortLabel: String) { GAMEJOLT("gamejolt", "Game Jolt", "Game Jolt"), BATTLENET("battlenet", "Battle.net", "Battle.net"), UBISOFT("ubisoft", "Ubisoft Connect", "Ubisoft"), - EA("ea", "EA", "EA"); + EA("ea", "EA", "EA"), + ROCKSTAR("rockstar", "Rockstar Games", "Rockstar"); val folder: String get() = if (this == ITCH) "itch" else shortLabel diff --git a/app/src/main/java/com/droiddeck/launcher/stores/StoreAccounts.kt b/app/src/main/java/com/droiddeck/launcher/stores/StoreAccounts.kt index 5de9b5e1ab..5e30fb7a5d 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/StoreAccounts.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/StoreAccounts.kt @@ -67,8 +67,8 @@ object StoreAccounts { fun write(context: Context, store: Store, json: JSONObject) { unavailable.remove(store) val f = credentialsFile(context, store) - if (seal(f, json, retry = store == Store.XBOX) == null) { - check(store != Store.XBOX) { "Android Keystore is unavailable for Xbox credentials" } + if (seal(f, json, retry = store == Store.XBOX || store == Store.ROCKSTAR) == null) { + check(store != Store.XBOX && store != Store.ROCKSTAR) { "Android Keystore is unavailable for ${store.label} credentials" } put(f, json.toString()) } } diff --git a/app/src/main/java/com/droiddeck/launcher/stores/StoreCatalog.kt b/app/src/main/java/com/droiddeck/launcher/stores/StoreCatalog.kt index cb46d23601..e87266df65 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/StoreCatalog.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/StoreCatalog.kt @@ -106,6 +106,7 @@ fun detailCatalogItem( library.firstOrNull { it.store == store && it.id == id } ?: found.firstOrNull { it.store == store && it.id == id } ?: shelves?.all?.firstOrNull { it.store == store && it.id == id } + ?: shelves?.all?.firstOrNull { it.store == store && it.extra[StoreFront.STORE_CARD] == id } fun mergeItems(old: List?, new: List): List { if (old.isNullOrEmpty()) return new diff --git a/app/src/main/java/com/droiddeck/launcher/stores/StoreFront.kt b/app/src/main/java/com/droiddeck/launcher/stores/StoreFront.kt new file mode 100644 index 0000000000..5791656111 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/stores/StoreFront.kt @@ -0,0 +1,119 @@ +package com.droiddeck.launcher.stores + +import android.content.SharedPreferences +import org.json.JSONArray +import org.json.JSONObject +import java.text.Normalizer +import java.util.Locale + +/** Store shelves fetched from a public catalog, kept in memory and on disk between refreshes. */ +internal class StoreFront( + private val store: Store, + private val prefs: () -> SharedPreferences, + private val fetch: () -> Catalog, + private val key: String = "store_front", + private val ttlMs: Long = 3 * 60 * 60 * 1000L, +) { + /** One refresh: the shelves and every game the store lists, for search. */ + class Catalog(val shelves: StoreShelves, val all: List = shelves.all) + + @Volatile private var memory: Catalog? = null + @Volatile private var memoryAt = 0L + + fun cached(): StoreShelves? = cachedCatalog()?.shelves + + fun everything(): List = cachedCatalog()?.all.orEmpty() + + private fun cachedCatalog(): Catalog? = memory ?: decode(prefs().getString(key, null))?.also { memory = it } + + /** The shelves, refreshed when stale; a refresh that fails keeps the last good set. */ + fun shelves(force: Boolean): StoreShelves? { + val now = System.currentTimeMillis() + if (!force) { + memory?.takeIf { now - memoryAt in 0 until ttlMs }?.let { return it.shelves } + val at = prefs().getLong("${key}_at", 0L) + if (now - at in 0 until ttlMs) decode(prefs().getString(key, null))?.let { memory = it; memoryAt = at; return it.shelves } + } + val fresh = runCatching(fetch).onFailure { StoresState.logLine("${store.label}: store shelves failed: ${it.javaClass.simpleName} ${it.message.orEmpty().take(160)}") } + .getOrNull()?.takeUnless { it.shelves.isEmpty } + ?: return cached() + prefs().edit().putString(key, encode(fresh)).putLong("${key}_at", now).apply() + memory = fresh + memoryAt = now + return fresh.shelves + } + + private fun encode(c: Catalog): String = JSONObject().apply { + val s = c.shelves + listOf(s.whatsNew, s.deals, s.free, s.trending).zip(SHELVES).forEach { (items, k) -> put(k, JSONArray(items.map { it.id })) } + put("art", JSONArray(s.art)) + put("items", JSONArray().apply { (c.all + s.all).distinctBy { it.id }.forEach { put(itemJson(it)) } }) + }.toString() + + private fun decode(text: String?): Catalog? { + val o = text?.let { runCatching { JSONObject(it) }.getOrNull() } ?: return null + val items = o.optJSONArray("items")?.let { a -> (0 until a.length()).mapNotNull { a.optJSONObject(it)?.let(::itemFrom) } }.orEmpty() + val byId = items.associateBy { it.id } + fun shelf(k: String) = o.optJSONArray(k)?.let { a -> (0 until a.length()).mapNotNull { byId[a.optString(it)] } }.orEmpty() + val art = o.optJSONArray("art")?.let { a -> List(a.length()) { a.optString(it) }.filter { it.isNotEmpty() } }.orEmpty() + val shelves = StoreShelves(shelf("new"), shelf("deals"), shelf("free"), shelf("trending"), art).takeUnless { it.isEmpty } ?: return null + return Catalog(shelves, items) + } + + private fun itemJson(i: CatalogItem) = JSONObject() + .put("id", i.id).put("title", i.title).put("image", i.imageUrl.orEmpty()).put("tall", i.tallImageUrl.orEmpty()).put("tags", i.tags) + .put("free", i.isFree).put("hasPrice", i.hasPrice).put("final", i.finalPrice).put("orig", i.originalPrice).put("disc", i.discountPercent) + .put("url", i.storeUrl).put("dev", i.developer).put("pub", i.publisher).put("rel", i.releaseDate).put("desc", i.description) + .put("mature", i.mature).put("logo", i.logoUrl.orEmpty()).put("extra", JSONObject(i.extra as Map<*, *>)) + + private fun itemFrom(o: JSONObject): CatalogItem? { + val extra = LinkedHashMap() + o.optJSONObject("extra")?.let { e -> e.keys().forEach { k -> extra[k] = e.optString(k) } } + return CatalogItem( + store = store, id = o.optString("id").ifEmpty { return null }, title = o.optString("title").ifEmpty { return null }, + imageUrl = o.optString("image").ifEmpty { null }, tallImageUrl = o.optString("tall").ifEmpty { null }, tags = o.optString("tags"), + isFree = o.optBoolean("free"), hasPrice = o.optBoolean("hasPrice"), finalPrice = o.optString("final"), originalPrice = o.optString("orig"), + discountPercent = o.optInt("disc"), storeUrl = o.optString("url"), developer = o.optString("dev"), publisher = o.optString("pub"), + releaseDate = o.optString("rel"), description = o.optString("desc"), mature = o.optBoolean("mature"), + logoUrl = o.optString("logo").ifEmpty { null }, extra = extra, + ) + } + + companion object { + /** On an owned game standing in for a store card: the card's id, so a page opened on the card still finds it. */ + const val STORE_CARD = "storeCard" + private val SHELVES = listOf("new", "deals", "free", "trending") + private val MARKS = Regex("[\\u2122\\u00AE\\u00A9]") + private val COMBINING = Regex("\\p{M}+") + private val NOT_WORD = Regex("[^\\p{L}\\p{N}]+") + + /** A title reduced to letters and digits, so "Far Cryยฎ 6" and "Far Cry 6" meet, and "Pokรฉmon" meets "Pokemon". */ + fun titleKey(title: String): String = + Normalizer.normalize(title.replace(MARKS, ""), Normalizer.Form.NFD).replace(COMBINING, "") + .lowercase(Locale.ROOT).replace(NOT_WORD, " ").trim() + + /** + * Shelf cards the account owns become its library entry, which carries what installing needs, + * keeping the shelf's art and price. + */ + fun markOwned(s: StoreShelves, library: List?, match: (CatalogItem, CatalogItem) -> Boolean): StoreShelves { + if (library.isNullOrEmpty()) return s + fun mark(list: List) = markOwned(list, library, match) + return StoreShelves(mark(s.whatsNew), mark(s.deals), mark(s.free), mark(s.trending), s.art) + } + + fun markOwned(list: List, library: List?, match: (CatalogItem, CatalogItem) -> Boolean): List { + if (library.isNullOrEmpty()) return list + return list.map { shelf -> + val owned = library.firstOrNull { match(shelf, it) } ?: return@map shelf + owned.copy( + imageUrl = shelf.imageUrl ?: owned.imageUrl, tallImageUrl = owned.tallImageUrl ?: shelf.tallImageUrl, + tags = owned.tags.ifBlank { shelf.tags }, description = owned.description.ifBlank { shelf.description }, + releaseDate = owned.releaseDate.ifBlank { shelf.releaseDate }, storeUrl = shelf.storeUrl.ifBlank { owned.storeUrl }, + developer = owned.developer.ifBlank { shelf.developer }, mature = shelf.mature, + extra = owned.extra + (STORE_CARD to shelf.id), + ) + }.distinctBy { it.id } + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/stores/StoreLaunch.kt b/app/src/main/java/com/droiddeck/launcher/stores/StoreLaunch.kt index 222b53702e..f45a23c654 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/StoreLaunch.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/StoreLaunch.kt @@ -18,8 +18,9 @@ object StoreLaunch { const val EA_ORIGIN = "C:\\Program Files (x86)\\Origin\\Origin.exe" fun writeLauncher(folder: File, sidecar: StoreGameSidecar): StoreGameSidecar { - val needs = sidecar.args.isNotEmpty() || sidecar.env.isNotEmpty() || sidecar.store == Store.EPIC || sidecar.store == Store.EA || sidecar.store == Store.UBISOFT + val needs = sidecar.args.isNotEmpty() || sidecar.env.isNotEmpty() || sidecar.store == Store.EPIC || sidecar.store == Store.EA || sidecar.store == Store.UBISOFT || sidecar.store == Store.ROCKSTAR val file = File(folder, LAUNCHER) + if (sidecar.store == Store.ROCKSTAR && java.nio.file.Files.isSymbolicLink(file.toPath())) return sidecar.copy(launcher = null) if (!needs) { file.delete(); return sidecar.copy(launcher = null) } file.writeText(launcherText(sidecar)) return sidecar.copy(launcher = LAUNCHER) @@ -31,11 +32,11 @@ object StoreLaunch { ?: exe.substringBeforeLast('\\', "") val lines = ArrayList() lines += "@echo off" - lines += "setlocal" - lines += "rem Written by DroidDeck for ${sidecar.store.label}: ${sidecar.title}. Steam's shortcut runs this file." + lines += if (sidecar.store == Store.ROCKSTAR) "setlocal DisableDelayedExpansion" else "setlocal" + if (sidecar.store != Store.ROCKSTAR) lines += "rem Written by DroidDeck for ${sidecar.store.label}: ${sidecar.title}. Steam's shortcut runs this file." lines += "cd /d \"%~dp0$dir\"" for ((k, v) in sidecar.env) if (ENV_NAME.matches(k)) lines += "set \"$k=${v.replace("\"", "")}\"" - val args = sidecar.args.joinToString(" ") { quoteArg(it) } + val args = sidecar.args.joinToString(" ") { if (sidecar.store == Store.ROCKSTAR) batchArg(it) else quoteArg(it) } val run = "\"%~dp0$exe\"" + (if (args.isNotEmpty()) " $args" else "") if (sidecar.store == Store.EPIC) { lines += "if exist \"%~dp0$EPIC_ARGS\" goto client" @@ -54,6 +55,12 @@ object StoreLaunch { lines += "del \"%~dp0$EPIC_ARGS\"" lines += "if exist \"%~dp0$EPIC_CODE\" del \"%~dp0$EPIC_CODE\"" lines += "set \"$CLIENT_VAR=\" & \"%~dp0$exe\" %$CLIENT_VAR%" + } else if (sidecar.store == Store.ROCKSTAR) { + lines += "if not exist \"C:\\Program Files\\Rockstar Games\\Launcher\\launch.json\" goto direct" + lines += "\"C:\\Program Files\\Rockstar Games\\Launcher\\Launcher.exe\"" + lines += "exit /b %errorlevel%" + lines += ":direct" + lines += run } else if (sidecar.store == Store.UBISOFT) { lines += "if not exist \"%~dp0$UBISOFT_LAUNCH\" goto direct" lines += "if not exist \"$UBISOFT_SERVICE\" goto direct" @@ -77,6 +84,22 @@ object StoreLaunch { private val ENV_NAME = Regex("[A-Za-z_][A-Za-z0-9_]*") + private fun batchArg(arg: String): String { + val quoted = StringBuilder("\"") + var slashes = 0 + for (c in arg.filter { it >= ' ' && it != '\u007f' }) { + if (c == '\\') { slashes++; continue } + quoted.append("\\".repeat(if (c == '"') slashes * 2 + 1 else slashes)).append(c) + slashes = 0 + } + quoted.append("\\".repeat(slashes * 2)).append('"') + return quoted.toString().map { c -> when (c) { + '%' -> "%%" + in "^&|<>()\"" -> "^$c" + else -> c.toString() + } }.joinToString("") + } + fun quoteArg(arg: String): String { val clean = arg.filter { it >= ' ' && it != '\u007f' } return if (' ' in clean && !clean.contains('"')) "\"$clean\"" else clean @@ -93,12 +116,14 @@ object StoreLaunch { return Library.addedGame(context, game) } - /** Gives a Ubisoft game installed before it needed one the launcher that starts the launcher service. */ fun adopt(folder: File, sidecar: StoreGameSidecar): StoreGameSidecar { - if (sidecar.store != Store.UBISOFT || !sidecar.isInstalled) return sidecar + if (sidecar.store !in listOf(Store.UBISOFT, Store.ROCKSTAR) || !sidecar.isInstalled) return sidecar + if (sidecar.store == Store.ROCKSTAR && java.nio.file.Files.isSymbolicLink(File(folder, LAUNCHER).toPath())) return sidecar.copy(launcher = null) val wrongExe = !sidecar.exeFile(folder).isFile || sidecar.exe.contains("installer", ignoreCase = true) || sidecar.exe.contains("autorun", ignoreCase = true) - if (sidecar.launcher == LAUNCHER && !wrongExe) return sidecar - val exe = if (wrongExe) StoreExe.pick(folder, null, sidecar.title).ifEmpty { sidecar.exe } else sidecar.exe + if (sidecar.store == Store.UBISOFT && sidecar.launcher == LAUNCHER && !wrongExe) return sidecar + val metadataExe = if (sidecar.store == Store.ROCKSTAR) com.droiddeck.launcher.stores.rockstar.RockstarMetadata.find(folder)?.exe + ?.takeIf { File(folder, it).isFile && File(folder, it).canonicalPath.startsWith(folder.canonicalPath + File.separator) } else null + val exe = metadataExe ?: if (wrongExe) StoreExe.pick(folder, null, sidecar.title).ifEmpty { sidecar.exe } else sidecar.exe if (exe == sidecar.exe && sidecar.launcher == LAUNCHER && runCatching { File(folder, LAUNCHER).readText() }.getOrNull() == launcherText(sidecar)) return sidecar return runCatching { writeLauncher(folder, sidecar.copy(exe = exe)).also { it.write(folder) } }.getOrDefault(sidecar) diff --git a/app/src/main/java/com/droiddeck/launcher/stores/StoreLaunchRequests.kt b/app/src/main/java/com/droiddeck/launcher/stores/StoreLaunchRequests.kt index 18f5a161e3..c89ada3f93 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/StoreLaunchRequests.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/StoreLaunchRequests.kt @@ -76,6 +76,14 @@ object StoreLaunchRequests { JSONObject().put("ok", true).put("code", code.written).put("reason", code.reason) } } + "rockstar-launch" -> runCatching { + lastLaunched = Store.ROCKSTAR to request.optString("id") + com.droiddeck.launcher.stores.rockstar.RockstarLaunch.prepare(app, request.optString("id")) + }.getOrElse { JSONObject().put("ok", false).put("reason", "error-" + it.javaClass.simpleName) } + "rockstar-exited" -> { + if (lastLaunched == (Store.ROCKSTAR to request.optString("id"))) lastLaunched = null + JSONObject().put("ok", true) + } "ubisoft-launch" -> { val id = request.optString("id") if (id.isEmpty()) JSONObject().put("ok", false).put("reason", "no-id") diff --git a/app/src/main/java/com/droiddeck/launcher/stores/StoreLoginActivity.kt b/app/src/main/java/com/droiddeck/launcher/stores/StoreLoginActivity.kt index a07e0be855..54571ab172 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/StoreLoginActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/StoreLoginActivity.kt @@ -66,6 +66,7 @@ class StoreLoginActivity : ComponentActivity() { val pageScript: String get() = "(function(){ try { return document.body.innerText; } catch(e){ return ''; } })()" fun pageReady(result: String): Boolean = true fun forgetSignIn(done: () -> Unit) = done() + fun pageFinished(view: WebView, url: String) {} } private var store: Store? = null @@ -283,6 +284,7 @@ class StoreLoginActivity : ComponentActivity() { } override fun onPageFinished(view: WebView?, url: String?) { + if (!isPopup && url != null && view != null) flow?.pageFinished(view, url) if (url != null && view != null && flow?.readsPage == true && flow?.isRedirect(url) == true) complete(view, url) } diff --git a/app/src/main/java/com/droiddeck/launcher/stores/StoreSizes.kt b/app/src/main/java/com/droiddeck/launcher/stores/StoreSizes.kt index 5e8ce7c6d7..21969dfbe7 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/StoreSizes.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/StoreSizes.kt @@ -43,7 +43,7 @@ object StoreSizes { if (available != null) return CompletableFuture.completedFuture(available) val app = context.applicationContext val version = item.extra["version"].orEmpty() - return sizeRequests.computeIfAbsent(item.key) { + return shared(sizeRequests, item.key) { CompletableFuture.supplyAsync({ val cached = cache(app, item.store).get(item.id, version) val bytes = cached ?: runCatching { fetch(app, item) } @@ -56,7 +56,7 @@ object StoreSizes { Store.AMAZON -> AmazonPrefs.get(app).edit().putLong("size_${item.id}", it).apply() Store.ITCH, Store.GAMEJOLT -> {} Store.EA -> com.droiddeck.launcher.stores.ea.EaPrefs.get(app).edit().putLong("size_${item.id}", it).apply() - Store.GOG, Store.XBOX, Store.BATTLENET, Store.UBISOFT -> {} + Store.GOG, Store.XBOX, Store.BATTLENET, Store.UBISOFT, Store.ROCKSTAR -> {} } } }, pool).exceptionally { error -> @@ -66,6 +66,25 @@ object StoreSizes { } } + internal fun shared( + requests: ConcurrentHashMap>, + key: String, + start: () -> CompletableFuture, + ): CompletableFuture { + var created: CompletableFuture? = null + val shared = requests.computeIfAbsent(key) { CompletableFuture().also { created = it } } + if (created === shared) { + val source = runCatching(start).getOrElse { failure -> + CompletableFuture().apply { completeExceptionally(failure) } + } + source.whenComplete { bytes, error -> + if (bytes == null) requests.remove(key, shared) + if (error != null) shared.completeExceptionally(error) else shared.complete(bytes) + } + } + return shared + } + val onDisk = mutableStateMapOf() fun requestDisk(context: Context, key: String, game: InstalledStoreGame) { @@ -78,7 +97,7 @@ object StoreSizes { onDisk[key]?.let { return CompletableFuture.completedFuture(it) } val app = context.applicationContext val version = "disk:${game.sidecar.installedAt}:${game.sidecar.installVersion}" - return diskRequests.computeIfAbsent(key) { + return shared(diskRequests, key) { CompletableFuture.supplyAsync({ val c = cache(app, game.sidecar.store) c.get("disk:${game.sidecar.id}", version) @@ -113,7 +132,7 @@ object StoreSizes { AmazonManifest.parse(bytes).totalInstallSize } Store.EA -> com.droiddeck.launcher.stores.ea.EaSizes.size(context, item) - Store.GOG, Store.XBOX, Store.BATTLENET, Store.UBISOFT -> 0L + Store.GOG, Store.XBOX, Store.BATTLENET, Store.UBISOFT, Store.ROCKSTAR -> 0L Store.ITCH -> com.droiddeck.launcher.stores.itch.ItchLibrary.size(context, item) Store.GAMEJOLT -> com.droiddeck.launcher.stores.gamejolt.GameJoltBuilds.size(context, item) } } diff --git a/app/src/main/java/com/droiddeck/launcher/stores/StoresState.kt b/app/src/main/java/com/droiddeck/launcher/stores/StoresState.kt index e7a9383f32..40fedbded2 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/StoresState.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/StoresState.kt @@ -236,6 +236,27 @@ object StoresState { var itchPicking by mutableStateOf(null) var gameJoltPicking by mutableStateOf(null) + /** Store cards whose free game is being added to the account. */ + val claiming = mutableStateMapOf() + + fun canClaim(item: CatalogItem): Boolean = !item.accessible && isSignedIn(item.store) && backends[item.store]?.canClaim(item) == true + + /** Adds a free game to the account, then refreshes the library so it can be installed; [failed] runs when the store refused. */ + fun claim(context: Context, item: CatalogItem, failed: () -> Unit) { + val backend = backends[item.store] ?: return failed() + if (claiming.put(item.key, true) == true) return + val app = context.applicationContext + background("stores-claim", onFailure = { main.post { claiming.remove(item.key); failed() } }) { + val ok = backend.claim(app, item) + logLine("${item.store.label}: ${item.title} ${if (ok) "added to the library" else "could not be added; opening the store page"}") + if (ok) backend.syncLibrary(app, true) + main.post { + claiming.remove(item.key) + if (!ok) failed() + } + } + } + fun requestInstall(context: Context, item: CatalogItem) { askForNotifications(context) if (item.store == Store.ITCH && item.extra["uploadId"].isNullOrEmpty()) { itchPicking = item; return } @@ -359,6 +380,12 @@ interface StoreBackend { fun syncLibrary(context: Context, force: Boolean) fun loadShelves(context: Context, force: Boolean) fun search(context: Context, query: String): List = emptyList() + + /** Whether this store can add a free game to the account itself, rather than through its website. */ + fun canClaim(item: CatalogItem): Boolean = false + + /** Adds a free game to the account; true once the store has it in the account's library. */ + fun claim(context: Context, item: CatalogItem): Boolean = false fun install(context: Context, item: CatalogItem, root: java.io.File) fun uninstall(context: Context, game: InstalledStoreGame) } diff --git a/app/src/main/java/com/droiddeck/launcher/stores/ea/EaApi.kt b/app/src/main/java/com/droiddeck/launcher/stores/ea/EaApi.kt index 185e23f424..55ecf79455 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/ea/EaApi.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/ea/EaApi.kt @@ -22,6 +22,7 @@ object EaApi { val downloadable: Boolean, val trial: Boolean, val ownership: List, + val productName: String = "", ) class Offer( @@ -109,6 +110,7 @@ object EaApi { downloadable = product.optBoolean("downloadable", true), trial = product.optJSONObject("trialDetails")?.optString("trialType").orEmpty().let { it.isNotEmpty() && it != "null" }, ownership = (0 until (methods?.length() ?: 0)).map { methods!!.optString(it) }, + productName = product.optString("name").replace("\n", " ").trim(), ) } val next = owned.optString("next").takeIf { it.isNotBlank() && it != "null" } @@ -197,6 +199,18 @@ object EaApi { } } + /** The free offer EA sells under a store slug, or null when the game has none. */ + fun freeOffer(token: String, slug: String): String? { + val variables = JSONObject().put("slug", slug).put("locale", "en-us").put("overrideCountryCode", "US") + val product = call(token, "GetGameProductOfferIds", variables).optJSONObject("game")?.optJSONObject("lowestPriceGameProduct") ?: return null + return product.optString("originOfferId").takeIf { product.optBoolean("isFree") && it.isNotBlank() && it != "null" } + } + + /** Adds a free offer to the account, as the EA app's "Get for free" does; the answer names what EA refused. */ + fun grantEntitlement(token: String, offerId: String): JSONObject = + call(token, "grantEntitlement", JSONObject().put("input", JSONObject().put("offerId", offerId).put("source", EaAuth.CLIENT_ID))) + .optJSONObject("grantEntitlement") ?: throw EaApiException(0, "EA gave no answer to the grant") + fun legacyEntitlements(token: String): List { val out = ArrayList() var next: String? = "0" diff --git a/app/src/main/java/com/droiddeck/launcher/stores/ea/EaBackend.kt b/app/src/main/java/com/droiddeck/launcher/stores/ea/EaBackend.kt index 091243ae53..bd8d5c1212 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/ea/EaBackend.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/ea/EaBackend.kt @@ -11,6 +11,7 @@ import com.droiddeck.launcher.stores.InstalledStoreGame import com.droiddeck.launcher.stores.LoginFlows import com.droiddeck.launcher.stores.Store import com.droiddeck.launcher.stores.StoreBackend +import com.droiddeck.launcher.stores.StoreFront import com.droiddeck.launcher.stores.StoreInstallRoot import com.droiddeck.launcher.stores.StoreLoginActivity import com.droiddeck.launcher.stores.StoresState @@ -40,6 +41,8 @@ object EaBackend : StoreBackend { val app = context.applicationContext EaAuth.signOut(app) EaLibrary.reset(app) + signOuts.incrementAndGet() + StoresState.post { StoresState.shelves.remove(store) } EaUpdates.available.clear() runCatching { WebCookies.expire(EaLogin.SIGN_IN_URLS, ".ea.com", listOf("/")) {} } } @@ -50,7 +53,32 @@ object EaBackend : StoreBackend { Thread({ EaLibrary.sync(app, force) }, "ea-sync").start() } - override fun loadShelves(context: Context, force: Boolean) {} + override fun loadShelves(context: Context, force: Boolean) { + val app = context.applicationContext + val account = signOuts.get() + EaStore.cached(app)?.let { s -> StoresState.post { StoresState.shelves[store] = StoreFront.markOwned(s, StoresState.library[store], EaStore::sameGame) } } + Thread({ + val shelves = EaStore.featured(app, force) ?: return@Thread + StoresState.post { if (signOuts.get() == account) StoresState.shelves[store] = StoreFront.markOwned(shelves, StoresState.library[store], EaStore::sameGame) } + }, "ea-shelves").start() + } + + private val signOuts = java.util.concurrent.atomic.AtomicInteger() + + override fun canClaim(item: CatalogItem): Boolean = item.isFree && !item.extra["slug"].isNullOrEmpty() + + override fun claim(context: Context, item: CatalogItem): Boolean { + val app = context.applicationContext + val token = EaAuth.accessToken(app) ?: return false + val slug = item.extra["slug"] ?: return false + val offer = EaApi.freeOffer(token, slug) ?: run { StoresState.logLine("ea: no free offer for $slug"); return false } + val answer = EaApi.grantEntitlement(token, offer) + StoresState.logLine("ea: grant $offer for $slug: $answer") + return answer.optBoolean("success") || answer.optJSONArray("entitledOfferIds")?.let { ids -> (0 until ids.length()).any { ids.optString(it) == offer } } == true + } + + override fun search(context: Context, query: String): List = + StoreFront.markOwned(EaStore.search(context.applicationContext, query), StoresState.library[store], EaStore::sameGame) override fun install(context: Context, item: CatalogItem, root: java.io.File) { val app = context.applicationContext diff --git a/app/src/main/java/com/droiddeck/launcher/stores/ea/EaLibrary.kt b/app/src/main/java/com/droiddeck/launcher/stores/ea/EaLibrary.kt index 2a90b2550c..336b8b6390 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/ea/EaLibrary.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/ea/EaLibrary.kt @@ -5,8 +5,8 @@ import android.content.SharedPreferences import com.droiddeck.launcher.R import com.droiddeck.launcher.stores.CatalogItem import com.droiddeck.launcher.stores.Store +import com.droiddeck.launcher.stores.StoreFront import com.droiddeck.launcher.stores.StoreNet -import com.droiddeck.launcher.stores.StoreShelves import com.droiddeck.launcher.stores.StoresState import com.droiddeck.launcher.stores.mergeItems import org.json.JSONArray @@ -36,13 +36,14 @@ data class EaGame( val masterTitleId: String = "", val cloudSaves: String = "", val locales: List = emptyList(), + val productName: String = "", ) { fun toJson(): JSONObject = JSONObject() .put("offerId", offerId).put("contentId", contentId).put("title", title).put("slug", slug) .put("tall", tall).put("wide", wide).put("logo", logo).put("version", version) .put("executePath", executePath).put("installCheck", installCheck).put("parameters", parameters) .put("multiplayerId", multiplayerId).put("masterTitleId", masterTitleId).put("cloudSaves", cloudSaves) - .put("locales", JSONArray(locales)) + .put("locales", JSONArray(locales)).put("productName", productName) companion object { fun fromJson(o: JSONObject): EaGame? { @@ -63,14 +64,15 @@ data class EaGame( masterTitleId = o.optString("masterTitleId"), cloudSaves = o.optString("cloudSaves"), locales = (0 until (locales?.length() ?: 0)).map { locales!!.optString(it) }, + productName = o.optString("productName"), ) } } } object EaLibrary { - private const val KEY_CACHE = "library_cache" - private const val KEY_SYNCED_AT = "library_synced_at" + private const val KEY_CACHE = "library_cache_v3" + private const val KEY_SYNCED_AT = "library_synced_at_v3" private const val THROTTLE_MS = 6 * 60 * 60 * 1000L private const val ART_TTL_MS = 7 * 24 * 60 * 60 * 1000L private const val ART_THREADS = 4 @@ -118,7 +120,7 @@ object EaLibrary { owned = true, sizeBytes = prefs.getLong("size_${g.offerId}", 0L), storeUrl = STORE_URL, - extra = mapOf("contentId" to g.contentId, "slug" to g.slug, "version" to g.version), + extra = mapOf("contentId" to g.contentId, "slug" to g.slug, "version" to g.version, "productName" to g.productName), logoUrl = g.logo.ifEmpty { null }, ) } @@ -137,6 +139,16 @@ object EaLibrary { }.sortedBy { it.first.name.lowercase() } } + /** + * Offers EA lists as owned whose entitlements grant no active game download: an online pass or product-key + * link such as Burnout Paradise's VALIDATED_ONLINE_ACCESS, or a Game Pass title disabled once the + * subscription lapsed. EA refuses their licence. Offers with no entitlement rows at all are left alone. + */ + internal fun withoutGameDownload(rows: List): Map> = + rows.groupBy { it.optString("productId") }.filterKeys { it.isNotEmpty() }.filterValues { offer -> + offer.none { it.optString("entitlementType").equals("ORIGIN_DOWNLOAD", true) && it.optString("status").equals("ACTIVE", true) } + } + private fun art(app: Context, token: String, slugs: Collection, gen: Int): Map { val prefs = EaPrefs.get(app) val now = System.currentTimeMillis() @@ -189,8 +201,7 @@ object EaLibrary { StoresState.post { if (gen != generation.get()) return@post StoresState.library[store] = mergeItems(StoresState.library[store], items) - val installed = StoresState.installed.filter { it.sidecar.store == store }.map { it.sidecar.id }.toSet() - StoresState.shelves[store] = StoreShelves(trending = items.filterNot { it.id in installed }, art = StoresState.shelves[store]?.art.orEmpty()) + StoresState.shelves[store]?.let { StoresState.shelves[store] = StoreFront.markOwned(it, items, EaStore::sameGame) } } } @@ -229,13 +240,28 @@ object EaLibrary { status(R.string.stores_sync_sign_in) val token = EaAuth.accessToken(app) ?: return problem(StoresState.notSignedInLine(store)) status(R.string.stores_sync_game_list) - val owned = withToken(app, token) { EaApi.owned(it) } + val listed = withToken(app, token) { EaApi.owned(it) } + val rows = try { + withToken(app, token) { EaApi.legacyEntitlements(it) } + } catch (e: Exception) { + if (e is EaApiException && e.status == 401) throw e + if (e !is EaApiException && e !is java.io.IOException) throw e + StoresState.logLine("ea: entitlements unavailable, keeping every owned product: ${e.message}") + emptyList() + } + val unplayable = withoutGameDownload(rows) + for ((id, held) in unplayable) if (listed.any { it.offerId == id }) StoresState.logLine( + "ea: left out $id, no game download: " + held.joinToString(",") { it.optString("entitlementTag") + "/" + it.optString("status") + "/" + it.optString("statusReasonCode") + "/" + it.optString("externalType") }) + val owned = listed.filterNot { it.offerId in unplayable } val offers = withToken(app, token) { EaApi.offers(it, owned.map { o -> o.offerId }) }.associateBy { it.offerId } val picked = pick(owned, offers) StoresState.logLine("ea: ${owned.size} owned products, ${picked.size} games") for ((o, offer) in picked) StoresState.logLine( "ea: owned ${o.offerId} content=${offer.contentId} master=${offer.masterTitleId} mp=${offer.multiplayerId} via=${o.ownership.joinToString("+")} type=${o.gameType}") - if (picked.isEmpty()) return problem(if (cache.isEmpty()) app.getString(R.string.stores_sync_no_games, store.label) else null) + if (picked.isEmpty()) { + if (owned.size < listed.size && storeCache(app, emptyList(), gen)) publish(app, emptyList(), gen) + return problem(app.getString(R.string.stores_sync_no_games, store.label).takeIf { cache.isEmpty() || owned.size < listed.size }) + } if (gen != generation.get()) return status(R.string.stores_sync_cover_art) val images = art(app, token, picked.map { it.first.slug }, gen) @@ -246,6 +272,7 @@ object EaLibrary { tall = img?.tall.orEmpty(), wide = img?.wide.orEmpty(), logo = img?.logo.orEmpty(), version = offer.gameVersion, executePath = offer.executePathOverride, installCheck = offer.installCheckOverride, parameters = offer.executeParameters, multiplayerId = offer.multiplayerId, masterTitleId = offer.masterTitleId, cloudSaves = offer.cloudSaves, locales = offer.locales, + productName = o.productName, ) } if (!storeCache(app, games, gen)) return diff --git a/app/src/main/java/com/droiddeck/launcher/stores/ea/EaOoa.kt b/app/src/main/java/com/droiddeck/launcher/stores/ea/EaOoa.kt index 9590ce4a0b..5be0d03931 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/ea/EaOoa.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/ea/EaOoa.kt @@ -175,13 +175,29 @@ object EaOoa { return head + EaCrypto.licenseEncrypt(licenseXml(l).toByteArray()) } + private const val AUTH_ATTEMPTS = 4 + + internal fun tokenRejected(body: String) = + body.contains("cause=\"AUTHENTICATION_FAILED\"") && body.contains("field=\"ea_eadmtoken\"") + + internal fun retryTokenRejected(request: () -> EaReply): EaReply { + var reply = request() + var attempt = 1 + while (!reply.ok && attempt < AUTH_ATTEMPTS && tokenRejected(reply.text)) { + attempt++ + reply = request() + } + return reply + } + fun request(token: String, contentId: String, machineHash: String, requestToken: String? = null, requestType: String? = null): License { val nonce = EaCrypto.hex(ByteArray(4).also(SecureRandom()::nextBytes)) val params = mutableListOf("contentId" to contentId, "machineHash" to machineHash, "nonce" to nonce, "ea_eadmtoken" to token) if (requestToken != null) params += "requestToken" to requestToken if (requestType != null) params += "requestType" to requestType val url = LICENSES + "?" + params.joinToString("&") { (k, v) -> k + "=" + URLEncoder.encode(v, "UTF-8") } - val reply = EaHttp.request(url, headers = mapOf("X-Requester-Id" to "Origin Online Activation", "User-Agent" to "EACTransaction")) + val headers = mapOf("X-Requester-Id" to "Origin Online Activation", "User-Agent" to "EACTransaction") + val reply = retryTokenRejected { EaHttp.request(url, headers = headers) } if (!reply.ok) throw IllegalStateException("EA refused the licence (${reply.status}): ${reply.text.replace(Regex("(eadmToken value=\")[^\"]*"), "$1\"").take(600)}") val signature = reply.header("x-signature") ?: throw IllegalStateException("EA's licence had no signature") return parseLicense(String(EaCrypto.licenseDecrypt(reply.body), Charsets.UTF_8), signature) diff --git a/app/src/main/java/com/droiddeck/launcher/stores/ea/EaStore.kt b/app/src/main/java/com/droiddeck/launcher/stores/ea/EaStore.kt new file mode 100644 index 0000000000..b585dfec98 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/stores/ea/EaStore.kt @@ -0,0 +1,120 @@ +package com.droiddeck.launcher.stores.ea + +import android.content.Context +import com.droiddeck.launcher.stores.CatalogItem +import com.droiddeck.launcher.stores.Store +import com.droiddeck.launcher.stores.StoreFront +import com.droiddeck.launcher.stores.StoreNet +import com.droiddeck.launcher.stores.StoreShelves +import com.droiddeck.launcher.stores.cleanStoreText +import org.json.JSONObject +import java.time.Instant +import java.util.concurrent.Executors +import java.util.concurrent.TimeUnit + +/** EA's PC catalog, read from the game pages ea.com renders for the EA app's games. */ +object EaStore { + private const val SITE = "https://www.ea.com" + private const val CATALOG = "$SITE/games/library/pc-download" + private const val PAGE_SIZE = 12 + private const val MAX_PAGES = 20 + private const val SHELF = 24 + private val NEXT_DATA = Regex("""""", RegexOption.DOT_MATCHES_ALL) + + private var front: StoreFront? = null + + private fun front(context: Context): StoreFront = synchronized(this) { + front ?: StoreFront(Store.EA, { EaPrefs.get(context) }, { fetchAll().let { StoreFront.Catalog(shelves(it), it) } }, key = "store_front_catalog").also { front = it } + } + + fun cached(context: Context): StoreShelves? = front(context).cached() + + fun featured(context: Context, force: Boolean): StoreShelves? = front(context).shelves(force) + + fun search(context: Context, query: String): List { + val q = StoreFront.titleKey(query) + if (q.length < 2) return emptyList() + return front(context).everything().filter { StoreFront.titleKey(it.title).contains(q) } + } + + /** Whether a store card and a library entry are the same game. */ + fun sameGame(shelf: CatalogItem, owned: CatalogItem): Boolean { + val slug = shelf.extra["slug"].orEmpty() + if (slug.isNotEmpty() && slug == owned.extra["slug"]) return true + val shelfKey = StoreFront.titleKey(shelf.title).ifEmpty { return false } + return listOf(owned.title, owned.extra["productName"].orEmpty()).any { StoreFront.titleKey(it) == shelfKey } + } + + /** + * The device's currency. ea.com's pages are cached with whichever region asked first, so one page can carry + * roubles and the next dollars; a price in another currency is left off rather than shown wrong. + */ + private fun localCurrency(): String = + runCatching { java.util.Currency.getInstance(java.util.Locale.getDefault()).currencyCode }.getOrNull() ?: "USD" + + internal fun parsePage(html: String, currency: String = localCurrency()): Pair, Int> { + val data = NEXT_DATA.find(html)?.groupValues?.get(1) ?: return emptyList() to 0 + val props = JSONObject(data).optJSONObject("props")?.optJSONObject("pageProps") ?: return emptyList() to 0 + val games = props.optJSONArray("games") ?: return emptyList() to 0 + val items = (0 until games.length()).mapNotNull { games.optJSONObject(it) }.mapNotNull { item(it, currency) } + return items to props.optInt("totalItems", items.size) + } + + internal fun item(g: JSONObject, currency: String): CatalogItem? { + fun s(o: JSONObject?, k: String) = o?.optString(k)?.takeIf { it.isNotBlank() && it != "null" } + val slug = s(g, "slug") ?: return null + val title = s(g, "title")?.replace("\n", " ")?.trim() ?: return null + val art = g.optJSONObject("packArt") + val price = g.optJSONObject("price") + val total = s(price, "displayTotal").orEmpty() + val now = s(price, "displayTotalWithDiscount") ?: total + val discount = price?.optInt("discountPercentage") ?: 0 + val free = g.optBoolean("isFreeToPlay") || now.filter { it.isDigit() }.trimStart('0').isEmpty() && now.isNotEmpty() + val shown = !free && s(price, "currency").equals(currency, true) + val genres = g.optJSONArray("genres") + val franchise = s(g, "franchiseSlug") + return CatalogItem( + store = Store.EA, id = "ea-store:$slug", title = title, + imageUrl = s(art, "ar16X9") ?: s(art, "ar2X1"), tallImageUrl = s(art, "ar2X3") ?: s(art, "ar3X4"), + tags = (0 until (genres?.length() ?: 0)).mapNotNull { genres!!.optJSONObject(it)?.optString("name")?.takeIf(String::isNotBlank) }.take(3).joinToString(", "), + isFree = free, hasPrice = shown, finalPrice = if (shown) now else "", + originalPrice = if (shown && discount > 0) total else "", discountPercent = discount.coerceAtLeast(0), + storeUrl = if (franchise != null) "$SITE/games/$franchise/$slug" else "$SITE/games/$slug", + publisher = "Electronic Arts", releaseDate = s(g, "releaseDate")?.take(10).orEmpty(), + description = cleanStoreText(s(g, "shortDescription")), + extra = buildMap { put("slug", slug); s(g, "tier")?.let { put("tier", it) } }, + ) + } + + private fun page(n: Int): Pair, Int>? = + StoreNet.get(if (n == 1) CATALOG else "$CATALOG?page=$n", headers = mapOf("Accept" to "text/html"))?.let(::parsePage) + + /** Every page of the catalog; a page that fails fails the whole refresh, so a partial list never replaces a good one. */ + private fun fetchAll(): List { + val (first, total) = page(1) ?: throw java.io.IOException("ea.com catalog page 1 failed") + val pages = ((total + PAGE_SIZE - 1) / PAGE_SIZE).coerceIn(1, MAX_PAGES) + val rest = java.util.concurrent.ConcurrentHashMap>() + val pool = Executors.newFixedThreadPool(4) + try { + for (n in 2..pages) pool.execute { page(n)?.first?.let { rest[n] = it } } + } finally { + pool.shutdown() + if (!pool.awaitTermination(1, TimeUnit.MINUTES)) pool.shutdownNow() + } + (2..pages).firstOrNull { !rest.containsKey(it) }?.let { throw java.io.IOException("ea.com catalog page $it failed") } + return (first + (2..pages).flatMap { rest.getValue(it) }).distinctBy { it.id } + } + + internal fun shelves(all: List, now: Instant = Instant.now()): StoreShelves { + val today = now.toString().take(10) + val released = all.filter { it.releaseDate.isNotEmpty() && it.releaseDate <= today } + val headline = released.filter { it.extra["tier"] == "Tier1" || it.extra["tier"] == "Tier2" } + return StoreShelves( + whatsNew = released.sortedByDescending { it.releaseDate }.take(SHELF), + deals = released.filter { it.discountPercent > 0 }.sortedByDescending { it.discountPercent }.take(SHELF), + free = released.filter { it.isFree }.take(SHELF), + trending = (headline + released).distinctBy { it.id }.take(SHELF), + art = all.mapNotNull { it.imageUrl }.take(SHELF), + ) + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/stores/gog/GogInstallRecord.kt b/app/src/main/java/com/droiddeck/launcher/stores/gog/GogInstallRecord.kt index df07991023..686ebd3c8f 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/gog/GogInstallRecord.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/gog/GogInstallRecord.kt @@ -65,13 +65,19 @@ internal object GogFiles { fun dir(folder: File): File = inside(folder, ".droiddeck-gog").apply { mkdirs() } fun journal(folder: File): File = File(dir(folder), "operation.json") - fun inside(root: File, raw: String): File { + private fun parts(raw: String): List { val path = raw.replace('\\', '/') + val parts = path.split('/') require(path.isNotBlank() && !path.startsWith('/') && ':' !in path && '\u0000' !in path && - path.split('/').none { it.isEmpty() || it == "." || it == ".." }) { "Invalid GOG path: $raw" } + parts.none { it.isEmpty() || it == "." || it == ".." }) { "Invalid GOG path: $raw" } + return parts + } + + fun inside(root: File, raw: String): File { + val parts = parts(raw) val base = root.canonicalFile var out = base - for (part in path.split('/')) { + for (part in parts) { out = File(out, part) require(!Files.isSymbolicLink(out.toPath())) { "GOG path is a symbolic link: $raw" } } @@ -122,21 +128,28 @@ internal object GogFiles { } fun validate(files: JSONArray, folder: File) { + val base = folder.canonicalFile val paths = HashSet() val components = HashMap() + val listings = HashMap>>() for (file in files.objects()) { val path = file.getString("path").replace('\\', '/') - inside(folder, path) + val parts = parts(path) require(!path.startsWith(".droiddeck-", true) && path != StoreGameSidecar.FILE_NAME) { "GOG content overlaps launcher metadata" } require(paths.add(path.lowercase(Locale.ROOT))) { "GOG paths differ only by case: $path" } - var parent = folder + var parent = base var relative = "" - for (part in path.split('/')) { + for (part in parts) { relative = if (relative.isEmpty()) part else "$relative/$part" + val child = File(parent, part) val previous = components.putIfAbsent(relative.lowercase(Locale.ROOT), relative) require(previous == null || previous == relative) { "GOG directory paths differ only by case: $path" } - require(parent.list()?.none { it != part && it.equals(part, true) } != false) { "An existing path differs only by case: $path" } - parent = File(parent, part) + if (previous == null) { + require(!Files.isSymbolicLink(child.toPath())) { "GOG path is a symbolic link: $path" } + val existing = listings.getOrPut(parent) { parent.list().orEmpty().groupBy { it.lowercase(Locale.ROOT) } } + require(existing[part.lowercase(Locale.ROOT)].orEmpty().all { it == part }) { "An existing path differs only by case: $path" } + } + parent = child } } } diff --git a/app/src/main/java/com/droiddeck/launcher/stores/rockstar/RockstarAuth.kt b/app/src/main/java/com/droiddeck/launcher/stores/rockstar/RockstarAuth.kt new file mode 100644 index 0000000000..b6c90cb41f --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/stores/rockstar/RockstarAuth.kt @@ -0,0 +1,239 @@ +package com.droiddeck.launcher.stores.rockstar + +import android.content.Context +import android.os.Build +import android.util.Log +import android.webkit.CookieManager +import com.droiddeck.launcher.stores.Store +import com.droiddeck.launcher.stores.StoreAccounts +import org.json.JSONObject +import java.net.HttpURLConnection +import java.net.URL +import java.net.URLEncoder +import java.security.SecureRandom + +object RockstarAuth { + private const val TAG = "RockstarAuth" + const val SIGN_IN_HOST = "https://signin.rockstargames.com" + private const val LAUNCHER_SITE = "https://rgl.rockstargames.com" + private const val GATEWAY = "$LAUNCHER_SITE/api/connect/gateway" + + const val START_URL = "$SIGN_IN_HOST/robots.txt" + + const val CODE_URL = "$SIGN_IN_HOST/droiddeck/auth-code" + val SIGN_IN_URLS = listOf(SIGN_IN_HOST, LAUNCHER_SITE, "https://www.rockstargames.com", "https://socialclub.rockstargames.com") + const val COOKIE_DOMAIN = ".rockstargames.com" + + const val USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36" + private const val PREFS = "stores.rockstar" + private const val TICKET_MARGIN_MS = 15 * 60 * 1000L + private val lock = Any() + + class Ticket(val ticket: String, val sessionKey: String, val sessionTicket: String, val rockstarId: String, val nickname: String, val expiresAt: Long, val email: String = "", val sdkTicket: String = "") + + internal fun fingerprint(context: Context): JSONObject { + val p = context.applicationContext.getSharedPreferences(PREFS, Context.MODE_PRIVATE) + fun stable(key: String, bytes: Int): String = p.getString(key, null) ?: ByteArray(bytes).also { SecureRandom().nextBytes(it) } + .joinToString("") { "%02x".format(it) }.also { p.edit().putString(key, it).apply() } + val device = "DROIDDECK-" + (Build.MODEL ?: "ANDROID").uppercase().replace(Regex("[^A-Z0-9]"), "").take(12) + return fingerprintOf(device, stable("volume_serial", 4), stable("cpu_info", 8)) + } + + internal fun fingerprintOf(device: String, volume: String, cpu: String): JSONObject = JSONObject() + .put("device_name", device) + .put("machine_name", device) + .put("os_version", "10.0.19045") + .put("volume_serial", volume) + .put("cpu_info", cpu) + + internal fun state(fingerprint: JSONObject) = "{\"fp\": $fingerprint}" + + internal fun bridgeScript(fingerprint: JSONObject, title: String, codeUrl: String = CODE_URL): String = """ +(function(){ + if (window.__droiddeckRgsc) return 'again'; + window.__droiddeckRgsc = true; + var fp = $fingerprint, title = ${JSONObject.quote(title)}, back = ${JSONObject.quote(codeUrl)}, seq = 0; + function later(cb, v){ setTimeout(function(){ try { if (cb) cb(v); } catch (e) {} }, 0); } + var answers = { + GetWindowConfig: { serviceInfo: { rosPlatform: 'pc' }, platformInfo: {} }, + GetDeviceId: { fingerprintKvp: fp }, + GetVersionInfo: { isDebugSdk: false }, + GetProfileList: { profiles: [] }, + GetCommandLineArguments: { arguments: [] } + }; + window.rgscQueryCancel = function(){}; + window.rgscQuery = function(q){ + q = q || {}; + var p = q.params || {}; + if (q.method === 'CallAuthResult' && p.authCode) { + later(q.onSuccess, {}); + setTimeout(function(){ location.replace(back + '?code=' + encodeURIComponent(p.authCode)); }, 50); + } else if ((q.method === 'CallAuthResult' && p.result === 3) || (q.method === 'CallSetWindowState' && p.state === 3)) { + later(q.onSuccess, {}); + setTimeout(function(){ location.replace(back + '?cancel=1'); }, 50); + } else if (q.method === 'CallLaunchExternalBrowser' && p.url) { + window.open(p.url, '_blank'); + later(q.onSuccess, {}); + } else { + later(q.onSuccess, Object.prototype.hasOwnProperty.call(answers, q.method) ? answers[q.method] : {}); + } + return ++seq; + }; + window.rgscAddSubscription = function(s){ + s = s || {}; + if (s.method === 'OnStartAuth') later(s.onSuccess, { launchPlatform: 0, titleLaunchInfo: { activeTitleName: title, externalPlatformInfo: {} }, profile: null, errorMessage: null }); + return ++seq; + }; + var form = '/signin/user-form?cid=launcher&lang=en-US'; + fetch(form, { credentials: 'include' }) + .then(function(r){ return r.text(); }) + .then(function(h){ + history.replaceState(null, '', form); document.open(); document.write(h); document.close(); + var css = document.createElement('style'); + css.textContent = '[data-ui-name="launcherSettings"]{display:none!important}'; + (document.head || document.documentElement).appendChild(css); + }); + return 'ok'; +})() +""".trimIndent() + + fun isCodeUrl(url: String) = url.startsWith(CODE_URL) + + internal fun cancelled(url: String): Boolean = android.net.Uri.parse(url).getQueryParameter("cancel") == "1" + + internal fun codeFrom(url: String): String? = android.net.Uri.parse(url).getQueryParameter("code")?.takeIf { it.isNotBlank() } + + fun completeSignIn(context: Context, url: String): String? { + val code = codeFrom(url) ?: return "no auth code" + val fp = fingerprint(context) + val gateway = "$GATEWAY?code=" + URLEncoder.encode(code, "UTF-8") + "&fingerprint=" + URLEncoder.encode(state(fp), "UTF-8") + val c = URL(gateway).openConnection() as HttpURLConnection + c.connectTimeout = 20_000 + c.readTimeout = 25_000 + c.instanceFollowRedirects = false + c.setRequestProperty("User-Agent", USER_AGENT) + c.setRequestProperty("Accept", "application/json") + c.setRequestProperty("X-Requested-With", "XMLHttpRequest") + c.setRequestProperty("Origin", LAUNCHER_SITE) + c.setRequestProperty("Referer", "$LAUNCHER_SITE/") + runCatching { CookieManager.getInstance().getCookie(LAUNCHER_SITE) }.getOrNull()?.takeIf { it.isNotEmpty() }?.let { c.setRequestProperty("Cookie", it) } + val (status, body) = try { + val s = c.responseCode + s to ((if (s in 200..299) c.inputStream else c.errorStream)?.use { it.readBytes().toString(Charsets.UTF_8) }.orEmpty()) + } finally { + c.disconnect() + } + val o = runCatching { JSONObject(body) }.getOrNull() + val token = o?.optString("ScAuthToken")?.takeIf { it.isNotEmpty() && it != "null" } + if (token == null) { + Log.w(TAG, "gateway $status; fields ${o?.keys()?.asSequence()?.toList() ?: "not json"}") + return "gateway $status" + } + val account = JSONObject() + .put("access_token", token) + .put("remembered_machine_token", o.optString("RememberedMachineToken").takeIf { it != "null" }.orEmpty()) + .put("login_guid", o.optString("LoginGuid").takeIf { it != "null" }.orEmpty()) + .put("display_name", "Rockstar Games") + .put("signed_in_at", System.currentTimeMillis()) + StoreAccounts.write(context.applicationContext, Store.ROCKSTAR, account) + val t = runCatching { mint(context) }.onFailure { Log.w(TAG, "first ticket: ${it.message}") }.getOrNull() + if (t == null) { + StoreAccounts.clear(context.applicationContext, Store.ROCKSTAR) + return "ticket" + } + return null + } + + fun ticket(context: Context, fresh: Boolean = false): Ticket? = synchronized(lock) { + val o = StoreAccounts.read(context.applicationContext, Store.ROCKSTAR) ?: return null + if (!fresh) { + val current = stored(o) + if (com.droiddeck.launcher.session.SessionState.running && + com.droiddeck.launcher.stores.StoreLaunchRequests.lastLaunched?.first == Store.ROCKSTAR) { + return current?.takeIf { it.expiresAt > System.currentTimeMillis() } + } + current?.takeIf { it.expiresAt - System.currentTimeMillis() > TICKET_MARGIN_MS }?.let { return it } + } + runCatching { mint(context) }.onFailure { Log.w(TAG, "ticket: ${it.message}") }.getOrNull() + } + + private fun stored(o: JSONObject): Ticket? { + val t = o.optString("ticket").takeIf { it.isNotEmpty() } ?: return null + return Ticket(t, o.optString("session_key"), o.optString("session_ticket"), o.optString("rockstar_id"), o.optString("display_name"), o.optLong("ticket_expires_at"), o.optString("email"), o.optString("sdk_ticket").takeIf { o.optInt("sdk_ticket_version") == 1 }.orEmpty()) + } + + private fun mint(context: Context): Ticket { + val app = context.applicationContext + val o = StoreAccounts.read(app, Store.ROCKSTAR) ?: throw IllegalStateException("not signed in") + val root = try { + RockstarRos.result("auth.asmx/CreateTicketScAuthToken2", listOf( + "ticket" to "", "platformName" to "pcros", "scAuthToken" to o.optString("access_token"), + "rememberedMachineToken" to o.optString("remembered_machine_token"), + ), headers = mapOf("SCS-MFAMachineFingerPrint" to state(fingerprint(app)))) + } catch (e: RockstarRos.RosException) { + if (e.code.startsWith("AuthenticationFailed")) com.droiddeck.launcher.stores.StoresState.markSignInExpired(Store.ROCKSTAR) + throw e + } + val t = parseTicket(root) ?: throw IllegalStateException("no ticket in the answer") + o.put("ticket", t.ticket).put("session_key", t.sessionKey).put("session_ticket", t.sessionTicket) + .put("rockstar_id", t.rockstarId).put("ticket_expires_at", t.expiresAt).put("email", t.email).put("sdk_ticket", t.sdkTicket).put("sdk_ticket_version", 1) + if (t.nickname.isNotEmpty()) o.put("display_name", t.nickname) + StoreAccounts.write(app, Store.ROCKSTAR, o) + return t + } + + internal fun parseTicket(root: org.w3c.dom.Element, now: Long = System.currentTimeMillis()): Ticket? { + val ticket = RockstarRos.text(root, "Ticket")?.takeIf { it.isNotEmpty() } ?: return null + val account = RockstarRos.first(root, "RockstarAccount") + val secs = RockstarRos.text(root, "SecsUntilExpiration")?.toLongOrNull() ?: 3600L + return Ticket( + ticket, RockstarRos.text(root, "SessionKey").orEmpty(), RockstarRos.text(root, "SessionTicket").orEmpty(), + (account?.let { RockstarRos.text(it, "RockstarId") } ?: RockstarRos.text(root, "RockstarId")).orEmpty(), + account?.let { RockstarRos.text(it, "Nickname") }.orEmpty(), + now + secs * 1000L, + account?.let { RockstarRos.text(it, "Email") }.orEmpty(), + sdkTicket(root), + ) + } + + internal fun sdkTicket(root: org.w3c.dom.Element): String { + val document = javax.xml.parsers.DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument() + val response = document.createElement("Response").also { document.appendChild(it) } + val fields = setOf("Status", "Ticket", "SessionKey", "SessionTicket", "SecsUntilExpiration", "PlayerAccountId", "PlayerAccountRuid", + "Region", "Privileges", "Privs", "Services", "SslServices", "Hosts", "DisabledSecurityFlags", "SessionId", "CloudKey", "PublicIp", "PosixTime", "IsSubAccount") + val blocked = setOf("scauthtoken", "accesstoken", "refreshtoken", "rememberedmachinetoken", "loginguid", "password") + fun copy(source: org.w3c.dom.Element): org.w3c.dom.Element { + val target = document.createElement(source.tagName) + for (i in 0 until source.attributes.length) { + val attribute = source.attributes.item(i) + if (attribute.nodeName.lowercase() !in blocked) target.setAttribute(attribute.nodeName, attribute.nodeValue) + } + var child = source.firstChild + while (child != null) { + if (child is org.w3c.dom.Element) { + if (child.tagName.lowercase() !in blocked) target.appendChild(copy(child)) + } else if (child.nodeType == org.w3c.dom.Node.TEXT_NODE || child.nodeType == org.w3c.dom.Node.CDATA_SECTION_NODE) { + target.appendChild(document.createTextNode(child.nodeValue)) + } + child = child.nextSibling + } + return target + } + for (field in fields) RockstarRos.first(root, field)?.let { response.appendChild(copy(it)) } + RockstarRos.first(root, "RockstarAccount")?.let { account -> + val target = document.createElement("RockstarAccount") + for (field in setOf("RockstarId", "Nickname", "Email", "Age", "CountryCode", "LanguageCode", "AvatarUrl", "ZipCode", "Ruid")) { + RockstarRos.first(account, field)?.let { target.appendChild(copy(it)) } + } + response.appendChild(target) + } + val output = java.io.StringWriter() + javax.xml.transform.TransformerFactory.newInstance().newTransformer().apply { + setOutputProperty(javax.xml.transform.OutputKeys.OMIT_XML_DECLARATION, "yes") + transform(javax.xml.transform.dom.DOMSource(document), javax.xml.transform.stream.StreamResult(output)) + } + return output.toString() + } + + fun signOut(context: Context) = synchronized(lock) { StoreAccounts.clear(context.applicationContext, Store.ROCKSTAR) } +} diff --git a/app/src/main/java/com/droiddeck/launcher/stores/rockstar/RockstarBackend.kt b/app/src/main/java/com/droiddeck/launcher/stores/rockstar/RockstarBackend.kt new file mode 100644 index 0000000000..f816ed8ef1 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/stores/rockstar/RockstarBackend.kt @@ -0,0 +1,209 @@ +package com.droiddeck.launcher.stores.rockstar + +import android.content.Context +import android.content.Intent +import android.util.Log +import android.webkit.WebView +import com.droiddeck.launcher.R +import com.droiddeck.launcher.stores.CatalogItem +import com.droiddeck.launcher.stores.InstalledStoreGame +import com.droiddeck.launcher.stores.LoginFlows +import com.droiddeck.launcher.stores.Store +import com.droiddeck.launcher.stores.StoreBackend +import com.droiddeck.launcher.stores.StoreFront +import com.droiddeck.launcher.stores.StoreInstallRoot +import com.droiddeck.launcher.stores.StoreLoginActivity +import com.droiddeck.launcher.stores.StoreShelves +import com.droiddeck.launcher.stores.StoresState +import com.droiddeck.launcher.stores.WebCookies +import com.droiddeck.launcher.stores.download.DownloadEntry +import com.droiddeck.launcher.stores.download.DownloadQueue +import org.w3c.dom.Element + +object RockstarBackend : StoreBackend { + override val store: Store = Store.ROCKSTAR + + init { + LoginFlows.rockstarFlow = { ua -> RockstarLogin(ua) } + } + + override fun signIn(context: Context) { + context.startActivity( + Intent(context, StoreLoginActivity::class.java) + .putExtra(StoreLoginActivity.EXTRA_STORE, store.id) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK), + ) + } + + override fun signOut(context: Context) { + RockstarAuth.signOut(context.applicationContext) + RockstarLibrary.reset() + runCatching { WebCookies.expire(RockstarAuth.SIGN_IN_URLS, RockstarAuth.COOKIE_DOMAIN, listOf("/")) {} } + } + + override fun syncLibrary(context: Context, force: Boolean) { + val app = context.applicationContext + Thread({ RockstarLibrary.sync(app) }, "rockstar-sync").start() + } + + override fun loadShelves(context: Context, force: Boolean) { + StoresState.post { StoresState.shelves[store] = StoreFront.markOwned(RockstarCatalog.shelves(), StoresState.library[store], RockstarCatalog::sameGame) } + } + + override fun search(context: Context, query: String): List = + StoreFront.markOwned(RockstarCatalog.search(query), StoresState.library[store], RockstarCatalog::sameGame) + + override fun install(context: Context, item: CatalogItem, root: java.io.File) { + val app = context.applicationContext + val folder = StoreInstallRoot.folderFor(app, store, item.id, item.title, root) + val entry = DownloadEntry(store, item.id, item.title, cover = item.tallImageUrl ?: item.imageUrl, + bytesTotal = item.sizeBytes, location = StoreInstallRoot.labelFor(app, folder)) + DownloadQueue.enqueue(app, entry) { RockstarInstaller(app, item, folder) } + } + + override fun uninstall(context: Context, game: InstalledStoreGame) {} +} + +internal class RockstarLogin(override val userAgent: String) : StoreLoginActivity.Flow { + override val startUrl: String get() = RockstarAuth.START_URL + override fun isRedirect(url: String): Boolean = RockstarAuth.isCodeUrl(url) + + override fun pageFinished(view: WebView, url: String) { + if (!url.startsWith(RockstarAuth.START_URL)) return + val title = "launcher" + view.evaluateJavascript(RockstarAuth.bridgeScript(RockstarAuth.fingerprint(view.context), title)) { Log.d("RockstarLogin", "bridge: $it") } + } + + override fun forgetSignIn(done: () -> Unit) { + runCatching { WebCookies.expire(RockstarAuth.SIGN_IN_URLS, RockstarAuth.COOKIE_DOMAIN, listOf("/")) { done() } }.onFailure { done() } + } + + override fun finish(activity: StoreLoginActivity, view: WebView, url: String): String? = if (RockstarAuth.cancelled(url)) null else try { + RockstarAuth.completeSignIn(activity, url)?.let { + Log.w("RockstarLogin", "sign-in incomplete: $it") + activity.getString(R.string.stores_login_error_verification) + } + } catch (e: Exception) { + Log.w("RockstarLogin", "sign-in failed: ${e.javaClass.simpleName}") + activity.getString(R.string.stores_login_error_generic) + } +} + +internal data class RockstarApp(val id: String, val name: String, val titleId: String, val branches: List, val parent: String = "") + +internal data class RockstarBranch(val id: String, val name: String, val buildId: String, val isDefault: Boolean, val accessToken: String) { + val hasBuild: Boolean get() = (buildId.toLongOrNull() ?: 0L) > 0 && accessToken.isNotEmpty() +} + +internal data class RockstarPackage(val title: String, val featured: Boolean) + +internal class RockstarAccountApps(val apps: List, val packages: List) + +internal object RockstarApps { + fun parse(root: Element): List = RockstarRos.all(root, "App").map { a -> + val branches = RockstarRos.first(a, "Branches")?.let { RockstarRos.children(it, "Branch") }.orEmpty().map { b -> + RockstarBranch(b.getAttribute("Id"), b.getAttribute("Name"), b.getAttribute("BuildId"), + b.getAttribute("IsDefault").equals("true", true), RockstarRos.text(b, "AccessToken").orEmpty()) + } + val parent = (a.parentNode?.parentNode as? Element)?.takeIf { it.tagName == "App" }?.getAttribute("Name").orEmpty() + RockstarApp(a.getAttribute("Id"), a.getAttribute("Name"), a.getAttribute("TitleId"), branches, parent) + } + + fun packages(root: Element): List = RockstarRos.all(root, "PackageJson").mapNotNull { p -> + val o = runCatching { org.json.JSONObject(p.textContent) }.getOrNull() ?: return@mapNotNull null + o.optString("title").takeIf { it.isNotEmpty() }?.let { RockstarPackage(it, o.optBoolean("isFeatured")) } + } + + fun fetch(ticket: String, log: (String) -> Unit): RockstarAccountApps { + val root = RockstarRos.result("app.asmx/GetAppsAndPackages", listOf("ticket" to ticket)) + val out = RockstarAccountApps(parse(root), packages(root)) + log("Rockstar: packages " + out.packages.joinToString(", ") { it.title + if (it.featured) " (featured)" else "" }.ifEmpty { "none" } + + "; builds " + out.apps.filter { a -> a.branches.any { it.hasBuild } }.joinToString(", ") { it.name }.ifEmpty { "none" }) + return out + } + + fun branch(app: RockstarApp): RockstarBranch? = app.branches.firstOrNull { it.isDefault && it.hasBuild } ?: app.branches.firstOrNull { it.hasBuild } + + fun deliverer(apps: List, title: RockstarTitle): RockstarApp? = apps + .filter { RockstarTitles.byId(it.name) == title && !it.name.endsWith("_steam") && !it.name.endsWith("_epic") } + .sortedBy { if (it.name == title.id) 0 else 1 } + .firstOrNull { branch(it) != null } +} + +object RockstarLibrary { + private val generation = java.util.concurrent.atomic.AtomicInteger() + private val running = java.util.concurrent.atomic.AtomicReference(null) + + fun reset() { + generation.incrementAndGet() + StoresState.post { + StoresState.library.remove(Store.ROCKSTAR) + StoresState.shelves.remove(Store.ROCKSTAR) + } + } + + private fun post(gen: Int, block: () -> Unit) = StoresState.post { if (generation.get() == gen) block() } + + internal fun owned(account: RockstarAccountApps): List = + account.packages.filter { !it.featured }.flatMap { RockstarTitles.forName(it.title) }.distinct() + + internal fun owns(account: RockstarAccountApps, rosId: Int, id: String): Boolean = + owned(account).any { it.rosTitleId == rosId } || account.packages.any { !it.featured && it.title == id } + + internal fun games(account: RockstarAccountApps): List = owned(account).mapNotNull { t -> + RockstarApps.deliverer(account.apps, t)?.let { RockstarTitles.item(t, owned = true, extra = mapOf("app" to it.name, "appId" to it.id)) } + }.sortedBy { it.title.lowercase() } + + fun sync(app: Context) { + val gen = generation.get() + if (running.getAndSet(gen) == gen) return + try { + val t = RockstarAuth.ticket(app) + if (t == null) { + post(gen) { StoresState.status.remove(Store.ROCKSTAR); StoresState.problems[Store.ROCKSTAR] = app.getString(R.string.stores_sync_sign_in) } + return + } + if (StoresState.library[Store.ROCKSTAR].isNullOrEmpty()) post(gen) { StoresState.status[Store.ROCKSTAR] = app.getString(R.string.stores_sync_game_list) } + val account = RockstarApps.fetch(t.ticket) { StoresState.logLine(it) } + val games = games(account) + owned(account).filter { o -> games.none { it.id == o.id } }.takeIf { it.isNotEmpty() }?.let { elsewhere -> + StoresState.logLine("Rockstar: owned through another store, installs from there: " + elsewhere.joinToString(", ") { it.name }) + } + post(gen) { + StoresState.status.remove(Store.ROCKSTAR) + StoresState.problems.remove(Store.ROCKSTAR) + StoresState.library[Store.ROCKSTAR] = games + StoresState.shelves[Store.ROCKSTAR]?.let { StoresState.shelves[Store.ROCKSTAR] = StoreFront.markOwned(it, games, RockstarCatalog::sameGame) } + } + StoresState.logLine("Rockstar: ${games.size} owned games") + } catch (e: Exception) { + StoresState.logLine("Rockstar: library sync failed: ${e.javaClass.simpleName} ${e.message.orEmpty().take(300)}") + post(gen) { StoresState.status.remove(Store.ROCKSTAR); StoresState.problems[Store.ROCKSTAR] = app.getString(R.string.stores_sync_failed) } + } finally { + running.compareAndSet(gen, null) + } + } +} + +internal object RockstarCatalog { + fun all(): List = RockstarTitles.all.map { RockstarTitles.item(it) } + + fun shelves(): StoreShelves { + val all = all() + val newest = all.sortedByDescending { it.releaseDate } + val headline = listOf("gta5_gen9", "rdr2", "rdr", "gta4", "gtasaunreal", "lanoire", "mp3") + return StoreShelves( + whatsNew = newest, + trending = headline.mapNotNull { id -> all.firstOrNull { it.id == id } } + all.filter { it.id !in headline }, + art = all.mapNotNull { it.imageUrl }, + ) + } + + fun search(query: String): List { + val q = StoreFront.titleKey(query) + if (q.length < 2) return emptyList() + return all().filter { StoreFront.titleKey(it.title).contains(q) } + } + + fun sameGame(shelf: CatalogItem, owned: CatalogItem): Boolean = shelf.id == owned.id +} diff --git a/app/src/main/java/com/droiddeck/launcher/stores/rockstar/RockstarInstaller.kt b/app/src/main/java/com/droiddeck/launcher/stores/rockstar/RockstarInstaller.kt new file mode 100644 index 0000000000..ac039d95f9 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/stores/rockstar/RockstarInstaller.kt @@ -0,0 +1,263 @@ +package com.droiddeck.launcher.stores.rockstar + +import android.content.Context +import com.droiddeck.launcher.R +import com.droiddeck.launcher.stores.CatalogItem +import com.droiddeck.launcher.stores.Store +import com.droiddeck.launcher.stores.StoreExe +import com.droiddeck.launcher.stores.StoreGameSidecar +import com.droiddeck.launcher.stores.StoreInstalls +import com.droiddeck.launcher.stores.download.DownloadQueue +import com.droiddeck.launcher.stores.download.DownloadStage +import org.w3c.dom.Element +import java.io.File +import java.io.RandomAccessFile +import java.net.HttpURLConnection +import java.net.URL +import java.nio.file.Files +import java.security.MessageDigest +import java.util.concurrent.ConcurrentLinkedQueue +import java.util.concurrent.Executors +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicBoolean +import java.util.concurrent.atomic.AtomicLong +import java.util.concurrent.atomic.AtomicReference + +internal data class RockstarChunk(val fileEntryId: String, val chunkId: String, val sha256: String, val offset: Long, val size: Long) + +internal data class RockstarFile(val entryId: String, val versionId: String, val path: String, val size: Long, val sha256: String, val chunks: List) + +internal data class RockstarBuild(val buildId: String, val version: String, val preload: Boolean, val files: List) { + val bytes: Long get() = files.sumOf { it.size } +} + +internal object RockstarManifest { + fun inside(root: File, relative: String): File { + require(safePath(relative) == relative) { "Unsafe Rockstar install path" } + val base = root.canonicalFile + var target = base + for (part in relative.split('/')) { + target = File(target, part) + require(!Files.isSymbolicLink(target.toPath())) { "Rockstar install path is a symbolic link" } + } + require(target.canonicalFile.toPath().startsWith(base.toPath())) { "Rockstar install path leaves its folder" } + return target + } + + fun verified(target: File, chunk: RockstarChunk, cancelled: () -> Boolean = { false }): Boolean { + if (cancelled()) return false + if (!target.isFile || chunk.offset < 0 || chunk.size < 0 || chunk.offset > target.length() || chunk.size > target.length() - chunk.offset) return false + return RandomAccessFile(target, "r").use { input -> + input.seek(chunk.offset) + val digest = MessageDigest.getInstance("SHA-256") + val buffer = ByteArray(256 * 1024) + var remaining = chunk.size + while (remaining > 0) { + if (cancelled()) return false + val count = input.read(buffer, 0, minOf(buffer.size.toLong(), remaining).toInt()) + if (count <= 0) return false + digest.update(buffer, 0, count) + remaining -= count + } + digest.digest().joinToString("") { "%02x".format(it) }.equals(chunk.sha256, true) + } + } + + fun safePath(raw: String): String? { + val parts = raw.replace('\\', '/').split('/').filter { it.isNotEmpty() && it != "." } + if (parts.isEmpty() || parts.any { it == ".." || it.contains(':') }) return null + return parts.joinToString("/") + } + + fun parse(root: Element): RockstarBuild { + val result = RockstarRos.first(root, "Result") ?: throw IllegalStateException("manifest without a result") + val files = RockstarRos.all(result, "FileDetails").map { f -> + val entry = f.getAttribute("FileEntryId") + val path = safePath(RockstarRos.text(f, "RelativePath").orEmpty()) ?: throw IllegalStateException("unsafe path in the manifest") + val chunks = RockstarRos.first(f, "FileChunks")?.let { RockstarRos.children(it, "Chunk") }.orEmpty().map { c -> + RockstarChunk(entry, c.getAttribute("FileChunkId"), c.getAttribute("SHA256Hash").lowercase(), + c.getAttribute("StartByteOffset").toLong(), c.getAttribute("Size").toLong()) + } + val whole = RockstarRos.children(f, "SHA256Hash").firstOrNull()?.textContent?.trim()?.lowercase().orEmpty() + RockstarFile(entry, f.getAttribute("FileEntryVersionId"), path, f.getAttribute("FileSize").toLong(), whole, chunks) + } + return RockstarBuild(result.getAttribute("BuildId"), result.getAttribute("VersionNumber"), + RockstarRos.text(result, "IsPreload").equals("true", true), files) + } + + fun batches(chunks: List, maxBytes: Long = 48L * 1024 * 1024, maxCount: Int = 16): List> { + val out = ArrayList>() + var cur = ArrayList() + var bytes = 0L + for (c in chunks) { + if (cur.isNotEmpty() && (bytes + c.size > maxBytes || cur.size >= maxCount)) { out += cur; cur = ArrayList(); bytes = 0 } + cur += c + bytes += c.size + } + if (cur.isNotEmpty()) out += cur + return out + } + + fun key(file: RockstarFile, chunk: RockstarChunk) = "${file.versionId}:${chunk.chunkId}" +} + +internal class RockstarInstaller( + private val app: Context, + private val item: CatalogItem, + private val folder: File, +) : DownloadQueue.DownloadJob { + private val cancelled = AtomicBoolean(false) + + override fun run(handle: DownloadQueue.JobHandle): String? { + handle.stage(DownloadStage.MANIFEST, app.getString(R.string.stores_sync_sign_in)) + val ticket = RockstarAuth.ticket(app)?.ticket ?: throw IllegalStateException("Not signed in to Rockstar Games") + val title = RockstarTitles.byId(item.id) ?: throw IllegalStateException("Rockstar has no PC build of ${item.title}") + val account = RockstarApps.fetch(ticket) { handle.log(it) } + if (title !in RockstarLibrary.owned(account)) throw IllegalStateException("${item.title} is not in this Rockstar account's library") + val owned = RockstarApps.deliverer(account.apps, title) + ?: throw IllegalStateException("${item.title} is owned through another store and installs from there") + val branch = RockstarApps.branch(owned)!! + handle.log("rockstar: ${owned.name} branch ${branch.name} build ${branch.buildId}") + val build = RockstarManifest.parse(RockstarRos.result("app.asmx/GetBuildManifestFull", listOf("ticket" to ticket, "branchAccessToken" to branch.accessToken))) + if (build.preload) throw IllegalStateException("${item.title} is a preload Rockstar has not unlocked yet") + handle.log("rockstar: build ${build.buildId} ${build.version}, ${build.files.size} files, ${build.bytes} bytes") + handle.diskSize(build.bytes) + val cover = item.tallImageUrl ?: item.imageUrl + StoreInstalls.begin(folder, Store.ROCKSTAR, item.id, item.title, cover, item.imageUrl) + if (cancelled.get()) return null + + val ledger = RockstarManifest.inside(folder, LEDGER) + val done = HashSet().apply { if (ledger.isFile) ledger.readLines().filterTo(this) { it.isNotBlank() } } + val pending = ArrayList>() + var have = 0L + for (f in build.files) { + if (cancelled.get()) return null + val target = RockstarManifest.inside(folder, f.path) + target.parentFile?.mkdirs() + for (c in f.chunks) { + if (cancelled.get()) return null + if (RockstarManifest.key(f, c) in done && RockstarManifest.verified(target, c, cancelled::get)) have += c.size else pending += f to c + } + if (cancelled.get()) return null + RandomAccessFile(target, "rw").use { if (it.length() != f.size) it.setLength(f.size) } + } + val fileOf = pending.associate { (f, c) -> "${c.fileEntryId}:${c.chunkId}" to f } + val total = build.bytes + val progress = AtomicLong(have) + handle.stage(DownloadStage.DOWNLOAD) + handle.progress(have, total, "Downloading (${build.files.size} files)") + + val queue = ConcurrentLinkedQueue(RockstarManifest.batches(pending.map { it.second })) + val failure = AtomicReference(null) + val pool = Executors.newFixedThreadPool(WORKERS, DownloadQueue.workerFactory("rockstar-dl")) + val ledgerLock = Any() + repeat(WORKERS) { + pool.execute { + while (!cancelled.get() && failure.get() == null) { + val batch = queue.poll() ?: break + try { + val urls = chunkUrls(ticket, branch.accessToken, batch) + for (c in batch) { + if (cancelled.get()) break + val f = fileOf.getValue("${c.fileEntryId}:${c.chunkId}") + fetch({ retry -> (if (retry) null else urls[c.chunkId]) ?: chunkUrls(ticket, branch.accessToken, listOf(c)).getValue(c.chunkId) }, RockstarManifest.inside(folder, f.path), c, progress) { + handle.progress(progress.get(), total, "Downloading (${build.files.size} files)") + } + synchronized(ledgerLock) { ledger.appendText(RockstarManifest.key(f, c) + "\n") } + } + } catch (t: Throwable) { + failure.compareAndSet(null, t) + } + } + } + } + pool.shutdown() + while (!pool.awaitTermination(250, TimeUnit.MILLISECONDS)) Unit + if (cancelled.get()) return null + failure.get()?.let { throw it } + + handle.interruptible(false) + handle.stage(DownloadStage.INSTALL, app.getString(R.string.stores_registering)) + val exe = resolve(folder, title.exe) ?: StoreExe.pick(folder, null, item.title).ifEmpty { title.exe.replace('\\', '/') } + handle.log("rockstar: exe=$exe") + val sidecar = StoreGameSidecar( + Store.ROCKSTAR, item.id, item.title, exe = exe, + installVersion = build.version.ifEmpty { build.buildId }, installedAt = System.currentTimeMillis(), + cover = cover, hero = item.imageUrl, cloud = false, + extra = mapOf("rosTitleId" to title.rosTitleId.toString(), "app" to owned.name, "buildId" to build.buildId, "platform" to title.platform), + ) + StoreInstalls.complete(app, folder, sidecar, onStep = { d, steps -> handle.stageProgress(d.toLong(), steps.toLong()) }) + ledger.delete() + return folder.path + } + + private fun chunkUrls(ticket: String, branchToken: String, batch: List): Map { + val csv = batch.joinToString(",") { "${it.fileEntryId}:${it.chunkId}" } + val root = RockstarRos.result("app.asmx/RetrieveFileChunkMulti", listOf("ticket" to ticket, "branchAccessToken" to branchToken, "fileEntryAndChunkIdCsv" to csv)) + return RockstarRos.all(root, "Chunk").mapNotNull { c -> RockstarRos.text(c, "RedirectUrl")?.let { c.getAttribute("FileChunkId") to it } }.toMap() + } + + private fun fetch(url: (Boolean) -> String, target: File, chunk: RockstarChunk, progress: AtomicLong, report: () -> Unit) { + var lastError: Exception? = null + for (attempt in 0 until 3) { + if (cancelled.get()) return + val written = AtomicLong(0) + try { + val c = URL(url(attempt > 0)).openConnection() as HttpURLConnection + c.connectTimeout = 20_000 + c.readTimeout = 60_000 + try { + if (c.responseCode != 200) throw java.io.IOException("chunk ${chunk.chunkId}: HTTP ${c.responseCode}") + val digest = MessageDigest.getInstance("SHA-256") + RandomAccessFile(target, "rw").use { out -> + out.seek(chunk.offset) + c.inputStream.use { input -> + val buf = ByteArray(256 * 1024) + var last = 0L + while (true) { + if (cancelled.get()) { progress.addAndGet(-written.get()); return } + val n = input.read(buf) + if (n < 0) break + if (written.get() + n > chunk.size) throw java.io.IOException("chunk ${chunk.chunkId} is longer than the manifest says") + out.write(buf, 0, n) + digest.update(buf, 0, n) + written.addAndGet(n.toLong()) + progress.addAndGet(n.toLong()) + val now = System.currentTimeMillis() + if (now - last > 400) { last = now; report() } + } + } + } + val hex = digest.digest().joinToString("") { "%02x".format(it) } + if (written.get() != chunk.size || hex != chunk.sha256) throw java.io.IOException("chunk ${chunk.chunkId} failed its check") + report() + return + } finally { + c.disconnect() + } + } catch (e: Exception) { + progress.addAndGet(-written.get()) + lastError = e + } + } + throw lastError ?: java.io.IOException("chunk ${chunk.chunkId} failed") + } + + override fun cancel(deleteFiles: Boolean) { + cancelled.set(true) + if (deleteFiles) StoreInstalls.discard(app, folder, emptyList()) + } + + internal companion object { + const val LEDGER = ".droiddeck-rockstar-chunks" + private const val WORKERS = 4 + + fun resolve(folder: File, configured: String): String? { + var at = folder + for (part in configured.replace('\\', '/').split('/').filter { it.isNotEmpty() }) { + at = at.listFiles()?.firstOrNull { it.name.equals(part, ignoreCase = true) } ?: return null + } + return if (at.isFile) at.relativeTo(folder).invariantSeparatorsPath else null + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/stores/rockstar/RockstarLaunch.kt b/app/src/main/java/com/droiddeck/launcher/stores/rockstar/RockstarLaunch.kt new file mode 100644 index 0000000000..52f1119f90 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/stores/rockstar/RockstarLaunch.kt @@ -0,0 +1,69 @@ +package com.droiddeck.launcher.stores.rockstar + +import android.content.Context +import com.droiddeck.launcher.session.GameEnvironmentStore +import com.droiddeck.launcher.stores.Store +import com.droiddeck.launcher.stores.StoreGameSidecar +import com.droiddeck.launcher.stores.StoreInstallRoot +import org.json.JSONObject +import java.security.MessageDigest +import java.util.Base64 + +object RockstarLaunch { + internal val pipes = mapOf("gta3" to "GTA3_Pipe", "gtavc" to "GTA-VC_Pipe", "gtasa" to "GTA_SA_Pipe", "gta4" to "GTAIV_Pipe", "lanoire" to "LANOIRE_Pipe") + + fun usesClassicLauncher(id: String) = id in pipes + + fun applyDefaults(app: Context, id: String, appId: Long) { + val scope = (appId and 0xffffffffL).toString() + when (id) { + "gta3" -> GameEnvironmentStore.setDefault(app, scope, "FEX_X87REDUCEDPRECISION", "0") + "gtasa" -> GameEnvironmentStore.setDefault(app, scope, "PROTON_USE_WINED3D", "1") + } + } + + fun prepare(app: Context, id: String): JSONObject { + val folder = StoreInstallRoot.gameFolders(app).firstOrNull { folder -> + StoreGameSidecar.read(folder)?.let { it.store == Store.ROCKSTAR && it.id == id && it.isInstalled } == true + } ?: return failure("not-installed") + val installed = StoreGameSidecar.read(folder) ?: return failure("not-installed") + val exe = installed.exeFile(folder).canonicalFile + if (!exe.path.startsWith(folder.canonicalPath + java.io.File.separator) || !exe.isFile) return failure("missing-game-files") + val metadata = RockstarMetadata.find(folder) + val pipe = pipes[id] + val sdk = (pipe == null && metadata != null) || id in setOf("gta4", "lanoire") || listOf(folder, exe.parentFile).any { dir -> + dir.listFiles().orEmpty().any { it.isFile && it.name.lowercase() in setOf("socialclub.dll", "socialclub64.dll") } + } + if (pipe == null && !sdk) return failure("no-launcher-protocol") + if (pipe != null && !listOf(folder, exe.parentFile).any { java.io.File(it, "MTLX.dll").isFile }) return failure("missing-game-files") + val rosId = metadata?.rosId ?: RockstarTitles.byId(id)?.rosTitleId ?: return failure("missing-title-metadata") + var ticket = RockstarAuth.ticket(app) ?: RockstarAuth.ticket(app, fresh = true) ?: return failure("signed-out") + if (sdk && ticket.sdkTicket.isEmpty()) ticket = RockstarAuth.ticket(app, fresh = true) ?: return failure("signed-out") + val account = try { + RockstarApps.fetch(ticket.ticket) {} + } catch (e: RockstarRos.RosException) { + if (!(e.code.contains("Ticket", true) || e.code.contains("Sign", true) || e.code.contains("Auth", true))) throw e + ticket = RockstarAuth.ticket(app, fresh = true) ?: return failure("signed-out") + RockstarApps.fetch(ticket.ticket) {} + } + if (metadata != null && account.apps.none { it.titleId.toIntOrNull() == rosId && (it.name == metadata.id || it.name.startsWith(metadata.id + "_")) }) return failure("title-metadata-mismatch") + val tokenRoot = RockstarRos.result("app.asmx/GetTitleAccessToken2", listOf("ticket" to ticket.ticket, "titleId" to rosId.toString(), "platformId" to "8")) + val token = RockstarRos.text(tokenRoot, "Result")?.takeIf { it.isNotEmpty() } ?: return failure("no-title-token") + val result = JSONObject().put("ok", true).put("expiresAt", System.currentTimeMillis() + 90_000) + if (sdk) { + val session = JSONObject().put("accountId", ticket.rockstarId).put("identity", ticket.email.ifEmpty { ticket.nickname }).put("ticket", ticket.sdkTicket) + if (RockstarLibrary.owns(account, rosId, metadata?.id ?: id)) session.put("titleId", metadata?.id ?: id) + result.put("session", session) + } + if (pipe == null) return result + val hash = MessageDigest.getInstance("SHA-256").digest(RockstarAuth.fingerprint(app).toString().toByteArray()).copyOf(16) + val launch = RockstarRos.result("app.asmx/GetTitleLaunchData", listOf("ticket" to ticket.ticket, "titleAccessToken" to token, + "machineHash" to Base64.getEncoder().encodeToString(hash))) + val encoded = RockstarRos.text(launch, "Data") ?: return failure("no-launch-data") + val iv = RockstarRos.text(launch, "EndpointIV") ?: return failure("no-launch-iv") + val material = RockstarLaunchCipher.decode(encoded, iv) + return result.put("pipe", pipe).put("material", material) + } + + private fun failure(reason: String) = JSONObject().put("ok", false).put("reason", reason) +} diff --git a/app/src/main/java/com/droiddeck/launcher/stores/rockstar/RockstarLaunchCipher.kt b/app/src/main/java/com/droiddeck/launcher/stores/rockstar/RockstarLaunchCipher.kt new file mode 100644 index 0000000000..dd65b40b7c --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/stores/rockstar/RockstarLaunchCipher.kt @@ -0,0 +1,66 @@ +package com.droiddeck.launcher.stores.rockstar + +import java.nio.ByteBuffer +import java.nio.ByteOrder +import java.util.Base64 + +internal object RockstarLaunchCipher { + private val data by lazy { + val bytes = requireNotNull(javaClass.getResourceAsStream("/rockstar/legacy-cipher.bin")).use { it.readBytes() } + require(bytes.size == 86852 && bytes.copyOfRange(0, 8).contentEquals("DDRGLC01".toByteArray())) + bytes + } + private val tables by lazy { + ByteBuffer.wrap(data, 8, 86016).order(ByteOrder.LITTLE_ENDIAN).asIntBuffer().let { buffer -> IntArray(buffer.remaining()).also { buffer.get(it) } } + } + private val order = intArrayOf(0, 7, 10, 13, 1, 4, 11, 14, 2, 5, 8, 15, 3, 6, 9, 12) + + internal fun decrypt(cipher: ByteArray, iv: ByteArray, inner: Boolean): ByteArray { + require(cipher.isNotEmpty() && cipher.size <= 65536 && cipher.size % 16 == 0 && iv.size == 16) + val map = 86024 + val key = map + 272 + if (inner) 272 else 0 + val keys = ByteBuffer.wrap(data, key, 272).order(ByteOrder.LITTLE_ENDIAN).asIntBuffer().let { buffer -> IntArray(68).also { buffer.get(it) } } + val output = ByteArray(cipher.size) + var previous = iv + for (offset in cipher.indices step 16) { + var state = cipher.copyOfRange(offset, offset + 16) + for (round in 0..16) { + val next = ByteBuffer.allocate(16).order(ByteOrder.LITTLE_ENDIAN) + for (column in 0..3) { + var word = keys[round * 4 + column] + for (slot in column * 4 until column * 4 + 4) { + val index = if (round == 0 || round == 1 || round == 16) slot else order[slot] + val table = data[map + round * 16 + index].toInt() and 255 + require(table < 84) + word = word xor tables[table * 256 + (state[index].toInt() and 255)] + } + next.putInt(word) + } + state = next.array() + } + for (i in 0..15) output[offset + i] = (state[i].toInt() xor previous[i].toInt()).toByte() + previous = cipher.copyOfRange(offset, offset + 16) + } + val padding = output.last().toInt() and 255 + require(padding in 1..16 && output.takeLast(padding).all { (it.toInt() and 255) == padding }) + return output.copyOf(output.size - padding) + } + + fun decode(encoded: String, endpointIv: String): String { + require(encoded.length <= 90000 && endpointIv.length <= 32) + val clear = decrypt(Base64.getDecoder().decode(encoded), Base64.getDecoder().decode(endpointIv), false) + require(clear.size > 128) + val xml = clear.copyOf(clear.size - 128).toString(Charsets.UTF_8) + val root = RockstarRos.parse(xml) + require(root.tagName == "EncryptedResponse") + val date = requireNotNull(RockstarRos.text(root, "CreationDate")).toLong() + require(date in 0..0xffffffffL) + val text = requireNotNull(RockstarRos.text(root, "Data")) + require(text.length == 672 && text.all { it.digitToIntOrNull(16) != null }) + val cipher = ByteArray(text.length / 2) { i -> text.substring(i * 2, i * 2 + 2).toInt(16).toByte() } + val iv = ByteBuffer.allocate(16).order(ByteOrder.LITTLE_ENDIAN).put(data, data.size - 12, 12).putInt(date.toInt()).array() + val material = decrypt(cipher, iv, true) + require(material.size == 320) + return material.joinToString("") { "%02X".format(it) } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/stores/rockstar/RockstarMetadata.kt b/app/src/main/java/com/droiddeck/launcher/stores/rockstar/RockstarMetadata.kt new file mode 100644 index 0000000000..5a7e052946 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/stores/rockstar/RockstarMetadata.kt @@ -0,0 +1,53 @@ +package com.droiddeck.launcher.stores.rockstar + +import org.json.JSONObject +import java.io.File +import java.nio.ByteBuffer +import java.nio.ByteOrder +import java.nio.charset.CodingErrorAction +import javax.crypto.Cipher +import javax.crypto.spec.IvParameterSpec +import javax.crypto.spec.SecretKeySpec + +internal object RockstarMetadata { + data class Title(val id: String, val rosId: Int, val exe: String) + + fun find(folder: File): Title? { + val root = folder.canonicalFile + var level = listOf(root) + repeat(4) { + val entries = level.map { it.listFiles().orEmpty() } + val metadata = entries.flatMap { files -> files.filter { it.name.equals("title.rgl", true) } } + for (file in metadata.filter { it.isFile && !java.nio.file.Files.isSymbolicLink(it.toPath()) && it.canonicalPath.startsWith(root.path + File.separator) }) { + if (file.length() in 112..1_048_576) runCatching { decode(file.readBytes()) }.getOrNull()?.let { + return it.copy(exe = File(file.parentFile, it.exe).relativeTo(root).invariantSeparatorsPath) + } + } + level = entries.flatMap { files -> files.asSequence().filter { + it.isDirectory && !java.nio.file.Files.isSymbolicLink(it.toPath()) && it.canonicalPath.startsWith(root.path + File.separator) + }.take(256).toList() }.take(256) + } + return null + } + + fun decode(bytes: ByteArray): Title? = runCatching { + require(bytes.size in 112..1_048_576 && bytes.copyOfRange(0, 4).contentEquals(byteArrayOf(82, 71, 76, 77))) + val header = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN) + require(header.getInt(4) == 1 && header.getInt(8) == bytes.size - 80 && (bytes.size - 80) % 16 == 0) + val cipher = Cipher.getInstance("AES/CBC/NoPadding") + cipher.init(Cipher.DECRYPT_MODE, SecretKeySpec(ByteArray(32), "AES"), IvParameterSpec(bytes.copyOfRange(80, 96))) + val clear = cipher.doFinal(bytes, 96, bytes.size - 96) + val pad = clear.last().toInt() and 255 + val size = if (pad in 1..16 && clear.takeLast(pad).all { (it.toInt() and 255) == pad }) clear.size - pad + else clear.indexOfLast { it != 0.toByte() } + 1 + val text = Charsets.UTF_8.newDecoder().onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT).decode(ByteBuffer.wrap(clear, 0, size)).toString().removePrefix("\uFEFF") + val json = JSONObject(text) + val id = json.getString("titleId") + val rosId = json.get("rosTitleId").toString().takeIf { Regex("[1-9][0-9]{0,4}").matches(it) }?.toInt() ?: return null + val exe = json.getString("principalFileName").replace('\\', '/') + require(Regex("[a-z][a-z0-9_]{0,63}").matches(id) && rosId in 1..65535) + require(exe.isNotEmpty() && !exe.startsWith('/') && ':' !in exe && '\u0000' !in exe && exe.split('/').none { it == ".." }) + Title(id, rosId, exe) + }.getOrNull() +} diff --git a/app/src/main/java/com/droiddeck/launcher/stores/rockstar/RockstarRos.kt b/app/src/main/java/com/droiddeck/launcher/stores/rockstar/RockstarRos.kt new file mode 100644 index 0000000000..88217aed08 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/stores/rockstar/RockstarRos.kt @@ -0,0 +1,96 @@ +package com.droiddeck.launcher.stores.rockstar + +import org.w3c.dom.Element +import java.io.ByteArrayInputStream +import java.net.HttpURLConnection +import java.net.URL +import java.net.URLEncoder +import javax.xml.XMLConstants +import javax.xml.parsers.DocumentBuilderFactory + +internal object RockstarRos { + const val HOST = "https://rgl-prod.ros.rockstargames.com" + const val PUBLIC_HOST = "https://prod.ros.rockstargames.com" + const val SERVICES = "/launcher/11/launcherservices/" + private const val MAX_BYTES = 32 * 1024 * 1024 + + class RosException(message: String, val code: String = "", val status: Int = 0) : Exception(message) + + class Reply(val status: Int, val body: String) + + fun form(fields: List>): String = + fields.joinToString("&") { (k, v) -> "$k=" + URLEncoder.encode(v, "UTF-8") } + + fun call(method: String, fields: List>, host: String = HOST, headers: Map = emptyMap()): Reply { + val c = URL(host + SERVICES + method).openConnection() as HttpURLConnection + c.requestMethod = "POST" + c.connectTimeout = 20_000 + c.readTimeout = 60_000 + c.instanceFollowRedirects = false + c.doOutput = true + c.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=utf-8") + c.setRequestProperty("User-Agent", RockstarAuth.USER_AGENT) + for ((k, v) in headers) c.setRequestProperty(k, v) + try { + c.outputStream.use { it.write(form(fields).toByteArray(Charsets.UTF_8)) } + val status = c.responseCode + val stream = (if (status in 200..299) c.inputStream else c.errorStream) + val bytes = stream?.use { input -> + val out = java.io.ByteArrayOutputStream() + val buf = ByteArray(64 * 1024) + while (true) { + val n = input.read(buf) + if (n < 0) break + out.write(buf, 0, n) + if (out.size() > MAX_BYTES) throw RosException("$method: answer too large", status = status) + } + out.toByteArray() + } ?: ByteArray(0) + return Reply(status, bytes.toString(Charsets.UTF_8)) + } finally { + c.disconnect() + } + } + + fun result(method: String, fields: List>, host: String = HOST, headers: Map = emptyMap()): Element { + val reply = call(method, fields, host, headers) + if (reply.status !in 200..299) throw RosException("$method: HTTP ${reply.status}", status = reply.status) + val root = runCatching { parse(reply.body) }.getOrNull() + ?: throw RosException("$method: HTTP ${reply.status} invalid response", status = reply.status) + if (text(root, "Status") != "1") { + val error = first(root, "Error") + val code = listOfNotNull(error?.getAttribute("Code")?.takeIf { it.isNotEmpty() }, error?.getAttribute("CodeEx")?.takeIf { it.isNotEmpty() }).joinToString("/") + throw RosException("$method: ${code.ifEmpty { "HTTP ${reply.status}" }}", code, reply.status) + } + return root + } + + fun parse(xml: String): Element { + require(!xml.contains(" 0) it.item(0) as Element else null } + + fun all(root: Element, tag: String): List = root.getElementsByTagName(tag).let { l -> (0 until l.length).map { l.item(it) as Element } } + + fun text(root: Element, tag: String): String? = first(root, tag)?.textContent?.trim() + + fun children(parent: Element, tag: String): List { + val out = ArrayList() + var n = parent.firstChild + while (n != null) { + if (n is Element && n.tagName == tag) out += n + n = n.nextSibling + } + return out + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/stores/rockstar/RockstarTitles.kt b/app/src/main/java/com/droiddeck/launcher/stores/rockstar/RockstarTitles.kt new file mode 100644 index 0000000000..bbbc0e69dd --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/stores/rockstar/RockstarTitles.kt @@ -0,0 +1,84 @@ +package com.droiddeck.launcher.stores.rockstar + +import com.droiddeck.launcher.stores.CatalogItem +import com.droiddeck.launcher.stores.Store + +internal data class RockstarTitle( + val id: String, + val rosTitleId: Int, + val name: String, + val exe: String, + val registryKey: String, + val steamAppId: Int, + val released: String, + val platform: String = "pcros", + val description: String = "", + val page: String = "", +) + +internal object RockstarTitles { + private const val ART = "https://cdn.cloudflare.steamstatic.com/steam/apps/" + + val all = listOf( + RockstarTitle("gta5_gen9", 11, "Grand Theft Auto V Enhanced", "GTA5_Enhanced.exe", "Rockstar Games\\GTAV Enhanced", 3240220, "2025-03-04", platform = "pcrosalt", + description = "Story mode and GTA Online with ray-traced visuals, faster loading and DualSense support.", + page = "https://www.rockstargames.com/gta-v"), + RockstarTitle("gta5", 11, "Grand Theft Auto V Legacy", "GTA5.exe", "Rockstar Games\\Grand Theft Auto V", 271590, "2015-04-14", + description = "Three criminals, one city: the original PC release of Grand Theft Auto V.", + page = "https://www.rockstargames.com/gta-v"), + RockstarTitle("rdr2", 13, "Red Dead Redemption 2", "RDR2.exe", "Rockstar Games\\Red Dead Redemption 2", 1174180, "2019-11-05", + description = "Arthur Morgan and the Van der Linde gang on the run at the end of the outlaw era.", + page = "https://www.rockstargames.com/reddeadredemption2"), + RockstarTitle("rdr", 8, "Red Dead Redemption", "RDR.exe", "Rockstar Games\\Red Dead Redemption", 2668510, "2024-10-29", + description = "John Marston's story, with the Undead Nightmare expansion.", + page = "https://www.rockstargames.com/reddeadredemption"), + RockstarTitle("gta4", 1, "Grand Theft Auto IV: The Complete Edition", "GTAIV.exe", "Rockstar Games\\Grand Theft Auto IV", 12210, "2008-12-02", + description = "Niko Bellic's Liberty City, with The Lost and Damned and The Ballad of Gay Tony.", + page = "https://www.rockstargames.com/games/IV"), + RockstarTitle("lanoire", 9, "L.A. Noire", "LANoire.exe", "Rockstar Games\\LANoireMTL", 110800, "2011-11-08", + description = "A detective story in 1947 Los Angeles.", + page = "https://www.rockstargames.com/games/lanoire"), + RockstarTitle("lanoirevr", 24, "L.A. Noire: The VR Case Files", "LANoireVR.exe", "Rockstar Games\\LANoireVR", 722230, "2017-12-15", + description = "Seven cases from L.A. Noire rebuilt for virtual reality."), + RockstarTitle("mp3", 10, "Max Payne 3", "MaxPayne3.exe", "Rockstar Games\\MP3MTL", 204100, "2012-05-29", + description = "Max Payne, years after New York, working private security in Sรฃo Paulo.", + page = "https://www.rockstargames.com/games/maxpayne3"), + RockstarTitle("bully", 23, "Bully: Scholarship Edition", "Bully.exe", "Rockstar Games\\Bully", 12200, "2008-10-21", + description = "Jimmy Hopkins against the bullies, teachers and cliques of Bullworth Academy.", page = "https://www.rockstargames.com/bully"), + RockstarTitle("gta3unreal", 28, "Grand Theft Auto III โ€“ The Definitive Edition", "Gameface\\Binaries\\Win64\\LibertyCity.exe", "Rockstar Games\\GTA III - DE", 1546970, "2021-11-11", + description = "Liberty City, remastered with new lighting, controls and visual detail."), + RockstarTitle("gtavcunreal", 29, "Grand Theft Auto: Vice City โ€“ The Definitive Edition", "Gameface\\Binaries\\Win64\\ViceCity.exe", "Rockstar Games\\GTA Vice City - DE", 1546990, "2021-11-11", + description = "Tommy Vercetti's 1980s Vice City, remastered with new lighting, controls and visual detail."), + RockstarTitle("gtasaunreal", 30, "Grand Theft Auto: San Andreas โ€“ The Definitive Edition", "Gameface\\Binaries\\Win64\\SanAndreas.exe", "Rockstar Games\\GTA San Andreas - DE", 1547000, "2021-11-11", + description = "CJ's return to San Andreas, remastered with new lighting, controls and visual detail."), + RockstarTitle("gtasa", 18, "Grand Theft Auto: San Andreas", "gta_sa.exe", "Rockstar Games\\GTA: San Andreas", 12120, "2005-06-07", + description = "Carl Johnson's return to Los Santos and the state of San Andreas.", page = "https://www.rockstargames.com/games/sanandreas"), + RockstarTitle("gtavc", 27, "Grand Theft Auto: Vice City", "gta-vc.exe", "Rockstar Games\\Grand Theft Auto: Vice City", 12110, "2003-05-12", + description = "Tommy Vercetti's rise through 1980s Vice City.", page = "https://www.rockstargames.com/games/vicecity"), + RockstarTitle("gta3", 26, "Grand Theft Auto III", "gta3.exe", "Rockstar Games\\Grand Theft Auto III", 12100, "2002-05-20", + description = "Claude's revenge in Liberty City, the game that took the series into 3D.", page = "https://www.rockstargames.com/games/grandtheftauto3"), + ) + + private val byId = all.associateBy { it.id } + + private val PARENTS = mapOf( + "rdr2_sp" to "rdr2", "rdr2_rdo" to "rdr2", "rdr2_sp_rgl" to "rdr2", "rdr2_sp_steam" to "rdr2", "rdr2_sp_epic" to "rdr2", + "gtatrilogy" to "gtasaunreal", + ) + + fun forName(name: String): List = + if (name.equals("gtatrilogy", true)) listOf("gta3unreal", "gtavcunreal", "gtasaunreal").mapNotNull { byId[it] } else listOfNotNull(byId(name)) + + fun byId(id: String?): RockstarTitle? = id?.lowercase()?.let { byId[it] ?: byId[PARENTS[it]] } + + fun cover(t: RockstarTitle) = "$ART${t.steamAppId}/library_600x900.jpg" + fun hero(t: RockstarTitle) = "$ART${t.steamAppId}/library_hero.jpg" + fun wide(t: RockstarTitle) = "$ART${t.steamAppId}/header.jpg" + + fun item(t: RockstarTitle, owned: Boolean = false, extra: Map = emptyMap()) = CatalogItem( + store = Store.ROCKSTAR, id = t.id, title = t.name, imageUrl = hero(t), tallImageUrl = cover(t), + storeUrl = t.page.ifEmpty { "https://store.rockstargames.com" }, developer = "Rockstar Games", publisher = "Rockstar Games", + releaseDate = t.released, description = t.description, owned = owned, mature = true, + extra = mapOf("rosTitleId" to t.rosTitleId.toString()) + extra, + ) +} diff --git a/app/src/main/java/com/droiddeck/launcher/stores/ubisoft/UbisoftBackend.kt b/app/src/main/java/com/droiddeck/launcher/stores/ubisoft/UbisoftBackend.kt index 09008e1927..5d1a8c31bc 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/ubisoft/UbisoftBackend.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/ubisoft/UbisoftBackend.kt @@ -10,6 +10,7 @@ import com.droiddeck.launcher.stores.InstalledStoreGame import com.droiddeck.launcher.stores.LoginFlows import com.droiddeck.launcher.stores.Store import com.droiddeck.launcher.stores.StoreBackend +import com.droiddeck.launcher.stores.StoreFront import com.droiddeck.launcher.stores.StoreInstallRoot import com.droiddeck.launcher.stores.download.DownloadEntry import com.droiddeck.launcher.stores.download.DownloadQueue @@ -44,15 +45,21 @@ object UbisoftBackend : StoreBackend { Thread({ UbisoftLibrary.sync(app, force) }, "ubisoft-sync").start() } - override fun loadShelves(context: Context, force: Boolean) {} + override fun loadShelves(context: Context, force: Boolean) { + val app = context.applicationContext + val account = UbisoftLibrary.account() + UbisoftStore.cached(app)?.let { s -> StoresState.post { StoresState.shelves[store] = StoreFront.markOwned(s, StoresState.library[store], UbisoftStore::sameGame) } } + Thread({ + val shelves = UbisoftStore.featured(app, force) ?: return@Thread + StoresState.post { if (UbisoftLibrary.account() == account) StoresState.shelves[store] = StoreFront.markOwned(shelves, StoresState.library[store], UbisoftStore::sameGame) } + }, "ubisoft-shelves").start() + } + + override fun search(context: Context, query: String): List = + StoreFront.markOwned(UbisoftStore.search(query), StoresState.library[store], UbisoftStore::sameGame) override fun install(context: Context, item: CatalogItem, root: java.io.File) { val app = context.applicationContext - item.extra[STEAM_APP]?.takeIf { item.extra["productId"] == null }?.let { steam -> - StoresState.logLine("Ubisoft: ${item.title} is owned on Steam; installing Steam app $steam") - installInSteam(app, steam) - return - } if (!UbisoftNative.ready()) { StoresState.logLine(UbisoftNative.ENGINE_MISSING) StoresState.post { StoresState.problems[store] = UbisoftNative.ENGINE_MISSING } @@ -65,19 +72,6 @@ object UbisoftBackend : StoreBackend { } override fun uninstall(context: Context, game: InstalledStoreGame) {} - - const val STEAM_APP = "steamAppId" - - /** Steam asks to install a game it does not have when told to run it. */ - private fun installInSteam(app: Context, steamAppId: String) { - if (com.droiddeck.launcher.session.SessionState.running) { - if (!com.droiddeck.launcher.session.SessionService.launchGame(app, steamAppId)) StoresState.logLine("Ubisoft: Steam is busy; install Steam app $steamAppId there") - return - } - app.startActivity(Intent(app, com.droiddeck.launcher.SessionActivity::class.java) - .putExtra(com.droiddeck.launcher.session.SessionService.EXTRA_STEAM_URL, com.droiddeck.launcher.frontend.GameLaunchLink.steamUrl(steamAppId)) - .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) - } } internal class UbisoftLogin(override val userAgent: String) : StoreLoginActivity.Flow { @@ -115,6 +109,9 @@ object UbisoftLibrary { StoresState.post { StoresState.shelves.remove(Store.UBISOFT) } } + /** Changes on every sign-out, so work begun for the old account can tell. */ + fun account(): Int = generation.get() + private fun post(gen: Int, block: () -> Unit) = StoresState.post { if (generation.get() == gen) block() } internal fun parsePage(body: String): Pair, Int> { @@ -134,11 +131,20 @@ object UbisoftLibrary { return items to games.optInt("totalCount", items.size) } - /** Base games with a manifest, by UbiServices space; add-ons and bundles share spaces with their game. */ + private val THIRD_PARTY = Regex("""^\s*third_party_platform:\s*\r?\n\s+name:\s*['"]?([^'"\r\n]+?)['"]?\s*$""", RegexOption.MULTILINE) + + /** The store a product's configuration says delivers it, such as Steam, when not Ubisoft itself. */ + internal fun thirdParty(configuration: String): String? = THIRD_PARTY.find(configuration)?.groupValues?.get(1)?.trim()?.takeIf { it.isNotEmpty() } + + /** + * Owned base games Ubisoft delivers itself, by UbiServices space; add-ons and bundles share spaces with their + * game. A game whose manifest Ubisoft did not send stays: the manifest only names the build to download. + */ internal fun ownedBySpace(owned: JSONObject?): Map { val list = owned?.optJSONArray("games") ?: return emptyMap() val games = (0 until list.length()).mapNotNull { list.optJSONObject(it) } - .filter { it.optString("manifest").isNotEmpty() && it.optInt("productType") == 0 && it.optBoolean("owned", true) } + .filter { it.optInt("productType") == 0 && it.optBoolean("owned", true) && thirdParty(it.optString("configuration")) == null } + .sortedByDescending { it.optString("manifest").isNotEmpty() } val out = LinkedHashMap() for (key in listOf("spaceId")) for (g in games) { val space = g.optString(key).takeIf { it.isNotEmpty() } ?: continue @@ -147,19 +153,30 @@ object UbisoftLibrary { return out } - private val STEAM_ID = Regex("""^\s*steam_app_id:\s*['"]?(\d+)""", RegexOption.MULTILINE) - private val THIRD_PARTY = Regex("""^\s*third_party_platform:\s*\r?\n\s+name:\s*['"]?Steam\b""", setOf(RegexOption.MULTILINE, RegexOption.IGNORE_CASE)) + private fun download(o: JSONObject) = listOfNotNull( + "productId" to o.optLong("productId").toString(), + o.optString("manifest").takeIf { it.isNotEmpty() }?.let { "manifest" to it }, + o.optString("appId").takeIf { it.isNotEmpty() }?.let { "appId" to it }, + executable(o.optString("configuration"))?.let { "exe" to it }, + ) - /** The Steam app of a product Ubisoft says is owned and installed through Steam. */ - internal fun steamApp(configuration: String): String? = - if (THIRD_PARTY.containsMatchIn(configuration)) STEAM_ID.find(configuration)?.groupValues?.get(1) else null - - /** Owned games Ubisoft delivers through Steam, by UbiServices space. */ - internal fun steamBySpace(owned: JSONObject?): Map { - val list = owned?.optJSONArray("games") ?: return emptyMap() - return (0 until list.length()).mapNotNull { list.optJSONObject(it) } - .filter { it.optInt("productType") == 0 && it.optBoolean("owned", true) && it.optString("spaceId").isNotEmpty() } - .mapNotNull { o -> steamApp(o.optString("configuration"))?.let { o.optString("spaceId") to it } }.toMap() + /** + * Games Connect owns and delivers itself. The profile's game list also names games only played through + * Ubisoft+, free weekends or another store; without an ownership answer that list is all there is. + */ + internal fun assemble(listed: List, owned: JSONObject?): List { + val known = owned?.optJSONArray("games") != null && owned.optString("error").isEmpty() + val bySpace = ownedBySpace(owned) + val matched = listed.map { g -> bySpace[g.id]?.let { g.copy(extra = g.extra + download(it)) } ?: g } + .filter { !known || it.extra["productId"] != null } + .let { games -> games.filter { g -> g.extra["productId"] == null || games.first { it.extra["productId"] == g.extra["productId"] } === g } } + .let { games -> games.filter { g -> g.extra["productId"] != null || games.none { it !== g && it.title == g.title && it.extra["productId"] != null } } } + val products = matched.mapNotNull { it.extra["productId"] }.toSet() + val unlisted = bySpace.filterKeys { space -> listed.none { it.id == space } }.filterValues { it.optLong("productId").toString() !in products }.mapNotNull { (space, o) -> + val title = title(o.optString("configuration")) ?: return@mapNotNull null + CatalogItem(Store.UBISOFT, space, title, null, owned = true, extra = mapOf("spaceId" to space) + download(o)) + } + return (matched + unlisted).sortedBy { it.title.lowercase() } } private val RELATIVE = Regex("""relative:\s*['"]?([^'"\r\n]+?)['"]?\s*$""", RegexOption.MULTILINE) @@ -205,37 +222,26 @@ object UbisoftLibrary { } val owned = UbisoftNative.call("owned", JSONObject().put("ticket", s.ticket).put("sessionId", s.sessionId)) owned?.optString("error")?.takeIf { it.isNotEmpty() }?.let { StoresState.logLine("Ubisoft: ownership: $it") } - val bySpace = ownedBySpace(owned) owned?.takeIf { it.optInt("manifestsAsked") > 0 }?.let { StoresState.logLine("Ubisoft: latest manifests: ${it.optInt("manifestsFound")} of ${it.optInt("manifestsAsked")} ${it.optString("manifestError")}".trim()) } - fun download(o: JSONObject) = listOfNotNull( - "productId" to o.optLong("productId").toString(), - o.optString("manifest").takeIf { it.isNotEmpty() }?.let { "manifest" to it }, - o.optString("appId").takeIf { it.isNotEmpty() }?.let { "appId" to it }, - executable(o.optString("configuration"))?.let { "exe" to it }, - ) val listed = all.distinctBy { it.id } - val onSteam = steamBySpace(owned) - val matched = listed.map { g -> bySpace[g.id]?.let { g.copy(extra = g.extra + download(it)) } ?: onSteam[g.id]?.let { g.copy(extra = g.extra + (UbisoftBackend.STEAM_APP to it)) } ?: g } - .let { games -> games.filter { g -> g.extra["productId"] == null || games.first { it.extra["productId"] == g.extra["productId"] } === g } } - .let { games -> games.filter { g -> g.extra["productId"] != null || games.none { it !== g && it.title == g.title && it.extra["productId"] != null } } } - val products = matched.mapNotNull { it.extra["productId"] }.toSet() - val unlisted = bySpace.filterKeys { space -> listed.none { it.id == space } }.filterValues { it.optLong("productId").toString() !in products }.mapNotNull { (space, o) -> - val title = title(o.optString("configuration")) ?: return@mapNotNull null - CatalogItem(Store.UBISOFT, space, title, null, owned = true, extra = mapOf("spaceId" to space) + download(o)) + val games = assemble(listed, owned) + ownedBySpace(owned).values.filter { it.optString("manifest").isEmpty() }.takeIf { it.isNotEmpty() }?.let { bare -> + StoresState.logLine("Ubisoft: owned without a manifest: " + bare.joinToString(", ") { (title(it.optString("configuration")) ?: "?") + "=" + it.optLong("productId") }) } - val games = (matched + unlisted).sortedBy { it.title.lowercase() } - StoresState.logLine("Ubisoft: ${bySpace.size} downloadable products; " + + StoresState.logLine("Ubisoft: ${ownedBySpace(owned).size} owned products; " + games.filter { it.extra.containsKey("productId") }.joinToString(", ") { "${it.title}=${it.extra["productId"]}" }) + listed.filter { g -> games.none { it.id == g.id } }.takeIf { it.isNotEmpty() }?.let { left -> + StoresState.logLine("Ubisoft: left out ${left.size} games Connect does not deliver to this account: " + left.joinToString(", ") { it.title }) + } post(gen) { StoresState.status.remove(Store.UBISOFT) StoresState.problems.remove(Store.UBISOFT) StoresState.library[Store.UBISOFT] = games - StoresState.shelves[Store.UBISOFT] = com.droiddeck.launcher.stores.StoreShelves( - trending = games.sortedByDescending { it.extra.containsKey("productId") }, art = games.mapNotNull { it.imageUrl }) + StoresState.shelves[Store.UBISOFT]?.let { StoresState.shelves[Store.UBISOFT] = StoreFront.markOwned(it, games, UbisoftStore::sameGame) } } - StoresState.logLine("Ubisoft: ${games.size} owned games; on Steam: " + games.filter { it.extra.containsKey(UbisoftBackend.STEAM_APP) }.joinToString(", ") { "${it.title}=${it.extra[UbisoftBackend.STEAM_APP]}" }) + StoresState.logLine("Ubisoft: ${games.size} owned games") } catch (e: Exception) { StoresState.logLine("Ubisoft: library sync failed: ${e.javaClass.simpleName} ${e.message.orEmpty().take(200)}") post(gen) { StoresState.status.remove(Store.UBISOFT); StoresState.problems[Store.UBISOFT] = app.getString(R.string.stores_sync_failed) } diff --git a/app/src/main/java/com/droiddeck/launcher/stores/ubisoft/UbisoftStore.kt b/app/src/main/java/com/droiddeck/launcher/stores/ubisoft/UbisoftStore.kt new file mode 100644 index 0000000000..13edb2084f --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/stores/ubisoft/UbisoftStore.kt @@ -0,0 +1,129 @@ +package com.droiddeck.launcher.stores.ubisoft + +import android.content.Context +import android.net.Uri +import com.droiddeck.launcher.stores.CatalogItem +import com.droiddeck.launcher.stores.Store +import com.droiddeck.launcher.stores.StoreFront +import com.droiddeck.launcher.stores.StoreNet +import com.droiddeck.launcher.stores.StoreShelves +import com.droiddeck.launcher.stores.cleanStoreText +import com.droiddeck.launcher.stores.matureByAge +import org.json.JSONArray +import org.json.JSONObject +import java.text.NumberFormat +import java.time.Instant +import java.util.Currency +import java.util.Locale + +/** Ubisoft's PC catalog, from the product search the Ubisoft Store website uses. */ +object UbisoftStore { + /** The Ubisoft Store website's own read-only search key, sent by every store page. */ + private const val APP = "XELY3U4LOD" + private const val KEY = "5638539fd9edb8f2c6b024b49ec375bd" + private const val SHELF = 24 + private val RATING_AGE = mapOf("esrb-m" to 17, "esrb-ao" to 18, "pegi-18" to 18, "pegi-16" to 16, "usk-18" to 18) + + /** The store sites with an English catalog: site, index locale, currency. */ + private val SITES = mapOf( + "US" to Triple("us", "en_US", "USD"), "GB" to Triple("uk", "en_GB", "GBP"), + "CA" to Triple("ca", "en_CA", "CAD"), "AU" to Triple("anz", "en_AU", "AUD"), "NZ" to Triple("anz", "en_AU", "NZD"), + ) + + private fun site() = SITES[Locale.getDefault().country.uppercase(Locale.ROOT)] ?: SITES.getValue("US") + + private fun index(site: Triple, order: String) = "production__${site.first}_ubisoft__products__${site.second}__$order" + + private val fronts = HashMap, StoreFront>() + + /** Each store site keeps its own shelves, so a region change never shows another region's prices. */ + private fun front(context: Context): StoreFront = synchronized(fronts) { + val site = site() + fronts.getOrPut(site) { + StoreFront(Store.UBISOFT, { context.applicationContext.getSharedPreferences("stores.ubisoft", Context.MODE_PRIVATE) }, + { fetch(site) }, key = "store_front_${site.first}_${site.third}") + } + } + + fun cached(context: Context): StoreShelves? = front(context).cached() + + fun featured(context: Context, force: Boolean): StoreShelves? = front(context).shelves(force) + + fun search(query: String): List { + val term = query.trim() + if (term.length < 2) return emptyList() + return query(site(), "best_sellers", 40, query = term).orEmpty() + } + + /** Whether a store card and a library entry are the same game. */ + fun sameGame(shelf: CatalogItem, owned: CatalogItem): Boolean { + val product = shelf.extra["productId"].orEmpty() + if (product.isNotEmpty() && product == owned.extra["productId"]) return true + val key = StoreFront.titleKey(owned.title) + return key.isNotEmpty() && key == baseTitle(shelf.title) + } + + /** A product title without its edition, so "Far Cryยฎ 6 - Gold Edition" is "far cry 6". */ + internal fun baseTitle(title: String): String = StoreFront.titleKey(title.substringBefore(" - ")) + + /** One page of the index, or null when Ubisoft did not answer. */ + private fun query(site: Triple, order: String, hits: Int, query: String = "", filters: String = "", facets: List = emptyList()): List? { + val facetFilters = JSONArray().put("product_type:Games").put("Platform:PC (Digital)").apply { facets.forEach { put(it) } } + val url = Uri.parse("https://$APP-dsn.algolia.net/1/indexes/${index(site, order)}").buildUpon() + .appendQueryParameter("query", query) + .appendQueryParameter("hitsPerPage", (hits * 2).toString()) + .appendQueryParameter("facetFilters", facetFilters.toString()) + .apply { if (filters.isNotEmpty()) appendQueryParameter("filters", filters) } + .build().toString() + val body = StoreNet.get(url, headers = mapOf("X-Algolia-Application-Id" to APP, "X-Algolia-API-Key" to KEY)) ?: return null + return parse(JSONObject(body), site.third).take(hits) + } + + internal fun parse(answer: JSONObject, currency: String, now: Instant = Instant.now()): List { + val hits = answer.optJSONArray("hits") ?: return emptyList() + val items = (0 until hits.length()).mapNotNull { hits.optJSONObject(it) }.mapNotNull { item(it, currency, now) } + return items.groupBy { baseTitle(it.title) }.values.map { editions -> editions.firstOrNull { " - " !in it.title } ?: editions.first() } + } + + private fun money(amount: Double, currency: String): String = NumberFormat.getCurrencyInstance(Locale.US).apply { + this.currency = Currency.getInstance(currency) + }.format(amount) + + internal fun item(h: JSONObject, currency: String, now: Instant): CatalogItem? { + fun s(k: String) = h.optString(k).takeIf { it.isNotBlank() && it != "null" } + val id = s("objectID") ?: s("id") ?: return null + val title = s("title") ?: s("name") ?: return null + if (s("Free_offer") == "demo") return null + val price = h.optJSONObject("price")?.optDouble(currency)?.takeUnless { it.isNaN() } + val base = h.optJSONObject("default_price")?.optDouble(currency)?.takeUnless { it.isNaN() } + val discount = s("promotion_percentage")?.toDoubleOrNull()?.toInt() ?: 0 + val released = s("release_date")?.let { runCatching { Instant.parse(it) }.getOrNull() } + if (released != null && released.isAfter(now) && s("preorder") != "true") return null + val free = s("Free_offer") == "freeplay" || price == 0.0 + val image = s("image_link")?.substringBefore("?") + return CatalogItem( + store = Store.UBISOFT, id = "ubisoft-store:$id", title = title.trim(), + imageUrl = image, tallImageUrl = image, tags = listOfNotNull(s("Genre"), s("Edition")).joinToString(", "), + isFree = free, hasPrice = price != null, finalPrice = price?.let { money(it, currency) }.orEmpty(), + originalPrice = if (discount > 0 && base != null) money(base, currency) else "", discountPercent = if (discount > 0 && base != null) discount else 0, + storeUrl = s("link") ?: s("linkWeb").orEmpty(), publisher = "Ubisoft", releaseDate = released?.toString()?.take(10).orEmpty(), + description = cleanStoreText(s("longDescription")), + mature = s("adult").equals("TRUE", true) || matureByAge(listOfNotNull(s("Rating")?.let(RATING_AGE::get))), + extra = buildMap { + s("productLauncherIDString")?.let { put("productId", it) } + if (s("partOfUbisoftPlus").equals("true", true)) put("ubisoftPlus", "true") + }, + ) + } + + /** All four rows, or a failure when any of them failed, so a partial refresh never replaces a good one. */ + private fun fetch(site: Triple): StoreFront.Catalog { + fun row(order: String, filters: String = "", facets: List = emptyList()) = + query(site, order, SHELF, filters = filters, facets = facets) ?: throw java.io.IOException("Ubisoft store $order $filters$facets failed") + val trending = row("best_sellers") + val newest = row("release_date") + val deals = row("best_sellers", filters = "promotion_percentage > 0") + val free = row("best_sellers", facets = listOf("Free_offer:freeplay")) + return StoreFront.Catalog(StoreShelves(whatsNew = newest, deals = deals, free = free, trending = trending, art = trending.mapNotNull { it.imageUrl })) + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/AddedGameEditor.kt b/app/src/main/java/com/droiddeck/launcher/ui/AddedGameEditor.kt index 89e1480869..a1b205e64a 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/AddedGameEditor.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/AddedGameEditor.kt @@ -70,6 +70,7 @@ import com.droiddeck.launcher.frontend.AddedGameArt import com.droiddeck.launcher.frontend.AddedGameEdits import com.droiddeck.launcher.frontend.AddedGames import com.droiddeck.launcher.frontend.LogoPosition +import com.droiddeck.launcher.frontend.SoundtrackCollectionArt import com.droiddeck.launcher.frontend.SteamGameArt import com.droiddeck.launcher.frontend.SteamGridDb import com.droiddeck.launcher.frontend.SteamLaunchOptions @@ -179,6 +180,16 @@ internal class ArtTarget( { c, value -> AddedGameEdits.setLogoPosition(c, game.folder.path, value) }, ) + fun ofCollection(id: Int, name: String, root: java.io.File? = null) = ArtTarget( + name, + { c, _ -> SoundtrackCollectionArt.source(c, id) }, + { c, _ -> AddedGameArt.Choices(SoundtrackCollectionArt.options(c, id, root), SteamGridDb.Status.OK) }, + { c, _, option -> SoundtrackCollectionArt.choose(c, id, option) }, + { c, _ -> SoundtrackCollectionArt.reset(c, id) }, + { _ -> null }, + { _, _ -> false }, + ) + fun of(game: com.droiddeck.launcher.frontend.Library.SteamGame) = ArtTarget( game.name, { c, slot -> SteamGameArt.chosenSource(c, game.appId, slot).second }, @@ -199,6 +210,12 @@ internal fun SteamGameArtEditor( ArtOnlyEditor(game.name, target, game, { SteamGameArt.describe(it, game) }, onClose, onChanged) } +@Composable +internal fun CollectionArtEditor(id: Int, name: String, root: java.io.File? = null, onClose: () -> Unit, onChanged: () -> Unit) { + val target = remember(id, root) { ArtTarget.ofCollection(id, name, root) } + ArtOnlyEditor(name, target, id, { SoundtrackCollectionArt.describe(it, id, root) }, onClose, onChanged, listOf(AddedGameArt.Slot.COVER)) +} + @Composable internal fun StoreGameArtEditor(folder: String, name: String, onClose: () -> Unit, onChanged: () -> Unit) { val app = LocalContext.current.applicationContext @@ -212,7 +229,7 @@ internal fun StoreGameArtEditor(folder: String, name: String, onClose: () -> Uni @Composable private fun ArtOnlyEditor( name: String, target: ArtTarget?, refresh: Any?, describe: (Context) -> List, - onClose: () -> Unit, onChanged: () -> Unit, + onClose: () -> Unit, onChanged: () -> Unit, slots: List = AddedGameArt.Slot.values().toList(), ) { val app = LocalContext.current.applicationContext val shown = rememberShown(onClose) @@ -233,7 +250,7 @@ private fun ArtOnlyEditor( modifier = Modifier.fillMaxWidth().heightIn(max = maxHeight).verticalScroll(rememberScrollState()), ) { Text(stringResource(R.string.edit_artwork), fontSize = 12.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(start = 4.dp, top = 2.dp)) - for (slot in AddedGameArt.Slot.values()) key(slot) { + for (slot in slots) key(slot) { val state = arts.firstOrNull { it.slot == slot } FieldRow(slot.label(), focus = if (slot == AddedGameArt.Slot.COVER) first else null, onClick = { if (target != null) artSlot = slot }) { Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) { @@ -242,7 +259,7 @@ private fun ArtOnlyEditor( } } } - PickerRow(Icons.Outlined.Tune, stringResource(R.string.art_adjust_logo), logoPositionSummary(position?.value), enabled = target != null && position != null) { logoOpen = true } + if (AddedGameArt.Slot.LOGO in slots) PickerRow(Icons.Outlined.Tune, stringResource(R.string.art_adjust_logo), logoPositionSummary(position?.value), enabled = target != null && position != null) { logoOpen = true } } } val chosen = target ?: return diff --git a/app/src/main/java/com/droiddeck/launcher/ui/AgentEntries.kt b/app/src/main/java/com/droiddeck/launcher/ui/AgentEntries.kt index 63dde38872..3300b7f8a7 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/AgentEntries.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/AgentEntries.kt @@ -29,6 +29,7 @@ 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 androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue @@ -39,15 +40,12 @@ import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.pluralStringResource import androidx.compose.ui.res.stringResource -import androidx.compose.ui.text.AnnotatedString -import androidx.compose.ui.text.SpanStyle -import androidx.compose.ui.text.buildAnnotatedString import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontStyle import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextOverflow -import androidx.compose.ui.text.withStyle import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import coil.compose.AsyncImage @@ -57,7 +55,7 @@ import com.droiddeck.launcher.agent.AgentHost import com.droiddeck.launcher.agent.AgentHost.Entry @Composable -internal fun AgentEntry(entry: Entry, running: Boolean, last: Boolean = false) { +internal fun AgentEntry(entry: Entry, running: Boolean, last: Boolean = false, changes: Changes? = null, onRevise: () -> Unit = {}) { val colors = MaterialTheme.colorScheme val pal = LocalPalette.current when (entry) { @@ -72,12 +70,66 @@ internal fun AgentEntry(entry: Entry, running: Boolean, last: Boolean = false) { is Entry.Thought -> AgentThought(entry.text, live = false) is Entry.Used -> if (entry.tool == "TodoWrite") AgentTodos(entry.input) else AgentToolCall(entry, running) is Entry.Result -> Unit - is Entry.Finished -> if (last && AgentHost.answerless(AgentHost.entries)) AgentNoReply() else AgentTurnEnd(entry) + is Entry.Finished -> when { + last && AgentHost.answerless(AgentHost.entries) -> AgentNoReply() + last && entry.planned -> Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { + AgentTurnEnd(entry, changes) + AgentPlanActions(onRevise) + } + else -> AgentTurnEnd(entry, changes) + } } } +/** A plan turn changed nothing; Go carries the plan out with plan mode off, Revise asks for another. */ @Composable -private fun AgentTurnEnd(entry: Entry.Finished) { +private fun AgentPlanActions(onRevise: () -> Unit) { + val context = LocalContext.current + val pal = LocalPalette.current + val go = stringResource(R.string.agent_plan_go_message) + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.padding(horizontal = 4.dp)) { + PrimaryButton(stringResource(R.string.agent_plan_go), compact = true, modifier = Modifier.testTag("agent-plan-go")) { + AgentHost.choosePlan(context, false) + AgentHost.send(context, go) + } + SecondaryButton(stringResource(R.string.agent_plan_revise), compact = true, modifier = Modifier.testTag("agent-plan-revise")) { + AgentHost.choosePlan(context, true) + onRevise() + } + Text(stringResource(R.string.agent_plan_untouched), fontSize = 12.sp, color = pal.onSurfaceVariant) + } +} + +/** What a turn's edits added up to: files touched and lines added and removed. */ +internal data class Changes(val files: Int, val added: Int, val removed: Int) + +/** The edits of the turn that ends at [end], or null when it changed no file. */ +internal fun turnChanges(entries: List, end: Int): Changes? { + val start = entries.subList(0, end).indexOfLast { it is Entry.Asked } + // Plan mode saves its plan as a file of its own, which is not a change to anything. + val edits = entries.subList(start + 1, end).filterIsInstance().filter { !it.failed }.mapNotNull { diffOf(it) } + .filter { !it.path.contains("/.claude/plans/") } + if (edits.isEmpty()) return null + return Changes(edits.map { it.path }.distinct().size, edits.sumOf { it.added }, edits.sumOf { it.removed }) +} + +internal class Diff(val path: String, val lines: List) { + val added = lines.count { it.startsWith("+") } + val removed = lines.count { it.startsWith("-") } +} + +/** The diff an Edit or Write carries: its path, then lines led by ' ', '-' or '+'. */ +internal fun diffOf(entry: Entry.Used): Diff? { + if (entry.tool != "Edit" && entry.tool != "Write") return null + val lines = entry.input.lines() + val body = lines.drop(1).filter { it.isNotEmpty() } + if (lines.first().isBlank() || body.isEmpty() || body.any { it[0] != ' ' && it[0] != '-' && it[0] != '+' }) return null + if (body.none { it[0] != ' ' }) return null + return Diff(lines.first(), body) +} + +@Composable +private fun AgentTurnEnd(entry: Entry.Finished, changes: Changes?) { val colors = MaterialTheme.colorScheme val pal = LocalPalette.current val text = when { @@ -90,10 +142,19 @@ private fun AgentTurnEnd(entry: Entry.Finished) { if (u.inputTokens > 0 || u.outputTokens > 0) add(stringResource(R.string.agent_tokens, tokens(u.inputTokens), tokens(u.outputTokens))) }.joinToString(" ยท ") } - } ?: return - if (text.isEmpty()) return - Text(text, fontSize = 12.sp, color = if (entry.error != null && !entry.stopped) colors.error else pal.onSurfaceVariant, - modifier = Modifier.padding(horizontal = 4.dp)) + } + if (text.isNullOrEmpty() && changes == null) return + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.padding(horizontal = 4.dp)) { + if (changes != null) Row( + verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp), + modifier = Modifier.clip(Shape12).background(pal.surfaceVariant).padding(horizontal = 9.dp, vertical = 4.dp).testTag("agent-changes"), + ) { + Text(pluralStringResource(R.plurals.agent_files_changed, changes.files, changes.files), fontSize = 12.sp, color = pal.onSurfaceVariant) + Text("+${changes.added}", fontSize = 12.sp, fontFamily = FontFamily.Monospace, color = pal.good) + Text("โˆ’${changes.removed}", fontSize = 12.sp, fontFamily = FontFamily.Monospace, color = colors.error) + } + if (!text.isNullOrEmpty()) Text(text, fontSize = 12.sp, color = if (entry.error != null && !entry.stopped) colors.error else pal.onSurfaceVariant) + } } @Composable @@ -105,7 +166,11 @@ private fun AgentNoReply() { } } -internal fun tokens(n: Long) = if (n >= 1000) "${n / 1000}k" else n.toString() +internal fun tokens(n: Long) = when { + n >= 1_000_000 -> if (n % 1_000_000 == 0L) "${n / 1_000_000}M" else String.format(java.util.Locale.US, "%.1fM", n / 1_000_000.0) + n >= 1000 -> "${n / 1000}k" + else -> n.toString() +} @Composable internal fun AgentThought(text: String, live: Boolean) { @@ -149,12 +214,13 @@ private fun AgentTodos(list: String) { } } -/** A tool call: one line with its status, opening to the full input and output. */ +/** A tool call: one line with its status, opening to the full input and output, or to the diff of an edit. */ @Composable private fun AgentToolCall(entry: Entry.Used, running: Boolean) { val colors = MaterialTheme.colorScheme val pal = LocalPalette.current var open by rememberSaveable(entry.id.ifEmpty { entry.detail }) { mutableStateOf(false) } + val diff = remember(entry.input) { diffOf(entry) } Column( Modifier.fillMaxWidth().padding(horizontal = 4.dp).clip(Shape12).background(pal.surfaceVariant).animateContentSize(), ) { @@ -171,11 +237,19 @@ private fun AgentToolCall(entry: Entry.Used, running: Boolean) { } } Text(entry.tool, fontSize = 12.5.sp, fontWeight = FontWeight.SemiBold, color = pal.primary, modifier = Modifier.padding(start = 8.dp)) - Text(entry.detail, fontSize = 12.5.sp, fontFamily = FontFamily.Monospace, color = pal.onSurfaceVariant, + Text(diff?.path?.substringAfterLast('/') ?: entry.detail, fontSize = 12.5.sp, fontFamily = FontFamily.Monospace, color = pal.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f).padding(start = 8.dp)) + if (diff != null) { + Text("+${diff.added}", fontSize = 12.sp, fontFamily = FontFamily.Monospace, color = pal.good, modifier = Modifier.padding(start = 8.dp)) + Text("\u2212${diff.removed}", fontSize = 12.sp, fontFamily = FontFamily.Monospace, color = colors.error, modifier = Modifier.padding(start = 6.dp, end = 4.dp)) + } Icon(if (open) Icons.Outlined.ExpandLess else Icons.Outlined.ExpandMore, null, tint = pal.onSurfaceVariant, modifier = Modifier.size(18.dp)) } - if (open) Column(Modifier.padding(start = 10.dp, end = 10.dp, bottom = 10.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) { + if (open && diff != null) Column(Modifier.padding(start = 10.dp, end = 10.dp, bottom = 10.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) { + if (diff.path.contains('/')) Text(diff.path, fontSize = 11.5.sp, fontFamily = FontFamily.Monospace, color = pal.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis) + DiffBox(diff) + if (entry.failed && !entry.output.isNullOrBlank()) CodeBox(stringResource(R.string.agent_tool_output), entry.output, colors.error) + } else if (open) Column(Modifier.padding(start = 10.dp, end = 10.dp, bottom = 10.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) { if (entry.input.isNotBlank()) CodeBox(stringResource(R.string.agent_tool_input), entry.input, colors.onSurface) when { entry.output == null && running -> Text(stringResource(R.string.agent_tool_running), fontSize = 12.sp, color = pal.onSurfaceVariant) @@ -187,6 +261,30 @@ private fun AgentToolCall(entry: Entry.Used, running: Boolean) { } } +@Composable +private fun DiffBox(diff: Diff) { + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + Column( + Modifier.fillMaxWidth().heightIn(max = 360.dp).clip(Shape12).background(colors.surface) + .verticalScroll(rememberScrollState()).padding(vertical = 6.dp), + ) { + for (line in diff.lines) { + val tint = when (line[0]) { + '+' -> pal.good + '-' -> colors.error + else -> null + } + Text( + line[0] + " " + line.substring(1), + fontSize = 12.sp, fontFamily = FontFamily.Monospace, lineHeight = 17.sp, + color = tint ?: pal.onSurfaceVariant, + modifier = Modifier.fillMaxWidth().background(tint?.copy(alpha = 0.12f) ?: Color.Transparent).padding(horizontal = 10.dp), + ) + } + } +} + @Composable private fun CodeBox(label: String, text: String, color: Color) { val pal = LocalPalette.current @@ -227,81 +325,3 @@ internal fun AttachmentChip(path: String, onRemove: (() -> Unit)?) { } } } - -/** The Markdown agents write: headings, lists, fenced code, `code` and **bold**. */ -@Composable -internal fun AgentMarkdown(text: String, modifier: Modifier) { - val colors = MaterialTheme.colorScheme - val pal = LocalPalette.current - Column(modifier, verticalArrangement = Arrangement.spacedBy(6.dp)) { - for (block in markdownBlocks(text)) when (block) { - is MdBlock.Code -> Text(block.text, fontSize = 13.sp, fontFamily = FontFamily.Monospace, color = colors.onSurface, - modifier = Modifier.fillMaxWidth().clip(Shape12).background(pal.surfaceVariant).padding(12.dp)) - is MdBlock.Line -> Text( - inlineMarkdown(block.text, pal.primary2, pal.surfaceVariant), - fontSize = if (block.heading) 17.sp else 15.sp, - fontWeight = if (block.heading) FontWeight.Bold else null, - lineHeight = 22.sp, color = colors.onSurface, - modifier = if (block.bullet) Modifier.padding(start = 12.dp) else Modifier, - ) - } - } -} - -internal sealed interface MdBlock { - data class Line(val text: String, val heading: Boolean = false, val bullet: Boolean = false) : MdBlock - data class Code(val text: String) : MdBlock -} - -private val HEADING = Regex("^#{1,6}\\s+") -private val BULLET = Regex("^\\s*[-*+]\\s+") - -internal fun markdownBlocks(text: String): List { - val out = mutableListOf() - val code = StringBuilder() - var inCode = false - for (raw in text.lines()) { - if (raw.trimStart().startsWith("```")) { - if (inCode) { - out += MdBlock.Code(code.toString().trimEnd('\n')) - code.clear() - } - inCode = !inCode - continue - } - if (inCode) { - code.append(raw).append('\n') - continue - } - val line = raw.trimEnd() - if (line.isBlank()) continue - val heading = HEADING.find(line) - val bullet = BULLET.find(line) - out += when { - heading != null -> MdBlock.Line(line.substring(heading.range.last + 1), heading = true) - bullet != null -> MdBlock.Line("โ€ข " + line.substring(bullet.range.last + 1), bullet = true) - else -> MdBlock.Line(line) - } - } - if (inCode && code.isNotEmpty()) out += MdBlock.Code(code.toString().trimEnd('\n')) - return out -} - -internal fun inlineMarkdown(text: String, codeColor: Color, codeBackground: Color): AnnotatedString = buildAnnotatedString { - var i = 0 - while (i < text.length) { - val boldEnd = if (text.startsWith("**", i)) text.indexOf("**", i + 2) else -1 - val tickEnd = if (text[i] == '`') text.indexOf('`', i + 1) else -1 - when { - boldEnd > i + 2 -> { - withStyle(SpanStyle(fontWeight = FontWeight.Bold)) { append(text, i + 2, boldEnd) } - i = boldEnd + 2 - } - tickEnd > i + 1 -> { - withStyle(SpanStyle(fontFamily = FontFamily.Monospace, color = codeColor, background = codeBackground)) { append(text, i + 1, tickEnd) } - i = tickEnd + 1 - } - else -> append(text[i++]) - } - } -} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/AgentMarkdown.kt b/app/src/main/java/com/droiddeck/launcher/ui/AgentMarkdown.kt new file mode 100644 index 0000000000..0d85087f85 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/AgentMarkdown.kt @@ -0,0 +1,154 @@ +package com.droiddeck.launcher.ui + +import android.content.Context +import android.content.Intent +import android.net.Uri +import android.text.Selection +import android.text.Spannable +import android.text.SpannableStringBuilder +import android.text.Spanned +import android.widget.TextView +import android.widget.Toast +import androidx.compose.material3.MaterialTheme +import androidx.compose.runtime.Composable +import androidx.compose.runtime.remember +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.toArgb +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.unit.sp +import androidx.compose.ui.viewinterop.AndroidView +import com.droiddeck.launcher.R +import io.noties.markwon.AbstractMarkwonPlugin +import io.noties.markwon.Markwon +import io.noties.markwon.MarkwonConfiguration +import io.noties.markwon.MarkwonVisitor +import io.noties.markwon.core.MarkwonTheme +import io.noties.markwon.ext.strikethrough.StrikethroughPlugin +import io.noties.markwon.ext.tables.TableAwareMovementMethod +import io.noties.markwon.ext.tables.TablePlugin +import io.noties.markwon.ext.tables.TableRowSpan +import io.noties.markwon.ext.tasklist.TaskListPlugin +import org.commonmark.ext.autolink.AutolinkExtension +import org.commonmark.parser.Parser +import org.commonmark.ext.gfm.tables.TableCell +import org.commonmark.ext.gfm.tables.TableHead +import org.commonmark.ext.gfm.tables.TableRow +import org.commonmark.node.AbstractVisitor +import org.commonmark.node.CustomNode +import org.commonmark.node.Node + +@Composable +internal fun AgentMarkdown(text: String, modifier: Modifier) { + val context = LocalContext.current + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + val density = LocalDensity.current + val textSize = with(density) { 15.sp.toPx() } + val lineSpacing = with(density) { 3.sp.toPx() } + val renderer = remember(context, pal.primary2, pal.surfaceVariant, density) { + agentMarkdownRenderer(context, pal.primary2.toArgb(), pal.surfaceVariant.toArgb()) + } + val rendered = remember(renderer, text) { renderer.toMarkdown(text) } + AndroidView( + modifier = modifier, + factory = { TextView(it).apply { + setTextIsSelectable(true) + movementMethod = TableAwareMovementMethod.create() + includeFontPadding = false + } }, + update = { view -> + view.setTextColor(colors.onSurface.toArgb()) + view.setLinkTextColor(pal.primary2.toArgb()) + view.setTextSize(android.util.TypedValue.COMPLEX_UNIT_PX, textSize) + view.setLineSpacing(lineSpacing, 1f) + setAgentMarkdown(view, renderer, rendered) + }, + ) +} + +internal fun agentMarkdownRenderer(context: Context, linkColor: Int, codeBackground: Int): Markwon = + Markwon.builder(context) + .usePlugin(StrikethroughPlugin.create()) + .usePlugin(TablePlugin.create(context)) + .usePlugin(TaskListPlugin.create(context)) + .usePlugin(object : AbstractMarkwonPlugin() { + override fun configureParser(builder: Parser.Builder) { + builder.extensions(listOf(AutolinkExtension.create())) + } + + override fun afterRender(node: Node, visitor: MarkwonVisitor) { + val rows = mutableListOf() + node.accept(object : AbstractVisitor() { + override fun visit(customNode: CustomNode) { + if (customNode is TableHead || customNode is TableRow) { + val cells = generateSequence(customNode.firstChild) { it.next }.filterIsInstance().toList() + if (cells.isNotEmpty()) rows += cells.joinToString(" | ") { markdownCellText(it) } + else visitChildren(customNode) + } else visitChildren(customNode) + } + }) + if (rows.isEmpty()) return + // Markwon keeps table cells outside the text buffer; expose them for copy and accessibility. + val builder = visitor.builder() + val text = SpannableStringBuilder(builder.removeFromEnd(0)) + val spans = text.getSpans(0, text.length, TableRowSpan::class.java).sortedBy { text.getSpanStart(it) } + for ((row, span) in spans.withIndex().reversed()) { + val start = text.getSpanStart(span) + val end = text.getSpanEnd(span) + val content = rows[row].ifEmpty { "\u00a0" } + text.removeSpan(span) + text.replace(start, end, content) + text.setSpan(span, start, start + content.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) + } + builder.append(text) + } + + override fun configureTheme(builder: MarkwonTheme.Builder) { + builder.linkColor(linkColor).codeBackgroundColor(codeBackground) + } + + override fun configureConfiguration(builder: MarkwonConfiguration.Builder) { + builder.linkResolver { view, link -> + val intent = agentBrowserIntent(link) ?: return@linkResolver + try { + view.context.startActivity(intent) + } catch (_: android.content.ActivityNotFoundException) { + Toast.makeText(view.context, R.string.agent_browser_unavailable, Toast.LENGTH_SHORT).show() + } + } + } + }) + .build() + +private fun markdownCellText(node: Node): String = buildString { + node.accept(object : AbstractVisitor() { + override fun visit(text: org.commonmark.node.Text) { append(text.literal) } + override fun visit(code: org.commonmark.node.Code) { append(code.literal) } + override fun visit(lineBreak: org.commonmark.node.SoftLineBreak) { append(' ') } + override fun visit(lineBreak: org.commonmark.node.HardLineBreak) { append('\n') } + override fun visit(html: org.commonmark.node.HtmlInline) { append(html.literal) } + }) +} + +internal fun setAgentMarkdown(view: TextView, renderer: Markwon, rendered: Spanned) { + if (view.tag === rendered) return + val start = view.selectionStart + val end = view.selectionEnd + val sameText = view.text.toString() == rendered.toString() + renderer.setParsedMarkdown(view, rendered) + view.tag = rendered + if (sameText && start in 0..rendered.length && end in 0..rendered.length) { + (view.text as? Spannable)?.let { Selection.setSelection(it, start, end) } + } +} + +internal fun agentBrowserIntent(link: String): Intent? { + val uri = Uri.parse(link) + if (uri.scheme?.lowercase() !in listOf("http", "https") || uri.host.isNullOrBlank()) return null + return Intent(Intent.ACTION_VIEW, uri).apply { + addCategory(Intent.CATEGORY_BROWSABLE) + addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + selector = Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_APP_BROWSER) + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/AgentPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/AgentPage.kt index 9956d0469a..ed036a4933 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/AgentPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/AgentPage.kt @@ -1,24 +1,38 @@ package com.droiddeck.launcher.ui +import android.app.Activity +import android.content.ContextWrapper +import android.view.KeyEvent +import android.view.WindowManager import androidx.activity.compose.LocalActivityResultRegistryOwner import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts +import androidx.compose.animation.expandVertically +import androidx.compose.animation.fadeIn +import androidx.compose.animation.fadeOut +import androidx.compose.animation.shrinkVertically +import androidx.compose.foundation.Canvas import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.clickable +import androidx.compose.foundation.gestures.awaitEachGesture +import androidx.compose.foundation.gestures.awaitFirstDown import androidx.compose.foundation.horizontalScroll import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.WindowInsets import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.ime +import androidx.compose.foundation.layout.imePadding import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.widthIn import androidx.compose.foundation.lazy.LazyColumn -import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.lazy.LazyListState import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.CircleShape @@ -28,12 +42,16 @@ import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.outlined.Send import androidx.compose.material.icons.outlined.Add +import androidx.compose.material.icons.outlined.ArrowDownward import androidx.compose.material.icons.outlined.AttachFile import androidx.compose.material.icons.outlined.AutoAwesome +import androidx.compose.material.icons.outlined.Build import androidx.compose.material.icons.outlined.Close import androidx.compose.material.icons.outlined.ExpandMore import androidx.compose.material.icons.outlined.History import androidx.compose.material.icons.outlined.Memory +import androidx.compose.material.icons.outlined.MoreHoriz +import androidx.compose.material.icons.outlined.Pets import androidx.compose.material.icons.outlined.Settings import androidx.compose.material.icons.outlined.Stop import androidx.compose.material3.CircularProgressIndicator @@ -42,21 +60,41 @@ import androidx.compose.material3.LinearProgressIndicator 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.MutableState +import androidx.compose.runtime.Stable import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue +import androidx.compose.runtime.snapshotFlow import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip +import androidx.compose.ui.draw.clipToBounds +import androidx.compose.ui.focus.FocusRequester +import androidx.compose.ui.focus.focusRequester import androidx.compose.ui.focus.onFocusChanged +import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.SolidColor +import androidx.compose.ui.graphics.StrokeCap +import androidx.compose.ui.graphics.drawscope.Stroke import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.input.key.onPreviewKeyEvent +import androidx.compose.ui.input.nestedscroll.NestedScrollConnection +import androidx.compose.ui.input.nestedscroll.NestedScrollSource +import androidx.compose.ui.input.nestedscroll.nestedScroll +import androidx.compose.ui.input.pointer.PointerEventPass +import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.platform.LocalFocusManager +import androidx.compose.ui.platform.LocalView import androidx.compose.ui.platform.testTag import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.TextStyle @@ -65,25 +103,52 @@ import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.style.TextAlign 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.window.DialogWindowProvider import com.droiddeck.launcher.R import com.droiddeck.launcher.agent.AgentAttachments import com.droiddeck.launcher.agent.AgentHost import com.droiddeck.launcher.agent.AgentHost.Entry import com.droiddeck.launcher.agent.AgentSetup +import kotlinx.coroutines.launch -internal enum class AgentPanel { NONE, MODEL, HISTORY, PROCESSES } +internal enum class AgentPanel { NONE, MODEL, USAGE, HISTORY, PROCESSES } /** Slash commands the app handles itself; others go to the CLI, which has its own. */ private val LOCAL_COMMANDS = listOf("/new", "/model", "/plan", "/history", "/processes", "/stop") private val CLI_COMMANDS = listOf("/compact", "/cost", "/review", "/init") +private const val COMPOSER_SLIDE_MS = 350L +/** + * The chat with the composer at the bottom. The composer is the full editor only while it is + * being typed in; reading shrinks it to one line, and scrolling back through older messages + * hides it behind a small pill. [startTyping] opens an empty conversation ready to type. + */ @Composable -internal fun AgentPage(modifier: Modifier, inputModifier: Modifier = Modifier, visible: Boolean = true) { +internal fun AgentPage( + modifier: Modifier, inputModifier: Modifier = Modifier, visible: Boolean = true, startTyping: Boolean = true, hidesPet: Boolean = true, +) { val context = LocalContext.current + val view = LocalView.current + DisposableEffect(view, visible) { + val window = (view.parent as? DialogWindowProvider)?.window + ?: generateSequence(view.context) { (it as? ContextWrapper)?.baseContext } + .filterIsInstance().firstOrNull()?.window + val previousMode = window?.attributes?.softInputMode + if (visible) window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING) + onDispose { + if (visible && previousMode != null) window?.setSoftInputMode(previousMode) + } + } remember { AgentHost.refresh(context) } LaunchedEffect(AgentHost.unseen, visible) { if (visible) AgentHost.seen() } + DisposableEffect(visible, hidesPet) { + val counts = visible && hidesPet + if (counts) AgentPet.agentOnScreen++ + onDispose { if (counts) AgentPet.agentOnScreen-- } + } remember { AgentSetup.check(context) } var setup by rememberSaveable { mutableStateOf(false) } val draft = rememberSaveable { mutableStateOf("") } @@ -92,56 +157,115 @@ internal fun AgentPage(modifier: Modifier, inputModifier: Modifier = Modifier, v return } var panel by rememberSaveable { mutableStateOf(AgentPanel.NONE) } - Column(modifier.fillMaxSize()) { - AgentHeader(panel, { panel = if (panel == it) AgentPanel.NONE else it }, onSetup = { setup = true }) + val composer = remember { ComposerState(startTyping && AgentHost.entries.isEmpty()) } + val focusManager = LocalFocusManager.current + val togglePanel: (AgentPanel) -> Unit = { panel = if (panel == it) AgentPanel.NONE else it } + // The keyboard leaves too little height for a panel and the editor together, so typing closes the panel. + val keyboardOpen = WindowInsets.ime.getBottom(LocalDensity.current) > 0 + LaunchedEffect(keyboardOpen) { if (keyboardOpen && (panel == AgentPanel.MODEL || panel == AgentPanel.USAGE)) panel = AgentPanel.NONE } + Column( + modifier.fillMaxSize().imePadding().onPreviewKeyEvent { e -> + val k = e.nativeKeyEvent + if (k.keyCode != KeyEvent.KEYCODE_BUTTON_Y || composer.typing) return@onPreviewKeyEvent false + if (k.action == KeyEvent.ACTION_UP) composer.open() + true + }, + ) { when (panel) { - AgentPanel.HISTORY -> AgentHistory(Modifier.weight(1f)) { panel = AgentPanel.NONE } - AgentPanel.PROCESSES -> AgentProcessList(Modifier.weight(1f)) + AgentPanel.HISTORY -> { + AgentPanelBar(stringResource(R.string.agent_history)) { panel = AgentPanel.NONE } + AgentHistory(Modifier.weight(1f)) { panel = AgentPanel.NONE } + } + AgentPanel.PROCESSES -> { + AgentPanelBar(stringResource(R.string.agent_processes)) { panel = AgentPanel.NONE } + AgentProcessList(Modifier.weight(1f)) + } else -> { - if (panel == AgentPanel.MODEL) AgentModelPicker() - AgentConversation(Modifier.weight(1f)) - AgentStatus() - AgentComposer(draft, inputModifier) { panel = it } + val list = rememberLazyListState() + val scope = rememberCoroutineScope() + // Only dragging back through older messages hides the composer; showing it again shrinks the list, which must not hide it once more. + var readingBack by remember { mutableStateOf(false) } + LaunchedEffect(list) { snapshotFlow { list.canScrollForward }.collect { if (!it) readingBack = false } } + val dragBack = remember { + object : NestedScrollConnection { + override fun onPreScroll(available: Offset, source: NestedScrollSource): Offset { + if (source == NestedScrollSource.Drag && available.y > 1f && list.canScrollBackward) readingBack = true + return Offset.Zero + } + } + } + val toLatest: () -> Unit = { + readingBack = false + scope.launch { list.scrollToItem(maxOf(0, list.layoutInfo.totalItemsCount - 1), Int.MAX_VALUE / 2) } + } + val hidden = !composer.typing && readingBack && AgentHost.entries.isNotEmpty() + var wasHidden by remember { mutableStateOf(false) } + LaunchedEffect(hidden) { + if (hidden) wasHidden = true + else if (wasHidden) { + wasHidden = false + // The composer takes its height back as it slides in; the latest message stays above it. + kotlinx.coroutines.delay(COMPOSER_SLIDE_MS) + list.scrollToItem(maxOf(0, list.layoutInfo.totalItemsCount - 1), Int.MAX_VALUE / 2) + } + } + Box(Modifier.weight(1f).fillMaxWidth().clipToBounds().nestedScroll(dragBack)) { + AgentConversation( + Modifier.fillMaxSize().pointerInput(Unit) { + awaitEachGesture { + awaitFirstDown(requireUnconsumed = false, pass = PointerEventPass.Initial) + if (panel == AgentPanel.MODEL || panel == AgentPanel.USAGE) panel = AgentPanel.NONE + if (composer.typing) focusManager.clearFocus() + } + }, + list, onRevise = { composer.open() }, + ) + androidx.compose.animation.AnimatedVisibility( + hidden, enter = fadeIn(), exit = fadeOut(), modifier = Modifier.align(Alignment.BottomCenter).padding(bottom = 8.dp), + ) { + AgentJumpPill(toLatest) + } + } + androidx.compose.animation.AnimatedVisibility(!hidden, enter = expandVertically() + fadeIn(), exit = shrinkVertically() + fadeOut()) { + AgentComposer(composer, draft, inputModifier, panel, togglePanel) { setup = true } + } } } } } -@Composable -private fun AgentHeader(panel: AgentPanel, onPanel: (AgentPanel) -> Unit, onSetup: () -> Unit) { - val context = LocalContext.current - val colors = MaterialTheme.colorScheme - val pal = LocalPalette.current - val working = AgentHost.state == AgentHost.State.WORKING - Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().padding(bottom = 8.dp)) { - Column(Modifier.weight(1f)) { - Text(stringResource(R.string.rail_agent), fontSize = 22.sp, fontWeight = FontWeight.Bold, color = colors.onBackground) - val model = AgentHost.models(context).firstOrNull { it.id == AgentHost.model }?.label ?: AgentHost.model ?: stringResource(R.string.agent_model_default) - Row( - verticalAlignment = Alignment.CenterVertically, - modifier = Modifier.clip(Shape12).clickable { onPanel(AgentPanel.MODEL) }.padding(vertical = 2.dp).testTag("agent-model"), - ) { - val parts = listOfNotNull(AgentHost.harness.name, model, stringResource(R.string.agent_plan_short).takeIf { AgentHost.plan && AgentHost.harness.plans }) - Text(parts.joinToString(" ยท "), fontSize = 13.sp, color = if (panel == AgentPanel.MODEL) pal.primary else pal.onSurfaceVariant) - Icon(Icons.Outlined.ExpandMore, null, tint = pal.onSurfaceVariant, modifier = Modifier.size(16.dp)) - } - } - HeaderAction(Icons.Outlined.History, stringResource(R.string.agent_history), selected = panel == AgentPanel.HISTORY, tag = "agent-history") { onPanel(AgentPanel.HISTORY) } - HeaderAction(Icons.Outlined.Memory, stringResource(R.string.agent_processes), selected = panel == AgentPanel.PROCESSES, tag = "agent-processes") { onPanel(AgentPanel.PROCESSES) } - HeaderAction(Icons.Outlined.Add, stringResource(R.string.agent_new), enabled = !working && AgentHost.entries.isNotEmpty(), tag = "agent-new") { - AgentHost.forget(context) - if (panel != AgentPanel.NONE) onPanel(panel) - } - HeaderAction(Icons.Outlined.Settings, stringResource(R.string.agent_setup_title), enabled = !working, tag = "agent-settings", onClick = onSetup) +/** Whether the composer is the full editor; [open] also puts the cursor in it. */ +@Stable +private class ComposerState(typing: Boolean) { + var typing by mutableStateOf(typing) + var focusRequests by mutableIntStateOf(0) + private set + /** Opened and waiting for the text field to take focus; focus passes through nothing on the way. */ + var opening = false + + fun open() { + typing = true + opening = true + focusRequests++ } } @Composable -internal fun HeaderAction(icon: ImageVector, label: String, enabled: Boolean = true, selected: Boolean = false, tag: String? = null, onClick: () -> Unit) { +private fun AgentPanelBar(title: String, onClose: () -> Unit) { + Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().padding(bottom = 6.dp)) { + Text(title, fontSize = 17.sp, fontWeight = FontWeight.SemiBold, color = MaterialTheme.colorScheme.onBackground, modifier = Modifier.weight(1f)) + HeaderAction(Icons.Outlined.Close, stringResource(R.string.agent_close), size = 36.dp, tag = "agent-panel-close", onClick = onClose) + } +} + +@Composable +internal fun HeaderAction( + icon: ImageVector, label: String, enabled: Boolean = true, selected: Boolean = false, tag: String? = null, size: Dp = 44.dp, onClick: () -> Unit, +) { val pal = LocalPalette.current Box( contentAlignment = Alignment.Center, - modifier = Modifier.padding(start = 8.dp).size(44.dp).clip(Shape12) + modifier = Modifier.padding(start = if (size < 44.dp) 4.dp else 8.dp).size(size).clip(Shape12) .background(if (selected) pal.primary.copy(alpha = 0.2f) else pal.surfaceVariant) .clickable(enabled = enabled, onClick = onClick) .then(if (tag != null) Modifier.testTag(tag) else Modifier), @@ -150,18 +274,21 @@ internal fun HeaderAction(icon: ImageVector, label: String, enabled: Boolean = t selected -> pal.primary enabled -> pal.onBackground else -> pal.onSurfaceVariant.copy(alpha = 0.5f) - }, modifier = Modifier.size(22.dp)) + }, modifier = Modifier.size(if (size < 44.dp) 19.dp else 22.dp)) } } @Composable -private fun AgentConversation(modifier: Modifier) { +private fun AgentConversation(modifier: Modifier, list: LazyListState, onRevise: () -> Unit) { val pal = LocalPalette.current - val list = rememberLazyListState() val working = AgentHost.state == AgentHost.State.WORKING val atBottom by remember { derivedStateOf { !list.canScrollForward } } val items = AgentHost.entries.size + (if (working) 1 else 0) - LaunchedEffect(items) { if (items > 0) list.animateScrollToItem(items - 1) } + LaunchedEffect(items) { + if (items == 0) return@LaunchedEffect + list.animateScrollToItem(items - 1) + list.scrollToItem(items - 1, Int.MAX_VALUE / 2) + } LaunchedEffect(AgentHost.live.length / 80, AgentHost.liveThinking.length / 80) { if (atBottom && items > 0) list.scrollToItem(items - 1, Int.MAX_VALUE / 2) } @@ -177,12 +304,31 @@ private fun AgentConversation(modifier: Modifier) { LazyColumn(modifier.fillMaxWidth(), state = list, verticalArrangement = Arrangement.spacedBy(10.dp)) { items(AgentHost.entries.size) { i -> val entry = AgentHost.entries[i] - AgentEntry(entry, running = working && i > start && entry is Entry.Used && entry.output == null, last = !working && i == AgentHost.entries.lastIndex) + AgentEntry( + entry, running = working && i > start && entry is Entry.Used && entry.output == null, last = !working && i == AgentHost.entries.lastIndex, + changes = if (entry is Entry.Finished) turnChanges(AgentHost.entries, i) else null, onRevise = onRevise, + ) } if (working) item { AgentLive() } } } +/** Where the composer was, while it is hidden for reading back: what the agent is doing, and the way to the latest message. */ +@Composable +private fun AgentJumpPill(onClick: () -> Unit) { + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + Row( + verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp), + modifier = Modifier.clip(CircleShape).background(colors.surface).border(1.dp, pal.line, CircleShape) + .clickable(onClick = onClick).padding(horizontal = 14.dp, vertical = 8.dp).testTag("agent-latest"), + ) { + if (AgentHost.state == AgentHost.State.WORKING) CircularProgressIndicator(Modifier.size(13.dp), strokeWidth = 2.dp, color = pal.primary) + Text(stringResource(if (AgentHost.state == AgentHost.State.WORKING) R.string.agent_working_short else R.string.agent_latest), fontSize = 13.sp, color = pal.onSurfaceVariant) + Icon(Icons.Outlined.ArrowDownward, null, tint = pal.onSurfaceVariant, modifier = Modifier.size(16.dp)) + } +} + /** The reply being written, and what the agent is doing right now. */ @Composable private fun AgentLive() { @@ -211,65 +357,41 @@ internal fun clock(seconds: Long): String { } } -/** Above the composer: a Lab build's progress, the todo item in progress, and queued messages. */ @Composable -private fun AgentStatus() { +private fun AgentLabCard() { val context = LocalContext.current val colors = MaterialTheme.colorScheme val pal = LocalPalette.current - val lab = AgentHost.lab - if (lab != null) { - var armed by remember(lab.pid) { mutableStateOf(false) } - Column( - Modifier.fillMaxWidth().padding(top = 10.dp).clip(Shape14).background(colors.surface).border(1.dp, if (lab.failed) AttentionAmber else pal.line, Shape14) - .padding(horizontal = 14.dp, vertical = 10.dp).testTag("agent-lab"), - ) { - Row(verticalAlignment = Alignment.CenterVertically) { - Column(Modifier.weight(1f)) { - Text( - stringResource(if (lab.prepare) R.string.agent_lab_preparing else R.string.agent_lab_building) + " ยท " + labStage(lab), - fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = if (lab.failed) AttentionAmber else colors.onBackground, - ) - val facts = buildList { - if (lab.running && lab.total > 0) add("${lab.done}/${lab.total}") - add(clock(lab.elapsedSeconds.toLong())) - if (lab.running && lab.etaSeconds >= 0) add(stringResource(R.string.agent_lab_left, clock(lab.etaSeconds.toLong()))) - } - Text(facts.joinToString(" ยท "), fontSize = 12.5.sp, color = pal.onSurfaceVariant) - } - if (lab.running) SecondaryButton(stringResource(if (armed) R.string.agent_lab_cancel_confirm else R.string.agent_lab_cancel), compact = true) { - if (armed) AgentHost.cancelLabBuild(context) else armed = true - } - } - if (lab.running) { - LinearProgressIndicator( - progress = { lab.permille / 1000f }, color = pal.primary, trackColor = pal.surfaceVariant, - modifier = Modifier.fillMaxWidth().padding(top = 8.dp).height(6.dp).clip(CircleShape), + val lab = AgentHost.lab ?: return + var armed by remember(lab.pid) { mutableStateOf(false) } + Column( + Modifier.fillMaxWidth().padding(top = 8.dp).clip(Shape14).background(colors.surface).border(1.dp, if (lab.failed) AttentionAmber else pal.line, Shape14) + .padding(horizontal = 14.dp, vertical = 10.dp).testTag("agent-lab"), + ) { + Row(verticalAlignment = Alignment.CenterVertically) { + Column(Modifier.weight(1f)) { + Text( + stringResource(if (lab.prepare) R.string.agent_lab_preparing else R.string.agent_lab_building) + " ยท " + labStage(lab), + fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = if (lab.failed) AttentionAmber else colors.onBackground, ) - if (lab.task.isNotEmpty()) Text(lab.task, fontSize = 12.sp, fontFamily = FontFamily.Monospace, color = pal.onSurfaceVariant, - maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.padding(top = 4.dp)) + val facts = buildList { + if (lab.running && lab.total > 0) add("${lab.done}/${lab.total}") + add(clock(lab.elapsedSeconds.toLong())) + if (lab.running && lab.etaSeconds >= 0) add(stringResource(R.string.agent_lab_left, clock(lab.etaSeconds.toLong()))) + } + Text(facts.joinToString(" ยท "), fontSize = 12.5.sp, color = pal.onSurfaceVariant) + } + if (lab.running) SecondaryButton(stringResource(if (armed) R.string.agent_lab_cancel_confirm else R.string.agent_lab_cancel), compact = true) { + if (armed) AgentHost.cancelLabBuild(context) else armed = true } } - } - val todos = AgentHost.todos()?.lines()?.filter { it.isNotBlank() } - if (AgentHost.state == AgentHost.State.WORKING && !todos.isNullOrEmpty()) { - val doing = todos.firstOrNull { it.startsWith("[~]") } ?: todos.firstOrNull { it.startsWith("[ ]") } - val done = todos.count { it.startsWith("[x]") } - if (doing != null) Text( - "${doing.drop(4)} ยท $done/${todos.size}", fontSize = 13.sp, color = pal.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis, - modifier = Modifier.padding(top = 8.dp, start = 4.dp), - ) - } - for (queued in AgentHost.queue) { - Row( - verticalAlignment = Alignment.CenterVertically, - modifier = Modifier.padding(top = 8.dp).fillMaxWidth().clip(Shape12).background(pal.surfaceVariant).padding(start = 12.dp), - ) { - Text(stringResource(R.string.agent_queued, queued.text), fontSize = 13.sp, color = pal.onSurfaceVariant, maxLines = 1, - overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f)) - Box(contentAlignment = Alignment.Center, modifier = Modifier.size(40.dp).clickable { AgentHost.unqueue(queued) }) { - Icon(Icons.Outlined.Close, stringResource(R.string.agent_unqueue), tint = pal.onSurfaceVariant, modifier = Modifier.size(18.dp)) - } + if (lab.running) { + LinearProgressIndicator( + progress = { lab.permille / 1000f }, color = pal.primary, trackColor = pal.surfaceVariant, + modifier = Modifier.fillMaxWidth().padding(top = 8.dp).height(6.dp).clip(CircleShape), + ) + if (lab.task.isNotEmpty()) Text(lab.task, fontSize = 12.sp, fontFamily = FontFamily.Monospace, color = pal.onSurfaceVariant, + maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.padding(top = 4.dp)) } } } @@ -284,13 +406,99 @@ private fun labStage(lab: com.droiddeck.launcher.agent.LabProgress) = when (lab. else -> stringResource(R.string.agent_lab_stage_starting) } +private fun hasActivity() = AgentHost.lab != null || AgentHost.queue.isNotEmpty() || currentTodo() != null + +/** The todo item in progress and how many are done, while the agent works through a list. */ +private fun currentTodo(): String? { + if (AgentHost.state != AgentHost.State.WORKING) return null + val todos = AgentHost.todos()?.lines()?.filter { it.isNotBlank() }.orEmpty() + val doing = todos.firstOrNull { it.startsWith("[~]") } ?: todos.firstOrNull { it.startsWith("[ ]") } ?: return null + return "${todos.count { it.startsWith("[x]") }}/${todos.size} ยท ${doing.drop(4)}" +} + +/** A Lab build, the todo item in progress and queued messages, one chip each. */ @Composable -private fun AgentComposer(draftState: MutableState, inputModifier: Modifier, onPanel: (AgentPanel) -> Unit) { +private fun AgentActivity(labOpen: Boolean, onLab: () -> Unit) { val context = LocalContext.current - val colors = MaterialTheme.colorScheme val pal = LocalPalette.current + AgentHost.lab?.let { lab -> + AgentChip(selected = labOpen, warn = lab.failed, tag = "agent-lab-chip", onClick = onLab) { + Icon(Icons.Outlined.Build, null, tint = if (lab.failed) AttentionAmber else pal.onSurfaceVariant, modifier = Modifier.size(14.dp)) + Text(labStage(lab), fontSize = 12.5.sp, color = if (lab.failed) AttentionAmber else pal.onSurfaceVariant, maxLines = 1, + overflow = TextOverflow.Ellipsis, modifier = Modifier.widthIn(max = 160.dp)) + } + } + currentTodo()?.let { todo -> + AgentChip { + Text(todo, fontSize = 12.5.sp, color = pal.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.widthIn(max = 220.dp)) + } + } + for (queued in AgentHost.queue) AgentChip(warn = true) { + Text(stringResource(R.string.agent_queued, queued.text), fontSize = 12.5.sp, color = AttentionAmber, maxLines = 1, + overflow = TextOverflow.Ellipsis, modifier = Modifier.widthIn(max = 180.dp)) + Text( + stringResource(R.string.agent_send_now), fontSize = 12.5.sp, fontWeight = FontWeight.SemiBold, color = pal.onPrimary, + modifier = Modifier.clip(Shape12).background(pal.primary).clickable { AgentHost.sendNow(context, queued) } + .padding(horizontal = 8.dp, vertical = 3.dp).testTag("agent-send-now"), + ) + Icon(Icons.Outlined.Close, stringResource(R.string.agent_unqueue), tint = pal.onSurfaceVariant, + modifier = Modifier.size(22.dp).clip(CircleShape).clickable { AgentHost.unqueue(queued) }.padding(3.dp)) + } +} + +@Composable +private fun AgentChip(selected: Boolean = false, warn: Boolean = false, tag: String? = null, onClick: (() -> Unit)? = null, content: @Composable () -> Unit) { + val pal = LocalPalette.current + Row( + verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp), + modifier = Modifier.height(30.dp).clip(Shape12) + .background(if (warn) AttentionAmber.copy(alpha = 0.14f) else if (selected) pal.primary.copy(alpha = 0.2f) else pal.surfaceVariant) + .then(if (onClick != null) Modifier.clickable(onClick = onClick) else Modifier) + .then(if (tag != null) Modifier.testTag(tag) else Modifier) + .padding(horizontal = 9.dp), + ) { content() } +} + +/** How full the context is, or failing that the plan limit nearest its end; amber when little is left. */ +@Composable +private fun ContextRing(tag: String, onClick: () -> Unit) { + val pal = LocalPalette.current + val percent = usagePercent() ?: return + val warn = percent >= 80 + val tint = if (warn) AttentionAmber else pal.primary + Row( + verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(5.dp), + modifier = Modifier.height(30.dp).clip(Shape12).clickable(onClick = onClick).padding(horizontal = 6.dp).testTag(tag), + ) { + val track = pal.line + Canvas(Modifier.size(16.dp)) { + val stroke = Stroke(width = 2.5.dp.toPx(), cap = StrokeCap.Round) + drawArc(track, 0f, 360f, false, style = stroke) + drawArc(tint, -90f, 360f * percent / 100f, false, style = stroke) + } + Text("$percent%", fontSize = 12.5.sp, color = if (warn) AttentionAmber else pal.onSurfaceVariant) + } +} + +/** The context's fill, unless a plan limit is nearly reached: that is the wall the user meets first. */ +internal fun usagePercent(): Int? { + val limit = AgentHost.limits.maxOfOrNull { liveUsed(it) } + val context = if (AgentHost.window > 0 && AgentHost.context > 0) (AgentHost.context * 100 / AgentHost.window).toInt().coerceIn(0, 100) else null + return if (limit != null && (limit >= 90 || context == null)) maxOf(limit, context ?: 0) else context +} + +/** A limit whose window has passed since it was reported is back to nothing used. */ +internal fun liveUsed(limit: AgentHost.Limit) = if (limit.resetsAt > 0 && limit.resetsAt * 1000 < System.currentTimeMillis()) 0 else limit.usedPercent + +@Composable +private fun AgentComposer( + composer: ComposerState, draftState: MutableState, inputModifier: Modifier, panel: AgentPanel, onPanel: (AgentPanel) -> Unit, onSetup: () -> Unit, +) { + val context = LocalContext.current var draft by draftState - val working = AgentHost.state == AgentHost.State.WORKING + var labOpen by rememberSaveable { mutableStateOf(false) } + if (AgentHost.lab == null) labOpen = false + var hadFocus by remember { mutableStateOf(false) } val send = send@{ val text = draft.trim() when (text.substringBefore(' ')) { @@ -308,11 +516,84 @@ private fun AgentComposer(draftState: MutableState, inputModifier: Modif } draft = "" } + val keyboardOpen = WindowInsets.ime.getBottom(LocalDensity.current) > 0 + // Leaving the composer for the conversation, by touch or D-pad, is reading. + Column( + Modifier.fillMaxWidth().padding(bottom = if (keyboardOpen) 4.dp else 8.dp).onFocusChanged { + if (it.hasFocus) hadFocus = true + else if (hadFocus) { + hadFocus = false + if (composer.typing && !composer.opening) composer.typing = false + } + }, + ) { + if (labOpen) AgentLabCard() + when (panel) { + AgentPanel.MODEL -> Box(Modifier.padding(top = 8.dp)) { AgentModelPicker() } + AgentPanel.USAGE -> Box(Modifier.padding(top = 8.dp)) { AgentUsage() } + else -> Unit + } + if (composer.typing) { + if (hasActivity()) Row( + horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically, + modifier = Modifier.padding(top = 8.dp).fillMaxWidth().horizontalScroll(rememberScrollState()), + ) { AgentActivity(labOpen) { labOpen = !labOpen } } + AgentEditor(composer, draftState, inputModifier, panel, onPanel, onSetup, send) + } else AgentReadingBar(composer, draft, inputModifier, labOpen, onLab = { labOpen = !labOpen }) { onPanel(AgentPanel.USAGE) } + } +} + +/** The composer while reading: one line holding what is going on, opened by a press or by Y. */ +@Composable +private fun AgentReadingBar( + composer: ComposerState, draft: String, inputModifier: Modifier, labOpen: Boolean, onLab: () -> Unit, onUsage: () -> Unit, +) { + val context = LocalContext.current + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + val working = AgentHost.state == AgentHost.State.WORKING + var focused by remember { mutableStateOf(false) } + Row( + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier.fillMaxWidth().padding(top = 8.dp).height(44.dp).clip(Shape16).background(colors.surface) + .border(if (focused) 2.dp else 1.dp, if (focused) pal.primary else pal.line, Shape16) + .then(inputModifier).onFocusChanged { focused = it.isFocused }.clickable { composer.open() }.testTag("agent-composer-bar") + .padding(start = 14.dp, end = 4.dp), + ) { + Text( + draft.ifBlank { stringResource(if (working) R.string.agent_hint_working else R.string.agent_message) }, fontSize = 15.sp, + color = if (draft.isBlank()) pal.onSurfaceVariant else colors.onSurface, maxLines = 1, overflow = TextOverflow.Ellipsis, + modifier = Modifier.weight(1f, fill = !hasActivity()).widthIn(min = 72.dp), + ) + if (hasActivity()) Row( + horizontalArrangement = Arrangement.spacedBy(6.dp), verticalAlignment = Alignment.CenterVertically, + modifier = Modifier.weight(1f).padding(start = 8.dp).horizontalScroll(rememberScrollState()), + ) { AgentActivity(labOpen, onLab) } + ContextRing("agent-usage-bar", onUsage) + if (working) Box( + contentAlignment = Alignment.Center, + modifier = Modifier.padding(start = 4.dp).size(36.dp).clip(CircleShape).background(pal.error.copy(alpha = 0.22f)) + .clickable { AgentHost.stop(context) }.testTag("agent-stop"), + ) { Icon(Icons.Outlined.Stop, stringResource(R.string.agent_stop), tint = colors.error, modifier = Modifier.size(20.dp)) } + } +} + +/** The full editor: model and usage on top, the text with attach, stop and send under them. */ +@Composable +private fun AgentEditor( + composer: ComposerState, draftState: MutableState, inputModifier: Modifier, panel: AgentPanel, onPanel: (AgentPanel) -> Unit, + onSetup: () -> Unit, send: () -> Unit, +) { + val context = LocalContext.current + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + var draft by draftState + val working = AgentHost.state == AgentHost.State.WORKING if (draft.startsWith("/") && !draft.contains(' ')) { val matches = (LOCAL_COMMANDS + CLI_COMMANDS).filter { it.startsWith(draft) && it != draft } if (matches.isNotEmpty()) Row( horizontalArrangement = Arrangement.spacedBy(8.dp), - modifier = Modifier.padding(top = 10.dp).fillMaxWidth().horizontalScroll(rememberScrollState()), + modifier = Modifier.padding(top = 8.dp).fillMaxWidth().horizontalScroll(rememberScrollState()), ) { for (command in matches) Text( command, fontSize = 13.sp, fontFamily = FontFamily.Monospace, color = pal.primary, @@ -322,40 +603,80 @@ private fun AgentComposer(draftState: MutableState, inputModifier: Modif } if (AgentAttachments.pending.isNotEmpty()) Row( horizontalArrangement = Arrangement.spacedBy(8.dp), - modifier = Modifier.padding(top = 10.dp).fillMaxWidth().horizontalScroll(rememberScrollState()), + modifier = Modifier.padding(top = 8.dp).fillMaxWidth().horizontalScroll(rememberScrollState()), ) { for (path in AgentAttachments.pending.toList()) AttachmentChip(path) { AgentAttachments.pending.remove(path) } } var focused by remember { mutableStateOf(false) } - Row( - verticalAlignment = Alignment.Bottom, - modifier = Modifier.fillMaxWidth().padding(top = 10.dp, bottom = 16.dp).clip(Shape16).background(colors.surface) - .border(1.dp, if (focused) pal.primary else pal.line, Shape16).padding(start = 6.dp, end = 6.dp, top = 6.dp, bottom = 6.dp), + var menu by rememberSaveable { mutableStateOf(false) } + val field = remember { FocusRequester() } + LaunchedEffect(composer.focusRequests) { if (composer.focusRequests > 0) runCatching { field.requestFocus() } } + Column( + Modifier.fillMaxWidth().padding(top = 8.dp).clip(Shape16).background(colors.surface) + .border(1.dp, if (focused) pal.primary else pal.line, Shape16).padding(6.dp), ) { - if (LocalActivityResultRegistryOwner.current != null) AttachButton() - Box(Modifier.weight(1f).padding(start = 8.dp, top = 11.dp, bottom = 11.dp)) { - if (draft.isEmpty()) Text( - stringResource(if (working) R.string.agent_hint_working else R.string.agent_hint), fontSize = 16.sp, - color = pal.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis, - ) - BasicTextField( - draft, { draft = it }, - Modifier.fillMaxWidth().onFocusChanged { focused = it.isFocused }.testTag("agent-input").then(inputModifier), - textStyle = TextStyle(fontSize = 16.sp, color = colors.onSurface), - cursorBrush = SolidColor(pal.primary), - keyboardOptions = KeyboardOptions(imeAction = ImeAction.Send), - keyboardActions = KeyboardActions(onSend = { send() }), - maxLines = 6, - ) + Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().height(36.dp)) { + val model = AgentHost.models(context).firstOrNull { it.id == AgentHost.model }?.label ?: AgentHost.model ?: stringResource(R.string.agent_model_default) + Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.weight(1f)) { + Row( + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier.weight(1f, fill = false).height(30.dp).clip(Shape12).clickable { onPanel(AgentPanel.MODEL) } + .padding(horizontal = 8.dp).testTag("agent-model"), + ) { + val parts = listOfNotNull(AgentHost.harness.name, model, AgentHost.effort, stringResource(R.string.agent_plan_short).takeIf { AgentHost.plan && AgentHost.harness.plans }) + Text(parts.joinToString(" ยท "), fontSize = 13.sp, color = if (panel == AgentPanel.MODEL) pal.primary else pal.onSurfaceVariant, + maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f, fill = false)) + Icon(Icons.Outlined.ExpandMore, null, tint = pal.onSurfaceVariant, modifier = Modifier.size(16.dp)) + } + ContextRing("agent-usage", onClick = { onPanel(AgentPanel.USAGE) }) + } + if (menu) { + HeaderAction(Icons.Outlined.History, stringResource(R.string.agent_history), size = 32.dp, tag = "agent-history") { menu = false; onPanel(AgentPanel.HISTORY) } + HeaderAction(Icons.Outlined.Memory, stringResource(R.string.agent_processes), size = 32.dp, tag = "agent-processes") { menu = false; onPanel(AgentPanel.PROCESSES) } + HeaderAction(Icons.Outlined.Add, stringResource(R.string.agent_new), enabled = !working && AgentHost.entries.isNotEmpty(), size = 32.dp, tag = "agent-new") { + menu = false + AgentHost.forget(context) + } + HeaderAction(Icons.Outlined.Pets, stringResource(R.string.setup_agent_pet), selected = AgentPet.enabled, size = 32.dp, tag = "agent-pet-toggle") { + AgentPet.set(context, !AgentPet.enabled) + } + HeaderAction(Icons.Outlined.Settings, stringResource(R.string.agent_setup_title), enabled = !working, size = 32.dp, tag = "agent-settings") { + menu = false + onSetup() + } + } + HeaderAction(if (menu) Icons.Outlined.Close else Icons.Outlined.MoreHoriz, stringResource(R.string.agent_more), size = 32.dp, tag = "agent-menu") { menu = !menu } } - if (working) RoundButton(Icons.Outlined.Stop, stringResource(R.string.agent_stop), pal.error.copy(alpha = 0.22f), colors.error, "agent-stop") { - AgentHost.stop(context) + Row(verticalAlignment = Alignment.Bottom) { + if (LocalActivityResultRegistryOwner.current != null) AttachButton() + Box(Modifier.weight(1f).padding(start = 8.dp, top = 10.dp, bottom = 10.dp)) { + if (draft.isEmpty()) Text( + stringResource(if (working) R.string.agent_hint_working else R.string.agent_hint), fontSize = 16.sp, + color = pal.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis, + ) + BasicTextField( + draft, { draft = it }, + Modifier.fillMaxWidth().focusRequester(field).onFocusChanged { + focused = it.isFocused + if (it.isFocused) composer.opening = false + }.testTag("agent-input").then(inputModifier), + textStyle = TextStyle(fontSize = 16.sp, color = colors.onSurface), + cursorBrush = SolidColor(pal.primary), + keyboardOptions = KeyboardOptions(imeAction = ImeAction.Send), + keyboardActions = KeyboardActions(onSend = { send() }), + minLines = 1, + maxLines = 8, + ) + } + if (working) RoundButton(Icons.Outlined.Stop, stringResource(R.string.agent_stop), pal.error.copy(alpha = 0.22f), colors.error, "agent-stop") { + AgentHost.stop(context) + } + val canSend = draft.isNotBlank() || AgentAttachments.pending.isNotEmpty() + RoundButton( + Icons.AutoMirrored.Outlined.Send, stringResource(if (working) R.string.agent_queue else R.string.agent_send), + if (canSend) pal.primary else pal.surfaceVariant, if (canSend) pal.onPrimary else pal.onSurfaceVariant, "agent-send", enabled = canSend, + ) { send() } } - val canSend = draft.isNotBlank() || AgentAttachments.pending.isNotEmpty() - RoundButton( - Icons.AutoMirrored.Outlined.Send, stringResource(if (working) R.string.agent_queue else R.string.agent_send), - if (canSend) pal.primary else pal.surfaceVariant, if (canSend) pal.onPrimary else pal.onSurfaceVariant, "agent-send", enabled = canSend, - ) { send() } } } @@ -385,9 +706,9 @@ private fun RoundButton( ) { Box( contentAlignment = Alignment.Center, - modifier = Modifier.padding(start = 6.dp).size(46.dp).clip(CircleShape).background(background) + modifier = Modifier.padding(start = 6.dp).size(42.dp).clip(CircleShape).background(background) .clickable(enabled = enabled, onClick = onClick).testTag(tag), ) { - Icon(icon, label, tint = tint, modifier = Modifier.size(22.dp)) + Icon(icon, label, tint = tint, modifier = Modifier.size(21.dp)) } } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/AgentPanels.kt b/app/src/main/java/com/droiddeck/launcher/ui/AgentPanels.kt index fd9b9bf8cf..eed2fd6d13 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/AgentPanels.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/AgentPanels.kt @@ -14,10 +14,12 @@ 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.shape.CircleShape import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.text.selection.SelectionContainer +import androidx.compose.material3.LinearProgressIndicator import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable @@ -48,7 +50,7 @@ import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay import kotlinx.coroutines.withContext -/** The model and plan mode for the next turns; a conversation keeps going with whatever is chosen. */ +/** The model, reasoning effort and plan mode for the next turns; a conversation keeps going with whatever is chosen. */ @Composable internal fun AgentModelPicker() { val context = LocalContext.current @@ -63,6 +65,16 @@ internal fun AgentModelPicker() { else SecondaryButton(choice.label, compact = true) { AgentHost.chooseModel(context, id) } } } + if (AgentHost.harness.efforts.isNotEmpty()) Column(verticalArrangement = Arrangement.spacedBy(6.dp)) { + Text(stringResource(R.string.agent_effort), fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = MaterialTheme.colorScheme.onBackground, modifier = Modifier.padding(horizontal = 2.dp)) + Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.horizontalScroll(rememberScrollState())) { + for (level in listOf(null) + AgentHost.harness.efforts) { + val label = level ?: stringResource(R.string.agent_model_default) + if (level == AgentHost.effort) PrimaryButton(label, compact = true) {} + else SecondaryButton(label, compact = true) { AgentHost.chooseEffort(context, level) } + } + } + } if (AgentHost.harness.plans) Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().padding(horizontal = 2.dp)) { Column(Modifier.weight(1f)) { Text(stringResource(R.string.agent_plan), fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = MaterialTheme.colorScheme.onBackground) @@ -180,3 +192,71 @@ internal fun AgentProcessList(modifier: Modifier) { } } } + +/** How full the conversation's context is, how much of the plan's limits is used, and what this conversation cost. */ +@Composable +internal fun AgentUsage() { + val context = LocalContext.current + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + Column( + Modifier.fillMaxWidth().clip(Shape14).background(colors.surface).border(1.dp, pal.line, Shape14).padding(horizontal = 14.dp, vertical = 10.dp), + verticalArrangement = Arrangement.spacedBy(8.dp), + ) { + if (AgentHost.window > 0) UsageRow( + stringResource(R.string.agent_usage_context), + stringResource(R.string.agent_usage_of, tokens(AgentHost.context), tokens(AgentHost.window)), + (AgentHost.context.toFloat() / AgentHost.window).coerceIn(0f, 1f), + ) + for (limit in AgentHost.limits) { + val used = liveUsed(limit) + val label = when { + limit.minutes in 9_000..11_000 -> stringResource(R.string.agent_limit_week) + limit.minutes >= 60 -> stringResource(R.string.agent_limit_hours, limit.minutes / 60) + else -> stringResource(R.string.agent_limit_minutes, limit.minutes) + } + val value = if (limit.resetsAt * 1000 > System.currentTimeMillis()) stringResource(R.string.agent_limit_resets, used, resetTime(context, limit.resetsAt)) else "$used%" + UsageRow(label, value, used / 100f) + } + val turns = AgentHost.entries.filterIsInstance().mapNotNull { it.usage } + val cost = turns.sumOf { it.costUsd } + val ms = turns.sumOf { it.durationMs } + Row(verticalAlignment = Alignment.CenterVertically) { + val facts = buildList { + if (ms > 0) add(clock(ms / 1000)) + if (cost >= 0.005) add("$" + String.format(java.util.Locale.US, "%.2f", cost)) + } + Text( + if (facts.isEmpty()) stringResource(R.string.agent_usage_unknown) else stringResource(R.string.agent_usage_conversation, facts.joinToString(" ยท ")), + fontSize = 12.5.sp, color = pal.onSurfaceVariant, modifier = Modifier.weight(1f), + ) + if (AgentHost.harness.plans && AgentHost.entries.isNotEmpty() && AgentHost.state == AgentHost.State.IDLE) { + SecondaryButton("/compact", compact = true) { AgentHost.send(context, "/compact") } + } + } + } +} + +@Composable +private fun UsageRow(label: String, value: String, fraction: Float) { + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + Column(verticalArrangement = Arrangement.spacedBy(4.dp)) { + Row(verticalAlignment = Alignment.CenterVertically) { + Text(label, fontSize = 14.sp, color = colors.onBackground, modifier = Modifier.weight(1f)) + Text(value, fontSize = 12.5.sp, color = pal.onSurfaceVariant) + } + LinearProgressIndicator( + progress = { fraction }, color = if (fraction >= 0.8f) AttentionAmber else pal.primary, trackColor = pal.surfaceVariant, + modifier = Modifier.fillMaxWidth().height(5.dp).clip(CircleShape), + ) + } +} + +/** A reset later today shows its time; one further off shows the day too. */ +private fun resetTime(context: android.content.Context, epochSeconds: Long): String { + val ms = epochSeconds * 1000 + val flags = if (ms - System.currentTimeMillis() < 20 * 3_600_000L) DateUtils.FORMAT_SHOW_TIME + else DateUtils.FORMAT_SHOW_WEEKDAY or DateUtils.FORMAT_ABBREV_WEEKDAY or DateUtils.FORMAT_SHOW_TIME + return DateUtils.formatDateTime(context, ms, flags) +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/AgentPet.kt b/app/src/main/java/com/droiddeck/launcher/ui/AgentPet.kt new file mode 100644 index 0000000000..8adadcab9c --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/AgentPet.kt @@ -0,0 +1,323 @@ +package com.droiddeck.launcher.ui + +import android.app.Activity +import android.app.Application +import android.content.Context +import android.content.Intent +import android.net.Uri +import android.os.Bundle +import android.os.Handler +import android.os.Looper +import android.os.SystemClock +import android.provider.Settings +import android.view.View +import android.view.ViewGroup +import android.widget.FrameLayout +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.gestures.detectDragGestures +import androidx.compose.foundation.gestures.detectTapGestures +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.BoxWithConstraints +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.offset +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.widthIn +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableLongStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.runtime.snapshotFlow +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.input.pointer.pointerInput +import androidx.compose.ui.layout.onSizeChanged +import androidx.compose.ui.platform.ComposeView +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.onClick +import androidx.compose.ui.semantics.role +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.IntOffset +import androidx.compose.ui.unit.IntSize +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.droiddeck.launcher.agent.AgentHost +import kotlinx.coroutines.MainScope +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch +import kotlin.math.roundToInt + +/** A DroidDeck window the pet can live in when it may not float over other apps. */ +internal interface AgentPetHost { + /** Something already covers the pet's place, such as the session drawer. */ + val petBlocked: Boolean +} + +/** + * DeeDee, the agent's pet: shows what the agent is doing and opens a chat with it. With the + * "display over other apps" permission it floats over every app in windows of its own + * ([PetWindows]); without it, it lives in DroidDeck's own windows. Either way it opens the same + * chat, growing out of it. + */ +internal object AgentPet { + var enabled by mutableStateOf(false) + private set + /** May draw over other apps. */ + var allowed by mutableStateOf(false) + private set + /** Agent pages on screen; the pet steps aside while the conversation itself is in view. */ + var agentOnScreen by mutableIntStateOf(0) + var now by mutableLongStateOf(SystemClock.elapsedRealtime()) + private set + /** When the agent last changed what it was doing. */ + var since by mutableLongStateOf(SystemClock.elapsedRealtime()) + private set + /** The floating windows could not be made, so the pet stays in DroidDeck's own windows instead. */ + private var floatFailed by mutableStateOf(false) + val floating get() = enabled && allowed && !floatFailed + /** How to close the chat open inside each DroidDeck window that has one. */ + private val closeInWindow = java.util.WeakHashMap Unit>() + + /** + * B and Back close a chat open inside [host] before the window acts on them, since the window's + * own keys (leaving a session, going back a page) would otherwise run under it. + */ + fun handleBack(host: AgentPetHost, event: android.view.KeyEvent): Boolean { + val close = closeInWindow[host] ?: return false + if (event.keyCode != android.view.KeyEvent.KEYCODE_BACK && event.keyCode != android.view.KeyEvent.KEYCODE_BUTTON_B) return false + if (event.action == android.view.KeyEvent.ACTION_UP) close() + return true + } + + internal fun chatOpenInWindow(host: AgentPetHost, close: (() -> Unit)?) { + if (close == null) closeInWindow.remove(host) else closeInWindow[host] = close + } + private var windows: PetWindows? = null + private val main = Handler(Looper.getMainLooper()) + private const val TAG = "agent-pet" + private const val KEY = "pet" + private const val SIDE = "pet_side" + private const val HEIGHT = "pet_y" + + fun set(context: Context, on: Boolean) { + enabled = on + AgentHost.prefs(context).edit().putBoolean(KEY, on).apply() + if (on) { + allowed = PetWindows.allowed(context) + if (!allowed) requestFloating(context) + } + } + + /** Opens the system page where the user lets DroidDeck draw over other apps. */ + fun requestFloating(context: Context) { + val intent = Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:${context.packageName}")) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + runCatching { context.startActivity(intent) } + } + + internal fun place(context: Context) = AgentHost.prefs(context).let { it.getBoolean(SIDE, true) to it.getFloat(HEIGHT, 0.3f) } + + internal fun save(context: Context, right: Boolean, height: Float) { + AgentHost.prefs(context).edit().putBoolean(SIDE, right).putFloat(HEIGHT, height).apply() + } + + fun install(app: Application) { + enabled = AgentHost.prefs(app).getBoolean(KEY, false) + allowed = PetWindows.allowed(app) + val scope = MainScope() + scope.launch { + snapshotFlow { Triple(AgentHost.state, AgentHost.entries.size, AgentHost.lab?.running) }.collect { since = SystemClock.elapsedRealtime() } + } + scope.launch { + snapshotFlow { floating && AgentHost.installed }.collect { show -> + if (show && windows == null) windows = runCatching { PetWindows(app) }.onFailure { + android.util.Log.w("AgentPet", "could not float the pet", it) + floatFailed = true + }.getOrNull() + if (!show) windows?.close()?.also { windows = null } + } + } + tick(app) + app.registerActivityLifecycleCallbacks(object : Application.ActivityLifecycleCallbacks { + override fun onActivityResumed(activity: Activity) { + allowed = PetWindows.allowed(activity) + attach(activity) + } + override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) = Unit + override fun onActivityStarted(activity: Activity) = Unit + override fun onActivityPaused(activity: Activity) = Unit + override fun onActivityStopped(activity: Activity) = Unit + override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) = Unit + override fun onActivityDestroyed(activity: Activity) = Unit + }) + } + + private fun tick(app: Application) { + now = SystemClock.elapsedRealtime() + // The permission can be granted or taken back in Settings while DroidDeck is away. + if (enabled) allowed = PetWindows.allowed(app) + main.postDelayed({ tick(app) }, 1_000) + } + + private fun attach(activity: Activity) { + val host = activity as? AgentPetHost ?: return + val decor = activity.window.decorView as? ViewGroup ?: return + if (decor.findViewWithTag(TAG) != null) return + val layer = ComposeView(activity).apply { + tag = TAG + isFocusable = false + importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_NO + setContent { DroidDeckTheme(appScale = com.droiddeck.launcher.core.AppUiPrefs.scale(activity)) { PetLayer(host) } } + } + decor.addView(layer, FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)) + } +} + +private const val SLEEP_AFTER_MS = 5 * 60_000L +private const val CHEER_MS = 10_000L +internal const val PREVIEW_MS = 6_000L + +/** What the agent is up to, as the pet shows it; [since] is when the agent last changed what it was doing. */ +internal fun petState(now: Long, since: Long): PetState { + if (AgentHost.state == AgentHost.State.WORKING || AgentHost.lab?.running == true) return PetState.WORKING + val last = AgentHost.entries.lastOrNull { it is AgentHost.Entry.Finished } as? AgentHost.Entry.Finished + if (AgentHost.unseen && last != null && !last.stopped) { + if (last.error != null) return PetState.ERROR + val said = (AgentHost.entries.lastOrNull { it is AgentHost.Entry.Said } as? AgentHost.Entry.Said)?.text?.trimEnd().orEmpty() + if (last.planned || said.endsWith("?")) return PetState.QUESTION + if (now - since < CHEER_MS) return PetState.DONE + } + return if (now - since > SLEEP_AFTER_MS) PetState.SLEEP else PetState.IDLE +} + +internal fun petStateNow() = petState(AgentPet.now, AgentPet.since) + +/** The line the preview bubble shows while the pet has news, or null when it has none. */ +internal fun petBubbleText(): String? { + if (!AgentHost.unseen) return null + val state = petStateNow() + if (state != PetState.DONE && state != PetState.QUESTION && state != PetState.ERROR) return null + val last = AgentHost.entries.lastOrNull { it is AgentHost.Entry.Finished } as? AgentHost.Entry.Finished + last?.error?.let { return it } + val said = AgentHost.entries.lastOrNull { it is AgentHost.Entry.Said } as? AgentHost.Entry.Said ?: return null + return said.text.lineSequence().map { it.trim().trimStart('#', '*', '-', ' ') }.firstOrNull { it.isNotEmpty() } +} + +/** DeeDee in [state], with a dot while a reply waits to be read. */ +@Composable +internal fun PetFigure(state: PetState, modifier: Modifier) { + Box(modifier.testTag("agent-pet")) { + Box(Modifier.fillMaxSize().padding(4.dp).clip(CircleShape).background(Color(0xEB0E141B)).border(1.dp, Color(0x29FFFFFF), CircleShape)) + DeeDee(state, Modifier.fillMaxSize().padding(6.dp)) + if (AgentHost.unseen && (state == PetState.IDLE || state == PetState.SLEEP)) Box( + Modifier.align(Alignment.TopEnd).padding(8.dp).size(14.dp).clip(CircleShape).background(Color(0xFF1A9FFF)).border(2.dp, Color(0xFF0E141B), CircleShape), + ) + } +} + +@Composable +internal fun PetPreview(text: String, modifier: Modifier, onTap: () -> Unit) { + val shape = RoundedCornerShape(16.dp) + Text( + text, fontSize = 14.sp, color = Color.White, maxLines = 2, overflow = TextOverflow.Ellipsis, + modifier = modifier.widthIn(max = 260.dp).clip(shape).background(Color(0xF0171D25)).border(1.dp, Color(0x33FFFFFF), shape) + .pointerInput(Unit) { detectTapGestures { onTap() } }.padding(horizontal = 14.dp, vertical = 10.dp), + ) +} + +/** The pet inside one DroidDeck window, for when it may not float over other apps. */ +@Composable +private fun PetLayer(host: AgentPetHost) { + var chatOpen by remember { mutableStateOf(false) } + var chatShown by remember { mutableStateOf(false) } + val shown = AgentPet.enabled && !AgentPet.floating && AgentHost.installed && (chatShown || AgentPet.agentOnScreen == 0) && !host.petBlocked + if (!shown) return + val context = LocalContext.current + val motion = remember { PetMotion(context) } + val density = LocalDensity.current + val openLabel = androidx.compose.ui.res.stringResource(com.droiddeck.launcher.R.string.agent_pet_open) + val openChat = { + motion.dock() + chatShown = true + chatOpen = true + } + val closeChat = { + chatOpen = false + motion.undock() + } + BoxWithConstraints(Modifier.fillMaxSize()) { + motion.fit(constraints.maxWidth.toFloat(), constraints.maxHeight.toFloat()) + if (chatShown) PetChat(chatOpen, motion, closeChat) { chatShown = false } + androidx.compose.runtime.DisposableEffect(host, chatOpen) { + AgentPet.chatOpenInWindow(host, if (chatOpen) closeChat else null) + onDispose { AgentPet.chatOpenInWindow(host, null) } + } + var bubble by remember { mutableStateOf(null) } + val news = petBubbleText() + LaunchedEffect(news) { + bubble = news + if (news != null) { + delay(PREVIEW_MS) + bubble = null + } + } + if (motion.dragging) Box(Modifier.offset { + val (tx, ty) = motion.target + IntOffset((tx - motion.size / 2).roundToInt(), (ty - motion.size / 2).roundToInt()) + }) { PetCloseTarget(motion.overTarget) } + val text = bubble + if (text != null && !motion.dragging) { + var size by remember { mutableStateOf(IntSize.Zero) } + val gap = with(density) { 10.dp.toPx() } + PetPreview(text, Modifier.onSizeChanged { size = it }.offset { + val x = if (motion.right) motion.x - gap - size.width else motion.x + motion.size + gap + IntOffset(x.roundToInt(), (motion.y + motion.size / 2 - size.height / 2).roundToInt()) + }) { + bubble = null + openChat() + } + } + PetFigure( + petStateNow(), + Modifier.offset { IntOffset(motion.x.roundToInt(), motion.y.roundToInt()) } + .size(with(density) { motion.size.toDp() }) + .semantics { + contentDescription = openLabel + role = androidx.compose.ui.semantics.Role.Button + onClick { if (chatOpen) closeChat() else openChat(); true } + } + .pointerInput(Unit) { detectTapGestures { bubble = null; if (chatOpen) closeChat() else openChat() } } + .pointerInput(Unit) { + // The pet moves under the finger, so its velocity is measured where it is on the screen. + val tracker = androidx.compose.ui.input.pointer.util.VelocityTracker() + detectDragGestures( + onDragStart = { bubble = null; if (chatOpen) closeChat(); tracker.resetTracking(); motion.start() }, + onDrag = { change, amount -> + change.consume() + motion.move(amount.x, amount.y) + tracker.addPosition(change.uptimeMillis, androidx.compose.ui.geometry.Offset(motion.x + change.position.x, motion.y + change.position.y)) + }, + onDragEnd = { + val v = tracker.calculateVelocity() + if (motion.end(v.x, v.y)) AgentPet.set(context, false) + }, + onDragCancel = { motion.cancel() }, + ) + }, + ) + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/AgentPetWindows.kt b/app/src/main/java/com/droiddeck/launcher/ui/AgentPetWindows.kt new file mode 100644 index 0000000000..c8d3aba8c9 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/AgentPetWindows.kt @@ -0,0 +1,559 @@ +package com.droiddeck.launcher.ui + +import android.animation.ValueAnimator +import android.annotation.SuppressLint +import android.content.Context +import android.graphics.PixelFormat +import android.os.Build +import android.provider.Settings +import android.view.Gravity +import android.view.KeyEvent +import android.view.MotionEvent +import android.view.View +import android.view.ViewConfiguration +import android.view.WindowManager +import android.view.animation.OvershootInterpolator +import android.widget.FrameLayout +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.BoxWithConstraints +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.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.offset +import androidx.compose.foundation.layout.width +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.outlined.Close +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableFloatStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.runtime.snapshotFlow +import androidx.compose.animation.core.Animatable +import androidx.compose.foundation.Canvas +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.ui.Alignment +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.Path +import androidx.compose.ui.graphics.drawscope.Stroke +import androidx.compose.ui.unit.IntOffset +import kotlinx.coroutines.coroutineScope +import kotlinx.coroutines.delay +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.graphicsLayer +import androidx.compose.ui.input.key.onPreviewKeyEvent +import androidx.compose.ui.platform.ComposeView +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.LifecycleOwner +import androidx.lifecycle.LifecycleRegistry +import androidx.lifecycle.setViewTreeLifecycleOwner +import androidx.savedstate.SavedStateRegistry +import androidx.savedstate.SavedStateRegistryController +import androidx.savedstate.SavedStateRegistryOwner +import androidx.savedstate.setViewTreeSavedStateRegistryOwner +import com.droiddeck.launcher.R +import com.droiddeck.launcher.agent.AgentHost +import kotlinx.coroutines.MainScope +import kotlinx.coroutines.cancel +import kotlinx.coroutines.flow.collectLatest +import kotlinx.coroutines.launch +import kotlin.math.abs +import kotlin.math.hypot +import kotlin.math.roundToInt + +/** + * Where the pet is on the screen and how it moves: dragged anywhere, then settling against the + * nearer side edge, or dropped on the close target to turn it off. While its chat is open it is + * docked at the top corner, the way a chat head hops up when its conversation opens, and goes home + * when the chat closes. Positions are screen pixels. + */ +internal class PetMotion(private val context: Context) { + var x by mutableFloatStateOf(0f) + private set + var y by mutableFloatStateOf(0f) + private set + var right by mutableStateOf(true) + private set + var dragging by mutableStateOf(false) + private set + var width by mutableFloatStateOf(0f) + private set + var height by mutableFloatStateOf(0f) + private set + /** Docked for the chat; where to go back to is kept as a side and a relative height. */ + var docked by mutableStateOf(false) + private set + private val density = context.resources.displayMetrics.density + val size = 76 * density + private val margin = 6 * density + private val inset = 24 * density + private var settle: ValueAnimator? = null + private val spring = FlingSpring { sx, sy -> x = sx; y = sy } + + val dockX get() = width - size - margin + + private companion object { + /** The share of the pet that hangs past the edge it rests against. */ + const val TUCK = 0.2f + } + val dockY get() = inset + val target get() = Pair(width / 2, height - 72 * density) + val overTarget get() = dragging && hypot(x + size / 2 - target.first, y + size / 2 - target.second) < size + + /** Fits the pet into a [w] by [h] screen, keeping its side and relative height, as after a rotation. */ + fun fit(w: Float, h: Float) { + if (w <= 0 || h <= 0 || (w == width && h == height)) return + val first = width == 0f + val fraction = if (first) AgentPet.place(context).also { right = it.first }.second else if (docked) home else fractionOf(y) + settle?.cancel() + spring.cancel() + width = w + height = h + home = fraction + if (docked) { + x = dockX + y = dockY + } else { + x = edge(right) + y = inset + travel() * fraction + } + } + + private var home = 0f + private fun travel() = (height - size - inset * 2).coerceAtLeast(0f) + private fun fractionOf(at: Float) = if (travel() > 0) ((at - inset) / travel()).coerceIn(0f, 1f) else 0f + /** At rest the pet tucks part of itself past the screen edge, as a chat head does. */ + private fun edge(side: Boolean) = if (side) width - size * (1f - TUCK) else -size * TUCK + + /** Hops up to the top corner for the chat. */ + fun dock() { + if (docked) return + home = fractionOf(y) + docked = true + glide(dockX, dockY, 260, OvershootInterpolator(0.9f)) + } + + /** Goes back to where it was before the chat opened. */ + fun undock() { + if (!docked) return + docked = false + glide(edge(right), inset + travel() * home, 320, android.view.animation.DecelerateInterpolator(1.6f)) + } + + fun start() { + settle?.cancel() + spring.cancel() + docked = false + dragging = true + } + + fun move(dx: Float, dy: Float) { + x += dx + y += dy + } + + /** A drag the system took away: the pet goes back to an edge, never to the close target. */ + fun cancel() { + if (!dragging) return + dragging = false + right = x + size / 2 > width / 2 + val toY = y.coerceIn(inset, (height - size - inset).coerceAtLeast(inset)) + home = fractionOf(toY) + spring.start(x, y, 0f, 0f, edge(right), toY) + } + + /** Ends a drag let go at [vx], [vy] pixels per second; true when the pet was dropped on the close target. */ + fun end(vx: Float = 0f, vy: Float = 0f): Boolean { + val dismissed = overTarget + dragging = false + if (dismissed) return true + right = EdgeFling.toRight(x + size / 2, width, vx, density) + val toY = EdgeFling.restY(y, vy, inset, height - size - inset) + home = fractionOf(toY) + AgentPet.save(context, right, home) + spring.start(x, y, vx, vy, edge(right), toY) + return false + } + + private fun glide(toX: Float, toY: Float, ms: Long, curve: android.animation.TimeInterpolator) { + settle?.cancel() + spring.cancel() + val fromX = x + val fromY = y + settle = ValueAnimator.ofFloat(0f, 1f).apply { + duration = (ms * Motion.scale).toLong().coerceAtLeast(0) + interpolator = curve + addUpdateListener { + val f = it.animatedValue as Float + x = fromX + (toX - fromX) * f + y = fromY + (toY - fromY) * f + } + start() + } + } +} + +/** Lets a ComposeView live in a window no activity owns. */ +private class OverlayOwner : LifecycleOwner, SavedStateRegistryOwner { + private val registry = LifecycleRegistry(this) + private val saved = SavedStateRegistryController.create(this) + override val lifecycle: Lifecycle get() = registry + override val savedStateRegistry: SavedStateRegistry get() = saved.savedStateRegistry + + init { + saved.performRestore(null) + registry.currentState = Lifecycle.State.RESUMED + } + + fun destroy() { + registry.currentState = Lifecycle.State.DESTROYED + } +} + +/** + * The pet over every app, in windows of its own: the pet, its message preview, the close target + * while it is dragged, and the chat it opens. Needs the "display over other apps" permission. + */ +@SuppressLint("ClickableViewAccessibility") +internal class PetWindows(private val context: Context) { + private val windows = context.getSystemService(WindowManager::class.java) + private val owner = OverlayOwner() + private val motion = PetMotion(context) + private val scope = MainScope() + /** The chat is open, or opening; its window stays up until it has shrunk back into the pet. */ + private var chatOpen by mutableStateOf(false) + private var bubble by mutableStateOf(null) + private var bubbleWidth by mutableFloatStateOf(0f) + private var bubbleHeight by mutableFloatStateOf(0f) + /** The windows are in the window manager, so moving one goes through it. */ + private var added = false + private val turns = object : android.content.ComponentCallbacks { + override fun onConfigurationChanged(newConfig: android.content.res.Configuration) = fitScreen() + @Deprecated("Deprecated in Java") + override fun onLowMemory() = Unit + } + + // A window emptied to no size keeps showing its last frame, so each is hidden as a whole instead. + private val head = window(touchable = true, focusable = false) { + PetFigure(petStateNow(), Modifier.size(76.dp)) + } + private val preview = window(touchable = true, focusable = false, onSize = { w, h -> bubbleWidth = w.toFloat(); bubbleHeight = h.toFloat() }) { + bubble?.let { PetPreview(it, Modifier.padding(2.dp)) { openChat() } } + } + private val target = window(touchable = false, focusable = false) { + PetCloseTarget(motion.overTarget) + } + private val chat: Window = window(touchable = true, focusable = true, full = true) { + PetChat(chatOpen, motion, ::closeChat) { showChat(false) } + } + + init { + head.view.setOnTouchListener(DragTouch()) + head.view.contentDescription = context.getString(R.string.agent_pet_open) + head.view.setOnClickListener { if (chatOpen) closeChat() else openChat() } + scope.launch { snapshotFlow { Triple(motion.x, motion.y, motion.right) }.collectLatest { place() } } + scope.launch { snapshotFlow { bubbleWidth to bubbleHeight }.collectLatest { place() } } + scope.launch { snapshotFlow { AgentPet.agentOnScreen == 0 }.collectLatest { setVisible(head, it) } } + scope.launch { snapshotFlow { motion.dragging }.collectLatest { setVisible(target, it) } } + scope.launch { + snapshotFlow { bubble != null && !chatOpen && !motion.dragging && AgentPet.agentOnScreen == 0 }.collectLatest { setVisible(preview, it) } + } + scope.launch { + snapshotFlow { petBubbleText() }.collectLatest { text -> + bubble = text + if (text != null) { + kotlinx.coroutines.delay(PREVIEW_MS) + bubble = null + } + } + } + fitScreen() + context.registerComponentCallbacks(turns) + place() + listOf(target, preview).forEach { setVisible(it, false) } + showChat(false) + listOf(chat, target, preview, head).forEach { windows.addView(it.view, it.params) } + added = true + } + + private class Window(val view: FrameLayout, val params: WindowManager.LayoutParams, val touchable: Boolean) + + private fun window( + touchable: Boolean, focusable: Boolean, full: Boolean = false, onSize: ((Int, Int) -> Unit)? = null, content: @Composable () -> Unit, + ): Window { + val compose = ComposeView(context).apply { + setViewTreeLifecycleOwner(owner) + setViewTreeSavedStateRegistryOwner(owner) + setContent { DroidDeckTheme(appScale = com.droiddeck.launcher.core.AppUiPrefs.scale(context)) { content() } } + } + val frame = object : FrameLayout(context) { + override fun dispatchKeyEvent(event: KeyEvent): Boolean { + if (full && event.keyCode == KeyEvent.KEYCODE_BACK && event.action == KeyEvent.ACTION_UP && chatOpen) { + closeChat() + return true + } + return super.dispatchKeyEvent(event) + } + }.apply { + addView(compose) + setViewTreeLifecycleOwner(owner) + setViewTreeSavedStateRegistryOwner(owner) + } + val size = if (full) WindowManager.LayoutParams.MATCH_PARENT else WindowManager.LayoutParams.WRAP_CONTENT + val params = WindowManager.LayoutParams( + size, size, WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY, + (if (focusable) 0 else WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE) or + (if (touchable) 0 else WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE) or + WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN or + (if (full) 0 else WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS), + PixelFormat.TRANSLUCENT, + ).apply { + gravity = Gravity.TOP or Gravity.START + if (full) softInputMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES + } + if (onSize != null) compose.addOnLayoutChangeListener { v, _, _, _, _, _, _, _, _ -> onSize(v.width, v.height) } + return Window(frame, params, touchable) + } + + /** A hidden overlay window still owns its frame, which the system can stretch over the screen, so it also stops taking touches. */ + private fun setVisible(window: Window, shown: Boolean) { + window.view.visibility = if (shown) View.VISIBLE else View.GONE + setTouchable(window, shown && window.touchable) + } + + private fun setTouchable(window: Window, on: Boolean) { + val flags = if (on) window.params.flags and WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE.inv() + else window.params.flags or WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE + if (flags == window.params.flags) return + window.params.flags = flags + if (added) runCatching { windows.updateViewLayout(window.view, window.params) } + } + + private fun place() { + val gap = 10 * context.resources.displayMetrics.density + update(head, motion.x, motion.y) + val bx = if (motion.right) motion.x - gap - bubbleWidth else motion.x + motion.size + gap + update(preview, bx, motion.y + motion.size / 2 - bubbleHeight / 2) + val (tx, ty) = motion.target + update(target, tx - motion.size / 2, ty - motion.size / 2) + } + + private fun update(window: Window, x: Float, y: Float) { + if (window.params.x == x.roundToInt() && window.params.y == y.roundToInt()) return + window.params.x = x.roundToInt() + window.params.y = y.roundToInt() + if (added) runCatching { windows.updateViewLayout(window.view, window.params) } + } + + private fun openChat() { + bubble = null + if (chatOpen) return + motion.dock() + showChat(true) + chatOpen = true + } + + private fun closeChat() { + if (!chatOpen) return + chatOpen = false + motion.undock() + } + + /** + * The chat window is always drawn; closed, it waits off the screen and takes neither touches nor + * keys, so opening it is a move and not a first layout. + */ + private fun showChat(on: Boolean) { + chat.params.x = if (on) 0 else OFFSCREEN + val quiet = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE + chat.params.flags = if (on) chat.params.flags and quiet.inv() else chat.params.flags or quiet + if (added) runCatching { windows.updateViewLayout(chat.view, chat.params) } + } + + /** The whole screen, the status and navigation bars included, since overlay windows can cover them. */ + private fun fitScreen() { + val bounds = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) windows.maximumWindowMetrics.bounds + else android.graphics.Point().also { @Suppress("DEPRECATION") windows.defaultDisplay.getRealSize(it) }.let { android.graphics.Rect(0, 0, it.x, it.y) } + motion.fit(bounds.width().toFloat(), bounds.height().toFloat()) + } + + fun close() { + runCatching { context.unregisterComponentCallbacks(turns) } + scope.cancel() + listOf(head, preview, target, chat).forEach { runCatching { windows.removeView(it.view) } } + owner.destroy() + } + + /** Drags and taps on the pet, in screen coordinates, since its window moves under the finger. */ + private inner class DragTouch : View.OnTouchListener { + private val slop = ViewConfiguration.get(context).scaledTouchSlop + private var downX = 0f + private var downY = 0f + private var lastX = 0f + private var lastY = 0f + private var moved = false + private var tracker: android.view.VelocityTracker? = null + + /** The window moves under the finger, so velocity is measured on the screen. */ + private fun track(e: MotionEvent) { + val onScreen = MotionEvent.obtain(e).apply { setLocation(e.rawX, e.rawY) } + (tracker ?: android.view.VelocityTracker.obtain().also { tracker = it }).addMovement(onScreen) + onScreen.recycle() + } + + private fun release(): Pair { + val t = tracker ?: return 0f to 0f + t.computeCurrentVelocity(1000) + val v = t.xVelocity to t.yVelocity + t.recycle() + tracker = null + return v + } + + override fun onTouch(v: View, e: MotionEvent): Boolean { + track(e) + when (e.actionMasked) { + MotionEvent.ACTION_DOWN -> { + downX = e.rawX; downY = e.rawY; lastX = e.rawX; lastY = e.rawY + moved = false + } + MotionEvent.ACTION_MOVE -> { + if (!moved && (abs(e.rawX - downX) > slop || abs(e.rawY - downY) > slop)) { + moved = true + bubble = null + closeChat() + motion.start() + } + if (moved) motion.move(e.rawX - lastX, e.rawY - lastY) + lastX = e.rawX; lastY = e.rawY + } + MotionEvent.ACTION_UP -> { + val (vx, vy) = release() + if (moved) { + if (motion.end(vx, vy)) AgentPet.set(context, false) + } else v.performClick() + } + MotionEvent.ACTION_CANCEL -> { + release() + if (moved) motion.cancel() + } + } + return true + } + } + + companion object { + private const val OFFSCREEN = 10_000 + fun allowed(context: Context) = Settings.canDrawOverlays(context) + } +} + +/** + * The floating chat, opened the way a chat head opens its conversation: the pet hops into the top + * corner while the whole conversation scales up out of it and fades in, and closing shrinks it back + * into the pet as the pet glides home. In landscape it sits beside the docked pet, in portrait + * under it. Its contents are built while it is closed, so opening only animates. + */ +@Composable +internal fun PetChat(open: Boolean, motion: PetMotion, onClose: () -> Unit, onClosed: () -> Unit) { + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + val density = androidx.compose.ui.platform.LocalDensity.current + BoxWithConstraints( + Modifier.fillMaxSize().onPreviewKeyEvent { e -> + val k = e.nativeKeyEvent + if (k.keyCode != KeyEvent.KEYCODE_BUTTON_B || k.action != KeyEvent.ACTION_UP) return@onPreviewKeyEvent false + onClose() + true + }, + ) { + val w = constraints.maxWidth.toFloat() + val h = constraints.maxHeight.toFloat() + val margin = with(density) { 8.dp.toPx() } + val gap = with(density) { 6.dp.toPx() } + val wide = w > h + val panel = if (wide) { + val right = motion.dockX - gap + Rect((right - with(density) { 900.dp.toPx() }).coerceAtLeast(margin), motion.dockY, right, h - margin) + } else { + Rect(margin, motion.dockY + motion.size + gap, w - margin, h - margin) + } + val grow = remember { Animatable(0f) } + val fade = remember { Animatable(0f) } + LaunchedEffect(open) { + if (open) coroutineScope { + launch { grow.animateTo(1f, Motion.sp(0.82f, 520f)) } + launch { fade.animateTo(1f, Motion.tw(140)) } + } else if (fade.value > 0f) { + coroutineScope { + launch { grow.animateTo(0f, Motion.tw(170, easing = androidx.compose.animation.core.FastOutLinearInEasing)) } + launch { delay(Motion.ms(40).toLong()); fade.animateTo(0f, Motion.tw(130)) } + } + onClosed() + } + } + Box( + Modifier.fillMaxSize().graphicsLayer { alpha = fade.value }.background(Color(0x8C000000)) + .clickable(remember { MutableInteractionSource() }, null, enabled = open) { onClose() }, + ) + Column( + Modifier.offset { IntOffset(panel.left.roundToInt(), panel.top.roundToInt()) } + .size(with(density) { panel.width.toDp() }, with(density) { panel.height.toDp() }) + .graphicsLayer { + // Grows from where the pet is right now, so the two travel together while the pet hops to its corner. + transformOrigin = androidx.compose.ui.graphics.TransformOrigin( + ((motion.x + motion.size / 2 - panel.left) / panel.width.coerceAtLeast(1f)).coerceIn(0f, 1f), + ((motion.y + motion.size / 2 - panel.top) / panel.height.coerceAtLeast(1f)).coerceIn(0f, 1f), + ) + val s = 0.12f + 0.88f * grow.value + scaleX = s + scaleY = s + alpha = fade.value + } + .clip(Shape16).background(colors.background).border(1.dp, pal.line, Shape16) + .clickable(remember { MutableInteractionSource() }, null, enabled = open) {} + .padding(start = 12.dp, end = 12.dp, top = 6.dp), + ) { + Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().padding(bottom = 2.dp)) { + Text(stringResource(R.string.agent_pet_name), fontSize = 16.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, + modifier = Modifier.padding(start = 4.dp)) + Spacer(Modifier.weight(1f)) + HeaderAction(Icons.Outlined.Close, stringResource(R.string.agent_close), size = 34.dp, tag = "agent-pet-close", onClick = onClose) + } + AgentPage(Modifier.weight(1f).fillMaxWidth(), visible = open, startTyping = AgentHost.entries.isEmpty(), hidesPet = false) + } + } +} + +@Composable +internal fun PetCloseTarget(over: Boolean) { + Box( + contentAlignment = Alignment.Center, + modifier = Modifier.padding(4.dp).size(if (over) 84.dp else 68.dp).clip(androidx.compose.foundation.shape.CircleShape) + .background(Color(0xCC0E141B)) + .border(2.dp, if (over) Color(0xFFFF5A5F) else Color(0x66FFFFFF), androidx.compose.foundation.shape.CircleShape), + ) { Icon(Icons.Outlined.Close, null, tint = Color.White, modifier = Modifier.size(30.dp)) } +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/AndroidAppsPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/AndroidAppsPage.kt index f43e191a66..dce70549b2 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/AndroidAppsPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/AndroidAppsPage.kt @@ -22,6 +22,7 @@ import androidx.compose.foundation.focusGroup import androidx.compose.foundation.focusable import androidx.compose.foundation.gestures.awaitEachGesture import androidx.compose.foundation.gestures.awaitFirstDown +import androidx.compose.foundation.gestures.scrollBy import androidx.compose.foundation.hoverable import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.interaction.collectIsPressedAsState @@ -55,8 +56,6 @@ import androidx.compose.foundation.lazy.grid.rememberLazyGridState import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.filled.Close -import androidx.compose.material.icons.filled.Edit import androidx.compose.material.icons.filled.FilterAlt import androidx.compose.material.icons.filled.Sort import androidx.compose.material.icons.filled.Widgets @@ -75,6 +74,7 @@ import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue +import androidx.compose.runtime.snapshotFlow import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip @@ -92,6 +92,7 @@ import androidx.compose.ui.focus.FocusDirection import androidx.compose.ui.focus.FocusRequester import androidx.compose.ui.focus.focusProperties import androidx.compose.ui.focus.focusRequester +import androidx.compose.ui.focus.onFocusChanged import androidx.compose.ui.input.InputMode import androidx.compose.ui.platform.LocalInputModeManager import androidx.compose.ui.platform.LocalContext @@ -110,10 +111,13 @@ import androidx.compose.ui.zIndex import com.droiddeck.launcher.HomeApp import com.droiddeck.launcher.HomeFolders import com.droiddeck.launcher.HomeHidden +import com.droiddeck.launcher.HomeIcons import com.droiddeck.launcher.HomePins +import com.droiddeck.launcher.IconPack import android.content.pm.ShortcutInfo import android.graphics.Bitmap import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.flow.drop import kotlinx.coroutines.withContext import com.droiddeck.launcher.HomeWidgets import com.droiddeck.launcher.R @@ -145,6 +149,9 @@ private sealed interface AppEntry : AppEntryKey { } } +/** The focus id of the tile an entry is shown as. */ +private fun tileId(entry: AppEntry): String = "tile:" + if (entry is AppEntry.App) entry.app.key else entry.key + private fun indexLetter(label: String): String { val c = label.trim().firstOrNull()?.uppercaseChar() ?: return "#" return if (c in 'A'..'Z') c.toString() else if (c.isLetter()) c.toString() else "#" @@ -231,6 +238,48 @@ internal object AppsView { } } +internal object AppsGrid { + const val SMALL = 44 + const val MEDIUM = 52 + const val LARGE = 64 + private val ICON_SIZES = listOf(SMALL, MEDIUM, LARGE) + const val TIGHT = -12 + const val NORMAL = 0 + const val ROOMY = 16 + private val SPACINGS = listOf(TIGHT, NORMAL, ROOMY) + + var labels by mutableStateOf(true) + private set + var iconDp by mutableStateOf(MEDIUM) + private set + var spacing by mutableStateOf(NORMAL) + private set + + private fun prefs(context: Context) = context.getSharedPreferences("home_launcher", Context.MODE_PRIVATE) + + fun load(context: Context) { + val p = prefs(context) + labels = p.getBoolean("grid_labels", true) + iconDp = p.getInt("grid_icon", MEDIUM).takeIf { it in ICON_SIZES } ?: MEDIUM + spacing = p.getInt("grid_spacing", NORMAL).takeIf { it in SPACINGS } ?: NORMAL + } + + fun setLabels(context: Context, value: Boolean) { + labels = value + prefs(context).edit().putBoolean("grid_labels", value).apply() + } + + fun setIconDp(context: Context, value: Int) { + iconDp = value + prefs(context).edit().putInt("grid_icon", value).apply() + } + + fun setSpacing(context: Context, value: Int) { + spacing = value + prefs(context).edit().putInt("grid_spacing", value).apply() + } +} + internal interface AppEntryKey { val label: String val installedAt: Long @@ -239,9 +288,9 @@ internal interface AppEntryKey { @OptIn(ExperimentalLayoutApi::class) @Composable -internal fun AndroidAppsPage(s: FrontEndState, modifier: Modifier, onLaunch: (HomeApp.LaunchableApp) -> Unit) { +internal fun AndroidAppsPage(s: FrontEndState, a: FrontEndActions, modifier: Modifier, onLaunch: (HomeApp.LaunchableApp) -> Unit) { val ctx = LocalContext.current - remember { HomeFolders.load(ctx); HomeWidgets.load(ctx); HomeHidden.load(ctx); AppsView.load(ctx); true } + remember { HomeFolders.load(ctx); HomeWidgets.load(ctx); HomeHidden.load(ctx); AppsView.load(ctx); AppsGrid.load(ctx); true } val colors = MaterialTheme.colorScheme val narrow = LocalNarrowPane.current val padH = if (narrow) 16.dp else 22.dp @@ -249,6 +298,10 @@ internal fun AndroidAppsPage(s: FrontEndState, modifier: Modifier, onLaunch: (Ho var openFolder by rememberSaveable { mutableStateOf(null) } var renameOnOpen by rememberSaveable { mutableStateOf(false) } var picking by rememberSaveable { mutableStateOf(false) } + var iconFor by remember { mutableStateOf(null) } + LaunchedEffect(Unit) { + snapshotFlow { HomeIcons.overrides }.drop(1).collect { a.onAppIconsChanged() } + } val folders = HomeFolders.folders val byKey = remember(s.androidApps) { s.androidApps.associateBy { it.key } } val byPkg = remember(s.androidApps) { s.androidApps.filterNot { it.work }.groupBy { it.packageName }.mapNotNull { (pkg, apps) -> apps.singleOrNull()?.let { pkg to it } }.toMap() } @@ -294,7 +347,7 @@ internal fun AndroidAppsPage(s: FrontEndState, modifier: Modifier, onLaunch: (Ho ModeHeader( stringResource(R.string.content_android_apps), query, { query = it }, placeholder = stringResource(R.string.apps_search_hint), - clearSearchFocus = openFolder != null || picking, + clearSearchFocus = openFolder != null || picking || iconFor != null, lead = { Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.padding(start = 2.dp, end = 4.dp)) { Text(stringResource(R.string.content_android_apps), fontSize = if (narrow) 20.sp else 24.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, maxLines = 1) @@ -305,16 +358,37 @@ internal fun AndroidAppsPage(s: FrontEndState, modifier: Modifier, onLaunch: (Ho ) { AppsFilterButton() AppsSortButton() + AppsAppearanceButton(a) HeaderIconButton(stringResource(R.string.apps_add_widget), Icons.Filled.Widgets, "add-widget") { HomeWidgets.loadProviders(ctx) picking = true } } } - Box(Modifier.weight(1f).fillMaxWidth()) { + val front = LocalFrontFocus.current + val steer = rememberCoroutineScope() + // Down goes to the tile straight below. The grid's own search only sees the tiles laid out so far, so above a short or + // unseen last row it lands on a tile further left; above a gap in a short last row the row's last tile takes it. + Box(Modifier.weight(1f).fillMaxWidth().onPreviewKeyEvent { event -> + val k = event.nativeKeyEvent + if (k.keyCode != KeyEvent.KEYCODE_DPAD_DOWN || front == null) return@onPreviewKeyEvent false + val from = entries.indexOfFirst { tileId(it) == front.last } + val columns = (grid.layoutInfo.visibleItemsInfo.maxOfOrNull { it.column } ?: 0) + 1 + if (from < 0 || from / columns == entries.lastIndex / columns) return@onPreviewKeyEvent false + if (k.action == KeyEvent.ACTION_DOWN) { + val id = tileId(entries[minOf(from + columns, entries.lastIndex)]) + val shown = (front.attached[id] ?: 0) > 0 + if (!shown || runCatching { front.items.getValue(id).requestFocus() }.isFailure) steer.launch { + // The row below is not laid out yet: bring it in, then take it. + if (!shown) grid.scrollBy((grid.layoutInfo.visibleItemsInfo.firstOrNull { it.index == from + leadItems }?.size?.height ?: 0).toFloat()) + focusSoon { front.items.getValue(id) } + } + } + true + }) { val scroller = q.isEmpty() && byName && entries.size > 16 LazyVerticalGrid( - columns = GridCells.Adaptive(if (narrow) 84.dp else 96.dp), + columns = GridCells.Adaptive((if (narrow) 84 else 96).dp + AppsGrid.spacing.dp), state = grid, horizontalArrangement = Arrangement.spacedBy(10.dp), verticalArrangement = Arrangement.spacedBy(10.dp), @@ -345,7 +419,7 @@ internal fun AndroidAppsPage(s: FrontEndState, modifier: Modifier, onLaunch: (Ho items(entries, key = { it.key }) { entry -> when (entry) { is AppEntry.App -> AppTile( - entry.app, folderId = null, onLaunch = onLaunch, onNewFolder = newFolder, + entry.app, folderId = null, onLaunch = onLaunch, onNewFolder = newFolder, onChangeIcon = { iconFor = it }, first = entry === entries.first(), ) is AppEntry.Shortcut -> PinnedTile(entry.pinned, first = entry === entries.first()) @@ -369,7 +443,7 @@ internal fun AndroidAppsPage(s: FrontEndState, modifier: Modifier, onLaunch: (Ho var last by remember { mutableStateOf(folder) } if (folder != null) last = folder last?.let { f -> - FolderSheet(f, f.apps.mapNotNull(member).filter { it.key !in hidden }.sortedWith(compareBy(String.CASE_INSENSITIVE_ORDER) { it.label }), renameOnOpen, onLaunch, newFolder) { + FolderSheet(f, f.apps.mapNotNull(member).filter { it.key !in hidden }.sortedWith(compareBy(String.CASE_INSENSITIVE_ORDER) { it.label }), renameOnOpen, onLaunch, newFolder, { iconFor = it }) { openFolder = null renameOnOpen = false } @@ -379,11 +453,19 @@ internal fun AndroidAppsPage(s: FrontEndState, modifier: Modifier, onLaunch: (Ho picking, enter = fadeIn(Motion.tw(180)), exit = fadeOut(Motion.tw(160)), modifier = Modifier.fillMaxSize().zIndex(3f), ) { WidgetPicker(padH) { picking = false } } + AnimatedVisibility( + iconFor != null, enter = fadeIn(Motion.tw(180)), exit = fadeOut(Motion.tw(160)), + modifier = Modifier.fillMaxSize().zIndex(4f), + ) { + var last by remember { mutableStateOf(iconFor) } + iconFor?.let { last = it } + last?.let { app -> AppIconPicker(app, padH) { iconFor = null } } + } } } @Composable -private fun SwipeLock() { +internal fun SwipeLock() { DisposableEffect(Unit) { PageSwipe.locks++ onDispose { PageSwipe.locks-- } @@ -570,22 +652,22 @@ private fun AppIcon(app: HomeApp.LaunchableApp, size: androidx.compose.ui.unit.D private fun AppTile( app: HomeApp.LaunchableApp, folderId: String?, first: Boolean, onLaunch: (HomeApp.LaunchableApp) -> Unit, onNewFolder: (HomeApp.LaunchableApp) -> Unit, - modifier: Modifier = Modifier, + onChangeIcon: (HomeApp.LaunchableApp) -> Unit, modifier: Modifier = Modifier, ) { var menu by remember { mutableStateOf(false) } Box(modifier) { TileFrame(app.key, first, onClick = { onLaunch(app) }, onMenu = { menu = true }) { - AppIcon(app, 52.dp) - TileLabel(app.label) + AppIcon(app, AppsGrid.iconDp.dp) + if (AppsGrid.labels) TileLabel(app.label) } - AppMenu(app, folderId, menu, onDismiss = { menu = false }, onNewFolder = onNewFolder) + AppMenu(app, folderId, menu, onDismiss = { menu = false }, onNewFolder = onNewFolder, onChangeIcon = onChangeIcon) } } @Composable private fun AppMenu( app: HomeApp.LaunchableApp, folderId: String?, open: Boolean, - onDismiss: () -> Unit, onNewFolder: (HomeApp.LaunchableApp) -> Unit, + onDismiss: () -> Unit, onNewFolder: (HomeApp.LaunchableApp) -> Unit, onChangeIcon: (HomeApp.LaunchableApp) -> Unit, ) { val ctx = LocalContext.current var choosing by remember { mutableStateOf(false) } @@ -638,6 +720,14 @@ private fun AppMenu( onDismiss() HomeHidden.set(ctx, app.key, !isHidden) } + if (IconPack.active(ctx) != null) MenuItem(stringResource(R.string.apps_change_icon), checked = false) { + onDismiss() + onChangeIcon(app) + } + if (app.key in HomeIcons.overrides) MenuItem(stringResource(R.string.apps_reset_icon), checked = false) { + onDismiss() + HomeIcons.clear(ctx, app.key) + } MenuItem(stringResource(R.string.apps_app_info), checked = false) { onDismiss() runCatching { HomeApp.openAppInfo(ctx, app) } @@ -664,10 +754,10 @@ private fun PinnedTile(pinned: HomePins.Pinned, first: Boolean) { TileFrame(pinned.key, first, onClick = { runCatching { HomeApp.startShortcut(ctx, pinned.info) } }, onMenu = { menu = true }) { Box { val icon = pinned.icon - if (icon != null) Image(icon.asImageBitmap(), null, contentScale = ContentScale.Fit, modifier = Modifier.size(52.dp)) - else Box(Modifier.size(52.dp).clip(CircleShape).background(artBrush(hueOf(pinned.label)))) + if (icon != null) Image(icon.asImageBitmap(), null, contentScale = ContentScale.Fit, modifier = Modifier.size(AppsGrid.iconDp.dp)) + else Box(Modifier.size(AppsGrid.iconDp.dp).clip(CircleShape).background(artBrush(hueOf(pinned.label)))) } - TileLabel(pinned.label) + if (AppsGrid.labels) TileLabel(pinned.label) } AnchoredMenu(menu, onDismiss = { menu = false }, title = pinned.label, compact = true, minWidth = 180.dp) { firstItem -> MenuItem(stringResource(R.string.apps_shortcut_remove), checked = false, detail = pinned.appLabel, focusRequester = firstItem) { @@ -702,8 +792,8 @@ private fun FolderTile(entry: AppEntry.Folder, first: Boolean, onOpen: () -> Uni var menu by remember { mutableStateOf(false) } Box { TileFrame(entry.key, first, onClick = onOpen, onMenu = { menu = true }) { - FolderIcon(entry.apps, 52.dp) - TileLabel(entry.folder.name) + FolderIcon(entry.apps, AppsGrid.iconDp.dp) + if (AppsGrid.labels) TileLabel(entry.folder.name) } AnchoredMenu(menu, onDismiss = { menu = false }, title = entry.folder.name, compact = true, minWidth = 160.dp) { firstItem -> MenuItem(stringResource(R.string.apps_folder_rename), checked = false, focusRequester = firstItem) { @@ -722,7 +812,8 @@ private fun FolderTile(entry: AppEntry.Folder, first: Boolean, onOpen: () -> Uni @Composable private fun FolderSheet( folder: HomeFolders.Folder, apps: List, renameFirst: Boolean, - onLaunch: (HomeApp.LaunchableApp) -> Unit, onNewFolder: (HomeApp.LaunchableApp) -> Unit, onClose: () -> Unit, + onLaunch: (HomeApp.LaunchableApp) -> Unit, onNewFolder: (HomeApp.LaunchableApp) -> Unit, + onChangeIcon: (HomeApp.LaunchableApp) -> Unit, onClose: () -> Unit, ) { SwipeLock() val ctx = LocalContext.current @@ -779,29 +870,40 @@ private fun FolderSheet( .focusGroup() .padding(16.dp), ) { - Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth().padding(bottom = 10.dp)) { - if (renaming) Box(Modifier.weight(1f)) { + Box(contentAlignment = Alignment.Center, modifier = Modifier.fillMaxWidth().padding(bottom = 10.dp)) { + if (renaming) { AdbTextField( value = name, onValueChange = { name = it.take(40) }, label = stringResource(R.string.apps_folder_name), keyboardType = KeyboardType.Text, imeAction = ImeAction.Done, compact = true, showLabel = false, placeholder = folder.name, focusOnShow = true, onDone = { commit() }, ) } else { - Text(folder.name, fontSize = 20.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f, fill = false)) - SmallIconButton(Icons.Filled.Edit, stringResource(R.string.apps_folder_rename), tint = colors.onSurfaceVariant) { renaming = true } - Spacer(Modifier.weight(1f)) + val src = remember { MutableInteractionSource() } + val hot = rememberHot(src) + val rename = { renaming = true } + Text( + folder.name, fontSize = 20.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, + maxLines = 1, overflow = TextOverflow.Ellipsis, textAlign = TextAlign.Center, + // A faint chip at rest shows the name can be selected, now that the pencil is gone. + modifier = Modifier.clip(Shape12) + .background(if (hot) pal.signal.copy(alpha = 0.12f) else colors.onBackground.copy(alpha = 0.07f)) + .glideBorder(hot, Shape12, pal.signal) + .hoverable(src) + .clickable(interactionSource = src, indication = LocalIndication.current, onClickLabel = stringResource(R.string.apps_folder_rename), role = Role.Button, onClick = rename) + .controllerConfirm(onClick = rename) + .padding(horizontal = 14.dp, vertical = 6.dp), + ) } - SmallIconButton(Icons.Filled.Close, stringResource(R.string.common_close), tint = colors.onSurfaceVariant) { close() } } LazyVerticalGrid( - columns = GridCells.Adaptive(92.dp), + columns = GridCells.Adaptive(92.dp + AppsGrid.spacing.dp), state = grid, horizontalArrangement = Arrangement.spacedBy(10.dp), verticalArrangement = Arrangement.spacedBy(10.dp), ) { items(apps, key = { it.key }) { app -> AppTile( - app, folderId = folder.id, first = false, onLaunch = { onClose(); onLaunch(it) }, onNewFolder = onNewFolder, + app, folderId = folder.id, first = false, onLaunch = { onClose(); onLaunch(it) }, onNewFolder = onNewFolder, onChangeIcon = onChangeIcon, modifier = if (app === apps.first()) Modifier.focusRequester(firstApp) else Modifier, ) } @@ -823,7 +925,7 @@ private fun WidgetCard(w: HomeWidgets.Placed, maxWidthDp: Int) { val activity = remember(ctx) { ctx.findActivity() } Box { Box( - Modifier.size(width.dp, w.heightDp.dp) + Modifier.paneItem("widget:${w.id}").size(width.dp, w.heightDp.dp) .clip(Shape16) .background(colors.surface.copy(alpha = 0.35f)) .glideBorder(hot || menu, Shape16, pal.signal) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/AppIconPicker.kt b/app/src/main/java/com/droiddeck/launcher/ui/AppIconPicker.kt new file mode 100644 index 0000000000..a438a09130 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/AppIconPicker.kt @@ -0,0 +1,188 @@ +package com.droiddeck.launcher.ui + +import android.graphics.Bitmap +import android.util.LruCache +import androidx.activity.compose.BackHandler +import androidx.compose.foundation.Image +import androidx.compose.foundation.LocalIndication +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.focusGroup +import androidx.compose.foundation.hoverable +import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.imePadding +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.lazy.grid.GridCells +import androidx.compose.foundation.lazy.grid.GridItemSpan +import androidx.compose.foundation.lazy.grid.LazyVerticalGrid +import androidx.compose.foundation.lazy.grid.items +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.produceState +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.ExperimentalComposeUiApi +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.focus.FocusDirection +import androidx.compose.ui.focus.FocusRequester +import androidx.compose.ui.focus.focusProperties +import androidx.compose.ui.focus.focusRequester +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.asImageBitmap +import androidx.compose.ui.input.InputMode +import androidx.compose.ui.layout.ContentScale +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.platform.LocalInputModeManager +import androidx.compose.ui.res.stringResource +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 androidx.core.graphics.drawable.toBitmap +import com.droiddeck.launcher.HomeApp +import com.droiddeck.launcher.HomeIcons +import com.droiddeck.launcher.IconPack +import com.droiddeck.launcher.R +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext + +private val CELL_ICON = 44.dp + +@OptIn(ExperimentalComposeUiApi::class) +private fun Modifier.focusTrap(): Modifier = focusProperties { + exit = { dir -> + if (dir == FocusDirection.Up || dir == FocusDirection.Down || dir == FocusDirection.Left || dir == FocusDirection.Right) FocusRequester.Cancel + else FocusRequester.Default + } +}.focusGroup() + +private fun normalized(text: String) = text.lowercase().filter { it.isLetterOrDigit() } + +internal fun iconMatches(names: List, label: String, query: String): List { + val q = normalized(query) + if (q.isNotEmpty()) return names.filter { q in normalized(it) } + val hint = normalized(label) + val (likely, rest) = names.partition { hint in normalized(it) } + return likely + rest +} + +@Composable +internal fun AppIconPicker(app: HomeApp.LaunchableApp, padH: androidx.compose.ui.unit.Dp, onClose: () -> Unit) { + SwipeLock() + val ctx = LocalContext.current + val colors = MaterialTheme.colorScheme + val pack = remember { IconPack.selected(ctx) } + val names by produceState?>(null, pack) { value = withContext(Dispatchers.IO) { IconPack.names(ctx, pack) } } + var query by remember { mutableStateOf("") } + val shown = remember(names, query) { names?.let { iconMatches(it, app.label, query) } } + val cache = remember { LruCache(256) } + val inputMode = LocalInputModeManager.current.inputMode + val ff = LocalFrontFocus.current + val first = remember { FocusRequester() } + var closing by remember { mutableStateOf(false) } + val close = { + closing = true + onClose() + if (inputMode == InputMode.Keyboard && ff != null) { + runCatching { ff.items.getValue("tile:${app.key}").requestFocus() } + .onFailure { runCatching { ff.firstTile.requestFocus() } } + } + } + LaunchedEffect(names != null, inputMode) { + if (names != null && !closing && inputMode == InputMode.Keyboard) { + repeat(2) { androidx.compose.runtime.withFrameNanos { } } + ff?.last = "icon:${shown?.firstOrNull()}" + if (!closing) runCatching { first.requestFocus() } + } + } + BackHandler { close() } + Column( + Modifier.fillMaxSize().imePadding().background(colors.background) + .blockTouches() + .focusTrap(), + ) { + val title = stringResource(R.string.touch_icon_for, app.label) + Box(Modifier.fillMaxWidth().padding(start = padH, end = padH, top = 8.dp)) { + ModeHeader( + title, query, { query = it }, placeholder = stringResource(R.string.apps_icons_search), + lead = { + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) { + BackLink(stringResource(R.string.rail_apps), compact = true, onClick = close) + Text(title, fontSize = 15.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis) + } + }, + inlineWhenStacked = true, + ) { } + } + LazyVerticalGrid( + columns = GridCells.Adaptive(64.dp), + horizontalArrangement = Arrangement.spacedBy(4.dp), + verticalArrangement = Arrangement.spacedBy(4.dp), + contentPadding = PaddingValues(horizontal = padH, vertical = 8.dp), + modifier = Modifier.fillMaxSize(), + ) { + when { + shown == null -> item(key = "loading", span = { GridItemSpan(maxLineSpan) }) { Note(stringResource(R.string.apps_icons_loading)) } + shown.isEmpty() -> item(key = "none", span = { GridItemSpan(maxLineSpan) }) { Note(stringResource(R.string.apps_icons_none)) } + else -> items(shown, key = { it }) { name -> + PackIconCell( + pack, name, cache, + modifier = if (name == shown.first()) Modifier.focusRequester(first) else Modifier, + ) { + HomeIcons.set(ctx, app.key, pack, name) + close() + } + } + } + } + } +} + +@Composable +private fun PackIconCell( + pack: String, name: String, cache: LruCache, modifier: Modifier, onPick: () -> Unit, +) { + val ctx = LocalContext.current + val iconPx = with(LocalDensity.current) { CELL_ICON.roundToPx() } + val bitmap by produceState(cache.get(name), name) { + if (value == null) value = withContext(Dispatchers.IO) { + runCatching { IconPack.drawable(ctx, pack, name, ctx.resources.displayMetrics.densityDpi)?.toBitmap(iconPx, iconPx) }.getOrNull()?.also { cache.put(name, it) } + } + } + val pal = LocalPalette.current + val src = remember { MutableInteractionSource() } + val hot = rememberHot(src) + Box( + contentAlignment = Alignment.Center, + modifier = modifier.fillMaxWidth().paneItem("icon:$name").clip(Shape12) + .background(if (hot) pal.signal.copy(alpha = 0.14f) else Color.Transparent) + .glideBorder(hot, Shape12, pal.signal) + .hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Button, onClick = onPick) + .controllerConfirm(onClick = onPick) + .semantics { contentDescription = name.replace('_', ' ') } + .padding(10.dp), + ) { + val icon = bitmap + if (icon != null) Image(icon.asImageBitmap(), null, contentScale = ContentScale.Fit, modifier = Modifier.size(CELL_ICON)) + else Spacer(Modifier.size(CELL_ICON)) + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/AppsAppearance.kt b/app/src/main/java/com/droiddeck/launcher/ui/AppsAppearance.kt new file mode 100644 index 0000000000..e04ff0d613 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/AppsAppearance.kt @@ -0,0 +1,120 @@ +package com.droiddeck.launcher.ui + +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Palette +import androidx.compose.material3.Icon +import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.produceState +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.focus.focusRequester +import androidx.compose.ui.geometry.Rect +import androidx.compose.ui.layout.boundsInRoot +import androidx.compose.ui.layout.onGloballyPositioned +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.unit.dp +import com.droiddeck.launcher.HomeIcons +import com.droiddeck.launcher.IconPack +import com.droiddeck.launcher.R +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext + +private val PanelWidth = 348.dp +private val PanelHeight = 316.dp +private val TabsWidth = 204.dp + +@Composable +internal fun AppsAppearanceButton(a: FrontEndActions) { + val pal = LocalPalette.current + val title = stringResource(R.string.apps_appearance) + var at by remember { mutableStateOf(null) } + Box(Modifier.onGloballyPositioned { at = it.boundsInRoot() }) { + HeaderIconButton(title, Icons.Filled.Palette, "apps-appearance") { + val from = at ?: return@HeaderIconButton + Steps.ask(StepAsk( + anchor = from, side = StepSide.Left, accent = pal.signal, pillCorner = 8.dp, items = 2, maxWidth = PanelWidth, + handle = { Icon(Icons.Filled.Palette, null, tint = pal.signal, modifier = Modifier.size(18.dp)) }, + ) { + StepTitle(title) + Column( + Modifier.stepItem(1).fillMaxWidth().height(minOf(PanelHeight, (maxHeight - 64.dp).coerceAtLeast(44.dp))).verticalScroll(rememberScrollState()), + ) { AppearanceRows(a) } + }) + } + } +} + +@Composable +private fun StepOutScope.AppearanceRows(a: FrontEndActions) { + val ctx = LocalContext.current + val host = rememberMenuHost() + var packsOpen by remember { mutableStateOf(false) } + var selected by remember { mutableStateOf(IconPack.selected(ctx)) } + var appColors by remember { mutableStateOf(IconPack.appColors(ctx)) } + val installed by produceState(emptyList()) { + value = withContext(Dispatchers.IO) { runCatching { IconPack.installed(ctx) }.getOrDefault(emptyList()) } + } + val hasBack by produceState(false, selected) { value = withContext(Dispatchers.IO) { IconPack.active(ctx)?.hasBack == true } } + CompositionLocalProvider(LocalCompactSettings provides true) { + val packs = listOf(IconPack.Pack(IconPack.NONE, stringResource(R.string.apps_icon_pack_system))) + installed + val current = packs.find { it.packageName == selected } ?: packs.first() + Box(Modifier.focusRequester(first)) { + LinkRow( + stringResource(R.string.apps_icon_pack), current.label, "", "icon-pack", + arrow = if (packsOpen) "โ–ด" else "โ–พ", + ) { packsOpen = !packsOpen } + } + if (packsOpen) packs.forEach { (value, text) -> + MenuItem(text, checked = value == current.packageName) { + selected = value + IconPack.select(ctx, value) + a.onAppIconsChanged() + packsOpen = false + runCatching { first.requestFocus() } + } + } + SettingsRow(stringResource(R.string.apps_icon_size), null) { + SegmentedTabs( + listOf( + AppsGrid.SMALL to stringResource(R.string.apps_icon_small), + AppsGrid.MEDIUM to stringResource(R.string.apps_icon_medium), + AppsGrid.LARGE to stringResource(R.string.apps_icon_large), + ), + AppsGrid.iconDp, Modifier.width(TabsWidth), + ) { AppsGrid.setIconDp(ctx, it) } + } + SettingsRow(stringResource(R.string.apps_spacing), null) { + SegmentedTabs( + listOf( + AppsGrid.TIGHT to stringResource(R.string.apps_spacing_tight), + AppsGrid.NORMAL to stringResource(R.string.apps_spacing_normal), + AppsGrid.ROOMY to stringResource(R.string.apps_spacing_roomy), + ), + AppsGrid.spacing, Modifier.width(TabsWidth), + ) { AppsGrid.setSpacing(ctx, it) } + } + ToggleRow(host, "app-names", stringResource(R.string.apps_hide_names), null, !AppsGrid.labels) { AppsGrid.setLabels(ctx, !it) } + if (hasBack) ToggleRow(host, "app-colors", stringResource(R.string.apps_icon_app_colors), null, appColors) { + appColors = it + IconPack.setAppColors(ctx, it) + a.onAppIconsChanged() + } + if (HomeIcons.overrides.isNotEmpty()) ActionRow(stringResource(R.string.apps_icons_custom), null, stringResource(R.string.ctrl_reset), { + HomeIcons.clearAll(ctx) + runCatching { first.requestFocus() } + }) + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/BottomStrip.kt b/app/src/main/java/com/droiddeck/launcher/ui/BottomStrip.kt index 3df2090bc4..60844df4de 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/BottomStrip.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/BottomStrip.kt @@ -14,7 +14,6 @@ import androidx.compose.ui.platform.LocalContext import com.droiddeck.launcher.hud.DroidDeckHudConfig import com.droiddeck.launcher.hud.FrameStats import com.droiddeck.launcher.hud.GameFrameFeed -import com.droiddeck.launcher.hud.HudFrames import com.droiddeck.launcher.hud.HudMetrics import com.droiddeck.launcher.hud.KeyValueSet import com.droiddeck.launcher.hud.MangoReadings @@ -34,7 +33,7 @@ private const val STRIP_TEMP_PLAIN = 0xFFF2F5F9.toInt() @Composable internal fun SessionBottomStrip(pageId: String?, fps: () -> Float?) { val context = LocalContext.current - val frames = remember { GameFrameFeed(File(LinuxRuntime.rootDir(context), HudFrames.PATH)) } + val frames = remember { GameFrameFeed.forRoot(LinuxRuntime.rootDir(context)) } DisposableEffect(frames) { onDispose { frames.close() } } val page by rememberUpdatedState(pageId) var frameTick by remember { mutableIntStateOf(0) } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/BottomTelemetryPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/BottomTelemetryPage.kt index 08b4ae8ada..4c454b52d1 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/BottomTelemetryPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/BottomTelemetryPage.kt @@ -55,7 +55,6 @@ import com.droiddeck.launcher.hud.DroidDeckHudConfig import com.droiddeck.launcher.hud.DroidDeckHudHost import com.droiddeck.launcher.hud.FrameStats import com.droiddeck.launcher.hud.GameFrameFeed -import com.droiddeck.launcher.hud.HudFrames import com.droiddeck.launcher.hud.HudMetrics import com.droiddeck.launcher.hud.KeyValueSet import com.droiddeck.launcher.hud.MangoReadings @@ -144,7 +143,7 @@ fun BottomTelemetryPage(fps: () -> Float?, runningGame: () -> String? = { null } var perfTick by remember { mutableIntStateOf(0) } var traceTick by remember { mutableIntStateOf(0) } var clock by remember { mutableStateOf("") } - val frames = remember { GameFrameFeed(File(LinuxRuntime.rootDir(context), HudFrames.PATH)) } + val frames = remember { GameFrameFeed.forRoot(LinuxRuntime.rootDir(context)) } DisposableEffect(frames) { onDispose { frames.close() } } val currentFps = { if (frames.live) frames.stats.fps else fps() } var hud by remember { mutableStateOf(StatsHud.from(SessionPrefs.statsHud(context))) } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/BuildWatermark.kt b/app/src/main/java/com/droiddeck/launcher/ui/BuildWatermark.kt index a9d0c3d1a2..446420806c 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/BuildWatermark.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/BuildWatermark.kt @@ -2,7 +2,12 @@ package com.droiddeck.launcher.ui import android.app.Activity import android.app.Application +import android.content.BroadcastReceiver +import android.content.Intent +import android.content.IntentFilter import android.content.Context +import androidx.core.content.ContextCompat +import com.droiddeck.launcher.session.BuildWatermarkSetting import android.graphics.Canvas import android.graphics.Paint import android.graphics.Typeface @@ -14,11 +19,14 @@ import android.view.Gravity import android.view.View import android.view.ViewGroup import android.widget.FrameLayout +import java.util.WeakHashMap import com.droiddeck.launcher.BuildConfig import com.droiddeck.launcher.QuestXrActivity object BuildWatermark { private const val TITLE_LIMIT = 80 + private val activities = WeakHashMap() + internal var lineProvider: () -> List? = { lines() } fun lines( pr: Int = BuildConfig.PR_NUMBER, @@ -38,33 +46,56 @@ object BuildWatermark { if (text.length <= TITLE_LIMIT) text else text.take(TITLE_LIMIT - 1).trimEnd() + "โ€ฆ" fun install(app: Application) { - val lab = com.droiddeck.launcher.lab.LabOverlay.active?.let { "LAB | ${truncate(it.label)}" } - val lines = (listOfNotNull(lab) + lines().orEmpty()).ifEmpty { return } + ContextCompat.registerReceiver( + app, + object : BroadcastReceiver() { + override fun onReceive(context: Context, intent: Intent) { refresh(context) } + }, + IntentFilter(BuildWatermarkSetting.CHANGED), + "${app.packageName}.DYNAMIC_RECEIVER_NOT_EXPORTED_PERMISSION", + null, + ContextCompat.RECEIVER_NOT_EXPORTED, + ) app.registerActivityLifecycleCallbacks(object : Application.ActivityLifecycleCallbacks { override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) { if (activity is QuestXrActivity) return - val decor = activity.window.decorView as? ViewGroup ?: return - if (decor.findViewWithTag(TAG) != null) return - val margin = (8 * activity.resources.displayMetrics.density).toInt() - decor.addView( - MarkView(activity, lines).apply { tag = TAG }, - FrameLayout.LayoutParams( - ViewGroup.LayoutParams.WRAP_CONTENT, - ViewGroup.LayoutParams.WRAP_CONTENT, - Gravity.BOTTOM or Gravity.END, - ).apply { setMargins(margin, margin, margin, margin) }, - ) + synchronized(activities) { activities[activity] = Unit } + update(activity) } override fun onActivityStarted(activity: Activity) = Unit - override fun onActivityResumed(activity: Activity) = Unit + override fun onActivityResumed(activity: Activity) { update(activity) } override fun onActivityPaused(activity: Activity) = Unit override fun onActivityStopped(activity: Activity) = Unit override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) = Unit - override fun onActivityDestroyed(activity: Activity) = Unit + override fun onActivityDestroyed(activity: Activity) { synchronized(activities) { activities.remove(activity) } } }) } + fun refresh(context: Context) { + val current = synchronized(activities) { activities.keys.toList() } + current.forEach(::update) + } + + private fun update(activity: Activity) { + if (activity is QuestXrActivity) return + val decor = activity.window.decorView as? ViewGroup ?: return + decor.findViewWithTag(TAG)?.let(decor::removeView) + if (!com.droiddeck.launcher.session.SessionPrefs.buildWatermarkEnabled(activity)) return + val lab = com.droiddeck.launcher.lab.LabOverlay.active?.let { "LAB | ${truncate(it.label)}" } + val build = lineProvider().orEmpty() + val content = (listOfNotNull(lab) + build).ifEmpty { return } + val margin = (8 * activity.resources.displayMetrics.density).toInt() + decor.addView( + MarkView(activity, content).apply { tag = TAG }, + FrameLayout.LayoutParams( + ViewGroup.LayoutParams.WRAP_CONTENT, + ViewGroup.LayoutParams.WRAP_CONTENT, + Gravity.BOTTOM or Gravity.END, + ).apply { setMargins(margin, margin, margin, margin) }, + ) + } + private const val TAG = "build-watermark" private class MarkView(context: Context, private val lines: List) : View(context) { diff --git a/app/src/main/java/com/droiddeck/launcher/ui/DeeDee.kt b/app/src/main/java/com/droiddeck/launcher/ui/DeeDee.kt new file mode 100644 index 0000000000..c2632915fc --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/DeeDee.kt @@ -0,0 +1,381 @@ +package com.droiddeck.launcher.ui + +import androidx.compose.animation.core.CubicBezierEasing +import androidx.compose.animation.core.Easing +import androidx.compose.foundation.Canvas +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.produceState +import androidx.compose.runtime.withFrameNanos +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.Color +import androidx.compose.ui.graphics.Path +import androidx.compose.ui.graphics.PathOperation +import androidx.compose.ui.graphics.StrokeCap +import androidx.compose.ui.graphics.drawscope.DrawScope +import androidx.compose.ui.graphics.drawscope.Stroke +import androidx.compose.ui.graphics.drawscope.rotate +import androidx.compose.ui.graphics.drawscope.scale +import androidx.compose.ui.graphics.drawscope.translate +import androidx.compose.ui.graphics.drawscope.withTransform +import androidx.compose.ui.text.TextStyle +import androidx.compose.ui.text.drawText +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.rememberTextMeasurer +import kotlin.math.PI + +internal enum class PetState { IDLE, WORKING, QUESTION, DONE, ERROR, SLEEP } + +private val White = Color(0xFFFFFFFF) +private val Blue = Color(0xFF1A9FFF) +private val Ink = Color(0xFF0E141B) +private val Amber = Color(0xFFFFB627) +private val Red = Color(0xFFFF5A5F) +private val Slate = Color(0xFF3A4A5A) +private val Term = Color(0xFF26303B) +private val TermLine = Color(0xFF8FA3B6) + +private val EaseInOut: Easing = CubicBezierEasing(0.42f, 0f, 0.58f, 1f) +private val EaseOut: Easing = CubicBezierEasing(0f, 0f, 0.58f, 1f) +private val Hop: Easing = CubicBezierEasing(0.3f, 0f, 0.4f, 1f) +private val Pop: Easing = CubicBezierEasing(0.3f, 1.6f, 0.5f, 1f) +private val Linear = Easing { it } +private val Step = Easing { 0f } + +/** Where 0..1 of a loop [period] seconds long is at [time]; [lead] starts it that many seconds early. */ +private fun loop(time: Float, period: Float, lead: Float = 0f): Float { + val t = (time + lead) % period + return (if (t < 0) t + period else t) / period +} + +/** A CSS-style keyframe track: [stops] holds (position, value) pairs, eased per segment. */ +private fun track(p: Float, easing: Easing, vararg stops: Float): Float { + if (p <= stops[0]) return stops[1] + var i = 0 + while (i + 2 < stops.size) { + val a = stops[i] + val b = stops[i + 2] + if (p <= b) { + val t = if (b > a) (p - a) / (b - a) else 1f + return stops[i + 1] + (stops[i + 3] - stops[i + 1]) * easing.transform(t) + } + i += 2 + } + return stops[stops.size - 1] +} + +private fun mix(a: Color, b: Color, t: Float) = Color( + a.red + (b.red - a.red) * t, a.green + (b.green - a.green) * t, a.blue + (b.blue - a.blue) * t, a.alpha + (b.alpha - a.alpha) * t, +) + +/** The DroidDeck mark the head is drawn from, in its own 128 by 223.72 space. */ +private val headMark: Path by lazy { + val d = Path().apply { + moveTo(-31.98f, 0f) + lineTo(63.97f, 0f) + cubicTo(125.81f, 0f, 175.93f, 50.08f, 175.93f, 111.86f) + cubicTo(175.93f, 173.64f, 125.81f, 223.72f, 63.97f, 223.72f) + lineTo(-31.98f, 223.72f) + close() + } + val cut = Path().apply { + addOval(Rect(Offset(63.98f, 111.86f), 71.81f)) + addRect(Rect(56.055f, 0f, 56.055f + 15.83f, 45f)) + addRect(Rect(56.055f, 178.72f, 56.055f + 15.83f, 223.72f)) + } + Path.combine(PathOperation.Difference, d, cut) +} + +private fun star(x: Float, y: Float, a: Float) = Path().apply { + moveTo(x, y - a) + quadraticBezierTo(x, y, x + a, y) + quadraticBezierTo(x, y, x, y + a) + quadraticBezierTo(x, y, x - a, y) + quadraticBezierTo(x, y, x, y - a) + close() +} + +private class Spark(val x: Float, val y: Float, val size: Float, val color: Color, val lead: Float) + +private val sparks = listOf( + Spark(90f, 120f, 14f, White, 0f), Spark(318f, 110f, 12f, Blue, 0.4f), Spark(104f, 210f, 9f, Blue, 0.8f), + Spark(312f, 200f, 10f, White, 0.4f), Spark(250f, 40f, 8f, White, 0f), +).map { it to star(it.x, it.y, it.size) } + +/** The rig of the DeeDee mock (a 400 by 360 view box) looping through [state]; [crop] is the part of the view box shown. */ +@Composable +internal fun DeeDee(state: PetState, modifier: Modifier, crop: Rect = Rect(35f, 15f, 365f, 345f)) { + val time by produceState(0f) { + val start = withFrameNanos { it } + while (true) withFrameNanos { value = (it - start) / 1_000_000_000f } + } + val text = rememberTextMeasurer() + Canvas(modifier) { + val k = minOf(size.width / crop.width, size.height / crop.height) + withTransform({ + translate((size.width - crop.width * k) / 2, (size.height - crop.height * k) / 2) + scale(k, k, Offset.Zero) + translate(-crop.left, -crop.top) + }) { rig(state, time, text) } + } +} + +private fun DrawScope.rig(state: PetState, t: Float, text: androidx.compose.ui.text.TextMeasurer) { + // Shadow under the feet. + var shadowX = 1f + var shadowAlpha = 0.4f + when (state) { + PetState.IDLE -> shadowX = track(loop(t, 3f), EaseInOut, 0f, 1f, 0.5f, 0.9f, 1f, 1f) + PetState.DONE -> { + val p = loop(t, 1.2f) + shadowX = track(p, Hop, 0f, 1f, 0.15f, 1f, 0.45f, 0.7f, 0.75f, 1f, 1f, 1f) + shadowAlpha = track(p, Hop, 0f, 0.4f, 0.15f, 0.4f, 0.45f, 0.2f, 0.75f, 0.4f, 1f, 0.4f) + } + else -> Unit + } + scale(shadowX, 1f, Offset(200f, 336f)) { + drawOval(Color.Black.copy(alpha = shadowAlpha), Offset(130f, 327f), Size(140f, 18f)) + } + + // The whole body moves together. + var dx = 0f + var dy = 0f + var sx = 1f + var sy = 1f + when (state) { + PetState.IDLE -> dy = track(loop(t, 3f), EaseInOut, 0f, 0f, 0.5f, -6f, 1f, 0f) + PetState.WORKING -> dy = track(loop(t, 1.6f), EaseInOut, 0f, 0f, 0.5f, -2f, 1f, 0f) + PetState.QUESTION -> dy = track(loop(t, 2.4f), EaseInOut, 0f, 0f, 0.5f, -4f, 1f, 0f) + PetState.DONE -> { + val p = loop(t, 1.2f) + dy = track(p, Hop, 0f, 0f, 0.15f, 0f, 0.45f, -30f, 0.75f, 0f, 1f, 0f) + sx = track(p, Hop, 0f, 1.03f, 0.15f, 1f, 0.75f, 1f, 0.85f, 1.04f, 1f, 1.03f) + sy = track(p, Hop, 0f, 0.96f, 0.15f, 1f, 0.75f, 1f, 0.85f, 0.95f, 1f, 0.96f) + } + PetState.ERROR -> dx = track(loop(t, 2f), EaseInOut, 0f, 0f, 0.04f, -7f, 0.08f, 7f, 0.12f, -5f, 0.16f, 5f, 0.2f, -2f, 0.24f, 2f, 0.3f, 0f, 1f, 0f) + PetState.SLEEP -> { + val p = loop(t, 4f) + sx = track(p, EaseInOut, 0f, 1f, 0.5f, 1.02f, 1f, 1f) + sy = track(p, EaseInOut, 0f, 1f, 0.5f, 0.97f, 1f, 1f) + } + } + val alarm = if (state == PetState.ERROR) track(loop(t, 2f), EaseInOut, 0f, 0f, 0.04f, 1f, 0.24f, 1f, 0.3f, 0f, 1f, 0f) else 0f + withTransform({ + translate(dx, dy) + scale(sx, sy, Offset(200f, 317f)) + }) { + legs() + body(state, t, alarm) + if (state == PetState.WORKING) terminal(t) + arms(state, t) + head(state, t, alarm) + } + extras(state, t, text) +} + +private fun DrawScope.legs() { + for ((x, y, w, h, r) in listOf( + floatArrayOf(166f, 283f, 18f, 30f, 8f), floatArrayOf(216f, 283f, 18f, 30f, 8f), + floatArrayOf(158f, 305f, 30f, 12f, 6f), floatArrayOf(212f, 305f, 30f, 12f, 6f), + )) drawRoundRect(White, Offset(x, y), Size(w, h), CornerRadius(r)) +} + +private operator fun FloatArray.component5() = this[4] + +private fun DrawScope.body(state: PetState, t: Float, alarm: Float) { + drawRect(White, Offset(194f, 200f), Size(12f, 20f)) + drawRoundRect(White, Offset(148f, 215f), Size(104f, 72f), CornerRadius(22f)) + val glow = when (state) { + PetState.WORKING -> track(loop(t, 0.8f), EaseInOut, 0f, 1f, 0.5f, 0.5f, 1f, 1f) + PetState.SLEEP -> track(loop(t, 4f), EaseInOut, 0f, 0.35f, 0.5f, 0.8f, 1f, 0.35f) + else -> 1f + } + drawCircle(mix(Blue, Red, alarm).copy(alpha = glow), 11f, Offset(200f, 251f)) +} + +private fun DrawScope.terminal(t: Float) { + drawRoundRect(Term, Offset(150f, 256f), Size(100f, 40f), CornerRadius(8f)) + drawRoundRect(Blue, Offset(150f, 256f), Size(100f, 40f), CornerRadius(8f), style = Stroke(3f)) + drawRoundRect(Blue, Offset(160f, 266f), Size(44f, 5f), CornerRadius(2.5f)) + val grow = track(loop(t, 1.6f), EaseOut, 0f, 0.1f, 0.7f, 1f, 1f, 1f) + scale(grow, 1f, Offset(160f, 278f)) { drawRoundRect(TermLine, Offset(160f, 276f), Size(60f, 5f), CornerRadius(2.5f)) } + val cursor = track(loop(t, 0.7f), Step, 0f, 1f, 0.5f, 0.2f, 1f, 0.2f) + drawRoundRect(White.copy(alpha = cursor), Offset(224f, 276f), Size(10f, 5f), CornerRadius(2f)) +} + +/** One arm: from the shoulder through a curve to the hand, turned about the shoulder. */ +private fun DrawScope.arm(shoulder: Offset, control: Offset, hand: Offset, degrees: Float) { + rotate(degrees, shoulder) { + val path = Path().apply { + moveTo(shoulder.x, shoulder.y) + quadraticBezierTo(control.x, control.y, hand.x, hand.y) + } + drawPath(path, White, style = Stroke(10f, cap = StrokeCap.Round)) + drawCircle(White, 9f, hand) + } +} + +private fun DrawScope.arms(state: PetState, t: Float) { + val l = Offset(151f, 236f) + val r = Offset(249f, 236f) + when (state) { + PetState.IDLE -> { + val sway = track(loop(t, 3f), EaseInOut, 0f, 0f, 0.5f, 4f, 1f, 0f) + arm(l, Offset(127f, 246f), Offset(123f, 276f), sway) + arm(r, Offset(273f, 246f), Offset(277f, 276f), sway) + } + PetState.WORKING -> { + val p = loop(t, 0.32f) + arm(l, Offset(133f, 258f), Offset(157f, 270f), track(p, EaseInOut, 0f, 0f, 0.5f, -6f, 1f, 0f)) + arm(r, Offset(267f, 258f), Offset(243f, 270f), track(p, EaseInOut, 0f, -5f, 0.5f, 1f, 1f, -5f)) + } + PetState.QUESTION -> { + arm(l, Offset(127f, 246f), Offset(123f, 276f), 0f) + arm(r, Offset(279f, 230f), Offset(287f, 198f), track(loop(t, 0.9f), EaseInOut, 0f, -8f, 0.5f, 14f, 1f, -8f)) + } + PetState.DONE -> { + val p = loop(t, 1.2f) + arm(l, Offset(121f, 230f), Offset(115f, 196f), track(p, EaseInOut, 0f, 0f, 0.45f, 12f, 1f, 0f)) + arm(r, Offset(279f, 230f), Offset(285f, 196f), track(p, EaseInOut, 0f, 0f, 0.45f, -12f, 1f, 0f)) + } + PetState.ERROR, PetState.SLEEP -> { + arm(Offset(151f, 238f), Offset(137f, 254f), Offset(135f, 284f), 0f) + arm(Offset(249f, 238f), Offset(263f, 254f), Offset(265f, 284f), 0f) + } + } +} + +private fun DrawScope.head(state: PetState, t: Float, alarm: Float) { + val tilt = when (state) { + PetState.QUESTION -> track(loop(t, 2.4f), EaseInOut, 0f, -9f, 0.5f, -5f, 1f, -9f) + PetState.SLEEP -> 6f + else -> 0f + } + withTransform({ + rotate(tilt, Offset(200f, 215f)) + if (state == PetState.SLEEP) translate(0f, 6f) + }) { + antenna(state, t) + withTransform({ + translate(200f, 150f) + scale(0.62f, 0.62f, Offset.Zero) + translate(-64f, -111.86f) + }) { + drawPath(headMark, White) + drawCircle(mix(Blue, Red, alarm).copy(alpha = if (state == PetState.SLEEP) 0.6f else 1f), 55.98f, Offset(63.98f, 111.86f)) + } + eye(state, t) + if (state == PetState.WORKING) { + val sweep = 46f / (2f * PI.toFloat() * 39.6f) * 360f + rotate(360f * loop(t, 1.1f), Offset(200f, 150f)) { + drawArc(Blue, 0f, sweep, false, Offset(160.4f, 110.4f), Size(79.2f, 79.2f), style = Stroke(5f, cap = StrokeCap.Round)) + } + } + } +} + +private fun DrawScope.antenna(state: PetState, t: Float) { + val lean = when (state) { + PetState.ERROR -> 22f + PetState.SLEEP -> -28f + else -> 0f + } + rotate(lean, Offset(200f, 100f)) { + drawLine(White, Offset(200f, 100f), Offset(200f, 52f), 7f, StrokeCap.Round) + var radius = 10f + val (color, alpha) = when (state) { + PetState.IDLE -> Blue to track(loop(t, 3f), EaseInOut, 0f, 1f, 0.5f, 0.45f, 1f, 1f) + PetState.WORKING -> Blue to track(loop(t, 0.5f), Step, 0f, 1f, 0.5f, 0.2f, 1f, 0.2f) + PetState.QUESTION -> { + val p = loop(t, 1f) + radius = track(p, EaseInOut, 0f, 10f, 0.5f, 13f, 1f, 10f) + Amber to track(p, EaseInOut, 0f, 1f, 0.5f, 0.5f, 1f, 1f) + } + PetState.DONE -> Blue to 1f + PetState.ERROR -> Red to track(loop(t, 1f), Step, 0f, 1f, 0.5f, 0.25f, 1f, 0.25f) + PetState.SLEEP -> Slate to 1f + } + drawCircle(color.copy(alpha = alpha), radius, Offset(200f, 45f)) + } +} + +private fun DrawScope.eye(state: PetState, t: Float) { + when (state) { + PetState.DONE -> drawPath(Path().apply { moveTo(186f, 156f); quadraticBezierTo(203f, 136f, 220f, 156f) }, Ink, style = Stroke(7f, cap = StrokeCap.Round)) + PetState.SLEEP -> drawPath(Path().apply { moveTo(186f, 152f); quadraticBezierTo(203f, 162f, 220f, 152f) }, Ink, style = Stroke(6f, cap = StrokeCap.Round)) + PetState.ERROR -> { + val stroke = 6f + drawLine(Ink, Offset(193f, 139f), Offset(215f, 161f), stroke, StrokeCap.Round) + drawLine(Ink, Offset(215f, 139f), Offset(193f, 161f), stroke, StrokeCap.Round) + } + else -> { + val blink = if (state == PetState.IDLE) track(loop(t, 4.5f), EaseInOut, 0f, 1f, 0.44f, 1f, 0.47f, 0.1f, 0.5f, 1f, 1f, 1f) else 1f + val (px, py) = when (state) { + PetState.IDLE -> track(loop(t, 9f), EaseInOut, 0f, 0f, 0.3f, 0f, 0.36f, -7f, 0.52f, -7f, 0.58f, 5f, 0.8f, 5f, 0.86f, 0f, 1f, 0f) to 0f + PetState.WORKING -> track(loop(t, 1.6f), EaseInOut, 0f, -7f, 0.5f, 6f, 1f, -7f) to 0f + else -> 5f to -5f + } + scale(1f, blink, Offset(204f, 149f)) { + translate(px, py) { + drawCircle(Ink, 16f, Offset(204f, 149f)) + drawCircle(White, 5f, Offset(210f, 143f)) + drawCircle(White.copy(alpha = 0.7f), 2.2f, Offset(199f, 155f)) + } + } + } + } +} + +private fun DrawScope.speechTail(color: Color) { + drawPath(Path().apply { moveTo(264f, 82f); lineTo(254f, 100f); lineTo(278f, 86f); close() }, color) +} + +private fun DrawScope.extras(state: PetState, t: Float, text: androidx.compose.ui.text.TextMeasurer) { + when (state) { + PetState.QUESTION -> { + val p = loop(t, 2.4f) + val s = track(p, Pop, 0f, 0.4f, 0.12f, 1f, 0.88f, 1f, 1f, 0.9f) + val a = track(p, Pop, 0f, 0f, 0.12f, 1f, 0.88f, 1f, 1f, 0f).coerceIn(0f, 1f) + scale(s, s, Offset(262f, 96f)) { + drawRoundRect(Amber.copy(alpha = a), Offset(254f, 30f), Size(62f, 58f), CornerRadius(18f)) + speechTail(Amber.copy(alpha = a)) + val mark = text.measure("?", TextStyle(color = Ink.copy(alpha = a), fontSize = 42f.toSp(), fontWeight = FontWeight.Bold)) + drawText(mark, topLeft = Offset(285f - mark.size.width / 2f, 74f - mark.firstBaseline)) + } + } + PetState.ERROR -> { + val nudge = track(loop(t, 2f), EaseInOut, 0f, 0f, 0.06f, -10f, 0.14f, 8f, 0.22f, -4f, 0.3f, 0f, 1f, 0f) + rotate(nudge, Offset(262f, 96f)) { + drawRoundRect(Red, Offset(254f, 34f), Size(54f, 54f), CornerRadius(16f)) + speechTail(Red) + drawRoundRect(White, Offset(277f, 44f), Size(8f, 24f), CornerRadius(4f)) + drawCircle(White, 5f, Offset(281f, 77f)) + } + } + PetState.DONE -> for ((spark, path) in sparks) { + val p = loop(t, 1.2f, spark.lead) + val s = track(p, EaseInOut, 0f, 0f, 0.4f, 1f, 0.7f, 0.6f, 1f, 0f) + val turn = track(p, EaseInOut, 0f, 0f, 0.4f, 45f, 0.7f, 90f, 1f, 0f) + val a = track(p, EaseInOut, 0f, 0f, 0.4f, 1f, 0.7f, 0.8f, 1f, 0f) + if (s <= 0.01f) continue + withTransform({ + rotate(turn, Offset(spark.x, spark.y)) + scale(s, s, Offset(spark.x, spark.y)) + }) { drawPath(path, spark.color.copy(alpha = a)) } + } + PetState.SLEEP -> for ((i, z) in listOf(Triple(250f, 96f, 22f), Triple(268f, 74f, 30f), Triple(286f, 52f, 38f)).withIndex()) { + val p = loop(t, 4f, -1.3f * i) + val a = track(p, EaseOut, 0f, 0f, 0.2f, 1f, 1f, 0f) + val zx = track(p, EaseOut, 0f, -10f, 1f, 14f) + val zy = track(p, EaseOut, 0f, 16f, 1f, -22f) + val glyph = text.measure("z", TextStyle(color = White.copy(alpha = a), fontSize = z.third.toSp(), fontWeight = FontWeight.Bold)) + // The view box places a glyph by its baseline. + drawText(glyph, topLeft = Offset(z.first + zx, z.second + zy - glyph.firstBaseline)) + } + else -> Unit + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/DualScreenPanel.kt b/app/src/main/java/com/droiddeck/launcher/ui/DualScreenPanel.kt index b46afbb977..df4e4a8d1b 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/DualScreenPanel.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/DualScreenPanel.kt @@ -59,6 +59,8 @@ class DualPanelModel( val appScale: Int, val onSelect: (String) -> Unit, val onResume: () -> Unit, + val title: String = selected, + val moreDownloads: Int = 0, ) object DualScreenPanel { @@ -322,7 +324,7 @@ internal fun DualPanelContent(model: DualPanelModel) { Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) { Text(stringResource(R.string.app_name), fontSize = 15.sp, fontWeight = FontWeight.Bold, color = pal.signal) Spacer(Modifier.size(12.dp)) - val (label, _) = railLabelIcon(model.selected) + val (label, _) = railLabelIcon(model.title) Text(stringResource(label), fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, modifier = Modifier.weight(1f), maxLines = 1, overflow = TextOverflow.Ellipsis) PanelClock() @@ -336,7 +338,7 @@ internal fun DualPanelContent(model: DualPanelModel) { for (row in model.keys.chunked(columns)) { Row(Modifier.fillMaxWidth().height(tileHeight), horizontalArrangement = Arrangement.spacedBy(gap)) { for (key in row) PanelTile(key, key == model.selected, key in model.badges, - if (key == "stores") model.storeDownloads else 0, Modifier.weight(1f)) { model.onSelect(key) } + if (key == "stores") model.storeDownloads else if (key == NavTabs.MORE) model.moreDownloads else 0, Modifier.weight(1f)) { model.onSelect(key) } repeat(columns - row.size) { Spacer(Modifier.weight(1f)) } } } @@ -400,12 +402,10 @@ private fun PanelClock() { } @Composable -internal fun DualPanelPublisher(s: FrontEndState, selected: String, onSelect: (String) -> Unit, a: FrontEndActions) { - val badges = buildSet { - if (setupNeedsAttention(s)) add("setup") - if (s.updates.hasUpdate) add("updates") - } - val model = DualPanelModel(navigationKeys(s), selected, badges, s.storeDownloadsActive, s.running, s.theme, s.appScale, onSelect, a.onResume) +internal fun DualPanelPublisher(s: FrontEndState, selected: String, title: String, onSelect: (String) -> Unit, a: FrontEndActions) { + val keys = navigationKeys(s) + val badges = keys.filter { railBadge(s, it) }.toSet() + val model = DualPanelModel(keys, selected, badges, s.storeDownloadsActive, s.running, s.theme, s.appScale, onSelect, a.onResume, title, railCount(s, NavTabs.MORE)) androidx.compose.runtime.SideEffect { DualScreenPanel.model = model } androidx.compose.runtime.DisposableEffect(Unit) { onDispose { DualScreenPanel.model = null } } } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/EdgeFling.kt b/app/src/main/java/com/droiddeck/launcher/ui/EdgeFling.kt new file mode 100644 index 0000000000..700d031776 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/EdgeFling.kt @@ -0,0 +1,92 @@ +package com.droiddeck.launcher.ui + +import android.view.Choreographer +import kotlin.math.abs +import kotlin.math.sqrt + +/** + * Where something dragged and let go against the side edges, like a chat head, comes to rest: + * a quick sideways flick sends it to the side it was thrown toward from wherever it is; a slower + * release goes to the side its coasting would carry it to; and its height carries on with the + * throw. Velocities are pixels per second. + */ +internal object EdgeFling { + /** How far a throw coasts, in seconds of its release velocity. */ + const val COAST_S = 0.18f + /** A sideways speed past this many dp per second picks its side outright. */ + private const val FLICK_DP_S = 600f + + fun toRight(centerX: Float, span: Float, vx: Float, density: Float): Boolean { + if (abs(vx) > FLICK_DP_S * density) return vx > 0 + return centerX + vx * COAST_S > span / 2 + } + + fun restY(y: Float, vy: Float, min: Float, max: Float) = (y + vy * COAST_S).coerceIn(min, max.coerceAtLeast(min)) +} + +/** + * A spring in two dimensions that starts with the velocity it was let go with, stepped on each + * display frame, so a throw flows into its settle instead of starting over from rest. + */ +internal class FlingSpring( + private val stiffness: Float = 340f, + dampingRatio: Float = 0.74f, + private val onFrame: (Float, Float) -> Unit, +) : Choreographer.FrameCallback { + private val damping = 2f * dampingRatio * sqrt(stiffness) + private var x = 0f + private var y = 0f + private var vx = 0f + private var vy = 0f + private var toX = 0f + private var toY = 0f + private var last = 0L + private var onEnd: (() -> Unit)? = null + var running = false + private set + + fun start(fromX: Float, fromY: Float, velocityX: Float, velocityY: Float, targetX: Float, targetY: Float, end: (() -> Unit)? = null) { + cancel() + x = fromX; y = fromY; vx = velocityX; vy = velocityY; toX = targetX; toY = targetY + onEnd = end + if (Motion.scale == 0f) { + onFrame(toX, toY) + end?.invoke() + return + } + running = true + last = 0L + Choreographer.getInstance().postFrameCallback(this) + } + + fun cancel() { + if (!running) return + running = false + Choreographer.getInstance().removeFrameCallback(this) + } + + override fun doFrame(frameTimeNanos: Long) { + if (!running) return + val dt = if (last == 0L) 1f / 120f else ((frameTimeNanos - last) / 1e9f).coerceIn(0f, 1f / 20f) + last = frameTimeNanos + // Small fixed steps keep the spring stable however long a frame took. + var left = dt / Motion.scale.coerceAtLeast(0.1f) + while (left > 0f) { + val h = minOf(left, 1f / 480f) + vx += (-stiffness * (x - toX) - damping * vx) * h + vy += (-stiffness * (y - toY) - damping * vy) * h + x += vx * h + y += vy * h + left -= h + } + val settled = abs(x - toX) < 0.5f && abs(y - toY) < 0.5f && abs(vx) < 20f && abs(vy) < 20f + if (settled) { + running = false + onFrame(toX, toY) + onEnd?.invoke() + return + } + onFrame(x, y) + Choreographer.getInstance().postFrameCallback(this) + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrameGenMenu.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrameGenMenu.kt index bac30bd3b8..83f2e05436 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrameGenMenu.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrameGenMenu.kt @@ -13,6 +13,9 @@ internal fun FrameGenMenu( host: MenuHost, mode: FrameGen.Mode, lossless: Lossless.State, onPick: (FrameGen.Mode) -> Unit, onImportLossless: () -> Unit, + gameProfileId: String? = null, + hasGameOverride: Boolean = false, + onResetGame: () -> Unit = {}, ) { val context = LocalContext.current AnchoredMenu(host.open == "fg", onDismiss = { if (host.open == "fg") host.open = null }, title = stringResource(R.string.frame_gen_title)) { firstItemFocus -> @@ -27,6 +30,12 @@ internal fun FrameGenMenu( onPick(m); host.open = null } item(FrameGen.Mode.OFF, focus = firstItemFocus) + if (gameProfileId != null) { + MenuItem(stringResource(R.string.comp_game_use_general), checked = !hasGameOverride) { + onResetGame() + host.open = null + } + } for (m in 2..4) item(FrameGen.Mode(FrameGen.ENGINE_DDFG, m)) val lsfg = (2..4).map { FrameGen.Mode(FrameGen.ENGINE_LSFG, it) } + FrameGen.ADAPTIVE_TARGETS.map { FrameGen.Mode(FrameGen.ENGINE_LSFG, target = it) } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndContent.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndContent.kt index d03d6acafd..5eb083fe5e 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndContent.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndContent.kt @@ -115,6 +115,7 @@ internal fun Pane( 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("sound:") -> s.soundtracks.firstOrNull { "sound:${it.appId}" == selected }?.let { it.hero ?: it.art } selected.startsWith("rom:") -> romFor(s, selected)?.second?.art else -> null } @@ -124,10 +125,12 @@ internal fun Pane( val origins = remember { HashMap() } val paneAt = remember { arrayOf(Offset.Zero) } val livePage by rememberUpdatedState(s.pageKey) - val railContent = if (selected.startsWith("app:")) "games" else selected + val railContent = if (selected.startsWith("app:")) "games" else if (selected.startsWith("sound:")) "soundtracks" else selected val target = if (page != null && s.pageKey != null) s.pageKey else railContent val gameShown = remember { arrayOf("games") } if (selected == "games" || selected.startsWith("app:")) gameShown[0] = selected + val soundShown = remember { arrayOf("soundtracks") } + if (selected == "soundtracks" || selected.startsWith("sound:")) soundShown[0] = selected val before = remember { arrayOf(target) } if (page != null && s.pageKey != null) { pages[s.pageKey] = page @@ -171,7 +174,7 @@ internal fun Pane( label = "pane", ) { key -> val drawn = (if (page != null && key == s.pageKey) page else pages[key]) - ?: { Content(s, if (key == "games") gameShown[0] else key, a, Modifier.fillMaxSize(), onSelect, onAndroidAppClick, onOpenDeveloperOptions, onRequestWirelessAdb, onPairWirelessDebugging) } + ?: { Content(s, if (key == "games") gameShown[0] else if (key == "soundtracks") soundShown[0] else key, a, Modifier.fillMaxSize(), onSelect, onAndroidAppClick, onOpenDeveloperOptions, onRequestWirelessAdb, onPairWirelessDebugging) } val hopSink by androidx.compose.animation.core.animateFloatAsState( if (Hops.sinking == key) 1f else 0f, Motion.tw(260), label = "hopSink", ) @@ -266,7 +269,7 @@ private fun Content( StoresPage(s, a, modifier) return } - if (selected == "games" || selected.startsWith("app:")) { + if (selected == "games" || selected.startsWith("app:") || selected == "soundtracks" || selected.startsWith("sound:")) { LibraryPage(s, a, selected, onSelect, modifier) return } @@ -274,12 +277,16 @@ private fun Content( DesktopPage(s, a, modifier, onSelect) return } + if (selected == NavTabs.MORE) { + MorePage(s, a, onSelect, modifier.padding(horizontal = padH).padding(top = padV)) + return + } if (selected == "agent") { AgentPage(modifier.padding(horizontal = padH).padding(top = padV)) return } if (selected == "android-apps" && s.isHomeApp) { - AndroidAppsPage(s, modifier, onAndroidAppClick) + AndroidAppsPage(s, a, modifier, onAndroidAppClick) return } Column(modifier = modifier.verticalScroll(rememberScrollState()).padding(horizontal = padH, vertical = padV)) { diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndRail.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndRail.kt index b57e87d9dc..0916dfc39f 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndRail.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndRail.kt @@ -51,6 +51,7 @@ import androidx.compose.material.icons.outlined.AutoAwesome import androidx.compose.material.icons.outlined.DesktopWindows import androidx.compose.material.icons.outlined.Layers import androidx.compose.material.icons.outlined.LocalMall +import androidx.compose.material.icons.outlined.MoreHoriz import androidx.compose.material.icons.outlined.SportsEsports import androidx.compose.material.icons.outlined.Storefront import androidx.compose.material.icons.outlined.SystemUpdate @@ -106,13 +107,16 @@ internal fun BottomBar( val bounds = remember { androidx.compose.runtime.mutableStateMapOf() } val tint = androidx.compose.runtime.rememberUpdatedState(LocalPalette.current.signal) val content = remember { arrayOfNulls(1) } + val barContext = LocalContext.current + remember { RailLabels.load(barContext) } + val iconOnly = !RailLabels.shown Row(modifier.fillMaxWidth().background(MaterialTheme.colorScheme.surface), verticalAlignment = Alignment.CenterVertically) { BoxWithConstraints(Modifier.weight(1f)) { val itemWidth = (maxWidth / keys.size).coerceIn(56.dp, 88.dp) Box(Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()).onPlaced { content[0] = it }) { if (shown in keys) ChipGlide(keys.indexOf(shown), bounds[shown], tint, GlideAxis.Horizontal, corner = 14.dp, fill = 0.14f, outline = 0f) Row(Modifier.selectableGroup().padding(vertical = 4.dp), horizontalArrangement = Arrangement.Center) { - NavigationItems(s, shown, compact = true, iconOnly = false, height = 56.dp, width = itemWidth, + NavigationItems(s, shown, compact = true, iconOnly = iconOnly, height = if (iconOnly) 48.dp else 56.dp, width = itemWidth, place = { key -> Modifier.onGloballyPositioned { item -> content[0]?.let { bounds[key] = it.localBoundingBoxOf(item) }; Hops.railBounds[key] = item.boundsInRoot() } }, onSelect = onSelect, onFocusSelect = onFocusSelect) } @@ -122,15 +126,7 @@ internal fun BottomBar( } } -internal fun navigationKeys(s: FrontEndState) = buildList { - add("steam"); add("games") - if (s.gameStoresEnabled) add("stores") - add("desktop") - if (com.droiddeck.launcher.agent.AgentHost.available) add("agent") - add("components") - if (s.isHomeApp) add("android-apps") - add("setup"); add("updates"); add("trinkets") -} +internal fun navigationKeys(s: FrontEndState) = NavTabs.bar(s) internal object RailLabels { var shown by mutableStateOf(true) @@ -198,6 +194,7 @@ internal fun SideRail( internal fun railLabelIcon(key: String): Pair = when (key) { "steam" -> R.string.rail_steam to Icons.Outlined.SportsEsports "games" -> R.string.rail_games to Icons.Outlined.VideoLibrary + "soundtracks" -> R.string.rail_music to SoundtrackIcon "stores" -> R.string.rail_stores to Icons.Outlined.LocalMall "desktop" -> R.string.rail_desktop to Icons.Outlined.DesktopWindows "components" -> R.string.rail_components to Icons.Outlined.Layers @@ -205,12 +202,26 @@ internal fun railLabelIcon(key: String): Pair = when (key) { "android-apps" -> R.string.rail_apps to Icons.Outlined.Apps "setup" -> R.string.rail_setup to Icons.Outlined.Tune "trinkets" -> R.string.rail_trinkets to Icons.Outlined.Toys + NavTabs.MORE -> R.string.rail_more to Icons.Outlined.MoreHoriz else -> R.string.rail_updates to Icons.Outlined.SystemUpdate } internal fun setupNeedsAttention(s: FrontEndState): Boolean = !s.ready || (s.available != null && s.available != s.installed) || PhantomProcessLimit.blocksSteam(s.phantomProcessStatus) || com.droiddeck.launcher.sync.Syncthing.needsAttention +internal fun railBadge(s: FrontEndState, key: String, setupNeedsAttention: Boolean = setupNeedsAttention(s)): Boolean = when (key) { + "setup" -> setupNeedsAttention + "updates" -> s.updates.hasUpdate + NavTabs.MORE -> NavTabs.more(s).any { it != NavTabs.MORE && railBadge(s, it, setupNeedsAttention) } + else -> false +} + +internal fun railCount(s: FrontEndState, key: String): Int = when (key) { + "stores" -> s.storeDownloadsActive + NavTabs.MORE -> if ("stores" in NavTabs.more(s)) s.storeDownloadsActive else 0 + else -> 0 +} + @Composable private fun NavigationItems( s: FrontEndState, shown: String, compact: Boolean, iconOnly: Boolean, height: Dp, width: Dp, @@ -221,8 +232,8 @@ private fun NavigationItems( val (label, icon) = railLabelIcon(key) key(key) { RailItem(stringResource(label), icon, key, shown == key, compact, iconOnly, height, width, - badge = (key == "setup" && setupNeedsAttention) || (key == "updates" && s.updates.hasUpdate), - count = if (key == "stores") s.storeDownloadsActive else 0, + badge = railBadge(s, key, setupNeedsAttention), + count = railCount(s, key), place = place, onFocus = { onFocusSelect(key) }) { onSelect(key) } } } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt index 31a8fb28c8..c936d13c74 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt @@ -40,6 +40,8 @@ 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.ime +import androidx.compose.foundation.layout.imePadding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.systemBars import androidx.compose.foundation.layout.width @@ -108,6 +110,7 @@ class FrontEndState( val vacDiagnostics: Boolean = false, val agentCommands: Boolean = false, val graphicsLogs: Boolean = false, + val buildWatermark: Boolean = true, val steamGpuDrawing: Boolean = false, val bridgeFellBack: Boolean = false, val bridgeFellBackMemory: Boolean = false, @@ -168,6 +171,7 @@ class FrontEndState( val showPhantomGate: Boolean = false, val orientation: Int = android.content.pm.ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE, val launcherOrientation: Int = android.content.pm.ActivityInfo.SCREEN_ORIENTATION_USER, + val homePage: String = com.droiddeck.launcher.core.AppUiPrefs.HOME_PAGE_STEAM, val launcherFullscreen: Boolean = true, val downloadSource: String = DownloadSource.MODE_AUTO, val downloadMirror: String = "", @@ -177,6 +181,10 @@ class FrontEndState( val lowStorageWarning: Boolean = true, val launcherIcon: String = com.droiddeck.launcher.LauncherIcon.DARK, val gameStoresEnabled: Boolean = true, + val soundtracksEnabled: Boolean = true, + val soundtracksIngame: Boolean = false, + val soundtracks: List = emptyList(), + val soundtracksLoaded: Boolean = true, val gameStoresSpeedTier: String = "fast", val navigate: String? = null, val addedGamesArt: Boolean = true, @@ -247,6 +255,7 @@ class FrontEndActions( val onVacDiagnostics: () -> Unit = {}, val onAgentCommands: () -> Unit = {}, val onGraphicsLogs: () -> Unit = {}, + val onBuildWatermark: () -> Unit = {}, val onSteamGpuDrawing: () -> Unit = {}, val onClearCachedApps: (Boolean) -> Unit = {}, val onMemoryHud: (String) -> Unit = {}, @@ -267,6 +276,7 @@ class FrontEndActions( val onLauncherIcon: (String) -> Unit = {}, val onOrientation: (Int) -> Unit = {}, val onLauncherOrientation: (Int) -> Unit = {}, + val onHomePage: (String) -> Unit = {}, val onLauncherFullscreen: (Boolean) -> Unit = {}, val onAnimationsEnabled: (Boolean) -> Unit = {}, val onLowStorageWarning: (Boolean) -> Unit = {}, @@ -279,6 +289,11 @@ class FrontEndActions( val onDownloadPrefix: (String) -> Unit = {}, val onDownloadProxy: (String) -> Unit = {}, val onGameStoresEnabled: (Boolean) -> Unit = {}, + val onSoundtracksEnabled: (Boolean) -> Unit = {}, + val onSoundtracksIngame: (Boolean) -> Unit = {}, + val onSoundtrackAdded: (java.io.File) -> Unit = {}, + val onSoundtracksChanged: () -> Unit = {}, + val onSoundtrackRemoved: (Library.SteamGame) -> Unit = {}, val onGameStoresSpeedTier: (String) -> Unit = {}, val onNavigated: () -> Unit = {}, val onStoresShowMature: (Boolean) -> Unit = {}, @@ -287,6 +302,7 @@ class FrontEndActions( val onLibraryChanged: () -> Unit = {}, val onHomeApp: () -> Unit = {}, val onHomeScreen: (Boolean) -> Unit = {}, + val onAppIconsChanged: () -> Unit = {}, val onSteamIntegration: (com.droiddeck.launcher.core.SteamIntegration.Feature?) -> Unit = {}, val onDismissIntegration: () -> Unit = {}, val onIntegration: (com.droiddeck.launcher.core.SteamIntegration.Feature) -> Unit = {}, @@ -452,7 +468,9 @@ fun FrontEndScreen(s: FrontEndState, a: FrontEndActions, page: (@Composable () - @OptIn(ExperimentalComposeUiApi::class) @Composable private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Composable () -> Unit)?, frontFocus: FrontFocus) { - var selected by rememberSaveable { mutableStateOf(if (s.shortcutPicker) "games" else "steam") } + var selected by rememberSaveable { + mutableStateOf(if (s.shortcutPicker) "games" else if (NavTabs.place(s, "steam") == TabPlace.HIDDEN) navigationKeys(s).first { it != "components" } else "steam") + } LaunchedEffect(s.shortcutPicker) { if (s.shortcutPicker) selected = "games" } LaunchedEffect(s.navigate) { val target = s.navigate ?: return@LaunchedEffect @@ -462,6 +480,14 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com "setup:launcher" -> { SetupTabs.openLauncher = true; selected = "setup" } com.droiddeck.launcher.sync.SyncthingService.NAV -> com.droiddeck.launcher.sync.Syncthing.requestOpen() "setup:integration" -> { SetupTabs.openOverview = true; selected = "setup" } + com.droiddeck.launcher.core.AppUiPrefs.HOME_PAGE_APPS -> { + // Home lands on the apps page itself, so a page open over the rail (Components, Performance) closes first. + if (s.pageKey != null) a.onPageBack() + Hops.origin = null + Hops.restore = null + Hops.sinking = null + selected = target + } else -> selected = target } a.onNavigated() @@ -551,20 +577,32 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com ) { selected = if (selected.startsWith("rom:")) "emu:" + selected.removePrefix("rom:").substringBefore(':') else "desktop" } + val backToMore = s.pageKey == null && Hops.origin == null && selected in NavTabs.more(s) + BackHandler(enabled = !processSettingsPageVisible && backToMore) { + selected = NavTabs.MORE + } LaunchedEffect(s.isHomeApp) { if (!s.isHomeApp && selected == "android-apps") selected = "steam" } - LaunchedEffect(s.steamGames.isEmpty()) { - if (s.steamGames.isEmpty() && selected.startsWith("app:") && GameRef.parse(selected).appId != null) selected = "games" + LaunchedEffect(s.soundtracksEnabled) { + if (!s.soundtracksEnabled && (selected == "soundtracks" || selected.startsWith("sound:"))) selected = "games" + } + LaunchedEffect(s.steamGames.isEmpty(), s.soundtracks, s.soundtracksLoaded) { + if (s.steamGames.isEmpty() && selected.startsWith("app:")) { + val id = GameRef.parse(selected).appId + if (id != null && s.soundtracks.none { it.appId == id } && s.soundtracksLoaded) selected = "games" + } } remember { Motion.refresh(ctx); true } - val railSelection = when { + val openTab = when { Hops.origin != null && s.pageKey == Hops.origin?.page -> Hops.origin!!.dest s.pageKey == "performance" -> "steam" s.pageKey == "controller-mapping" -> "setup" selected.startsWith("app:") -> "games" + selected.startsWith("sound:") -> "soundtracks" selected.startsWith("emu:") || selected.startsWith("rom:") || selected.startsWith("user:") || selected == "store" -> "desktop" else -> s.pageKey ?: selected } + val railSelection = if (openTab in NavTabs.more(s)) NavTabs.MORE else openTab val railSelectionNow = androidx.compose.runtime.rememberUpdatedState(railSelection) var railPicks by remember { mutableStateOf(0) } val showRailPage: (String, Boolean) -> Unit = { key, focusContent -> @@ -673,23 +711,25 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com val r = Hops.restore ?: return@LaunchedEffect if (r.surface == HOP_SURFACE_SHEET) return@LaunchedEffect Hops.restore = null - if (r.rail != selected && !(r.rail == "games" && selected.startsWith("app:"))) selected = r.rail + if (r.rail != selected && !(r.rail == "games" && selected.startsWith("app:")) && !(r.rail == "soundtracks" && selected.startsWith("sound:"))) selected = r.rail kotlinx.coroutines.delay(Motion.ms(PAGE_EXIT_MS).toLong()) if (inputModeManager.inputMode != InputMode.Keyboard) return@LaunchedEffect frontFocus.last = r.control focusWithinFrames({ frontFocus.last == r.control && anyFocused }) { frontFocus.items[r.control] ?: frontFocus.paneEntry() } } var screenAt by remember { mutableStateOf(Offset.Zero) } - if (s.dualScreen) DualPanelPublisher(s, railSelection, { key -> + if (s.dualScreen) DualPanelPublisher(s, railSelection, openTab, { key -> if (processSettingsPageVisible) return@DualPanelPublisher if (inputModeManager.inputMode != InputMode.Keyboard) inputModeManager.requestInputMode(InputMode.Keyboard) focusManager.clearFocus(force = true) onRailSelect(key) }, a) CompositionLocalProvider(LocalShowSection provides { key -> selected = key }) { + val agentKeyboardOpen = railSelection == "agent" && WindowInsets.ime.getBottom(androidx.compose.ui.platform.LocalDensity.current) > 0 LauncherLayout( bottomNavigation && !s.dualScreen, pal.line, Modifier.fillMaxSize().onGloballyPositioned { screenAt = it.positionInRoot() } + .then(if (railSelection == "agent") Modifier.imePadding() else Modifier) .then(if (s.dualScreen) Modifier.onKeyEvent { event -> val step = dualPageStep(event.nativeKeyEvent) ?: return@onKeyEvent false if (event.type == KeyEventType.KeyDown && !processSettingsPageVisible) { @@ -703,7 +743,7 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com true } else Modifier), navigation = { - if (s.dualScreen) Unit + if (s.dualScreen || (bottomNavigation && agentKeyboardOpen)) Unit else if (bottomNavigation) BottomBar(s, railSelection, onRailSelect, onRailFocus, a, railFocus) else SideRail(s, railSelection, onRailSelect, onRailFocus, a, railFocus.fillMaxHeight()) }, @@ -801,7 +841,7 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com ) } } - val hasBackTarget = (s.pageKey != null && page != null) || + val hasBackTarget = backToMore || (s.pageKey != null && page != null) || (s.pageKey == null && Hops.origin?.page == selected) || ((s.pageKey == null || page == null) && (selected.startsWith("emu:") || selected.startsWith("rom:") || selected.startsWith("user:") || selected == "store")) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt index 79ce769131..aa08d07f17 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt @@ -91,6 +91,7 @@ private const val LAUNCHER_TAB = 2 internal object SetupTabs { var openLauncher = false + var focusTabs = false var openOverview = false } private const val GLASSES_TAB = 6 @@ -456,8 +457,9 @@ internal fun SetupPanel( remember { RailLabels.load(railContext) } ToggleRow(host, "rail-labels", stringResource(R.string.setup_rail_labels), stringResource(R.string.setup_rail_labels_hint), RailLabels.shown) { RailLabels.set(railContext, it) } LanguageRow(host, s.language, a.onLanguage) - ToggleRow(host, "show-stores", stringResource(R.string.setup_stores), null, s.gameStoresEnabled, onChange = a.onGameStoresEnabled) + if (s.soundtracksEnabled) ToggleRow(host, "soundtracks-ingame", stringResource(R.string.setup_soundtracks_ingame), stringResource(R.string.setup_soundtracks_ingame_hint), s.soundtracksIngame, onChange = a.onSoundtracksIngame) } + TabsSettingsGroup(host, s, a) } val device: @Composable () -> Unit = { SettingsGroup(stringResource(R.string.setup_group_device)) { @@ -468,6 +470,11 @@ internal fun SetupPanel( ) { a.onHomeScreen(it) } if (s.homeScreenEnabled) { ActionRow(stringResource(R.string.setup_default_home), s.defaultHomeLabel ?: stringResource(R.string.setup_choose_home), stringResource(R.string.setup_choose), a.onHomeApp) + ChoiceRow( + host, "home-page", stringResource(R.string.setup_home_page), stringResource(R.string.setup_home_page_hint), + com.droiddeck.launcher.core.AppUiPrefs.homePageOptions.map { (value, label) -> value to stringResource(label) }, + s.homePage, onPick = a.onHomePage, + ) } ChoiceRow( host, "launcher-orientation", stringResource(R.string.setup_launcher_orientation), null, @@ -589,6 +596,16 @@ internal fun SetupPanel( ) { a.onGameDebugLogs() } ToggleRow(host, "vacdiag", stringResource(R.string.setup_vac_diag), stringResource(R.string.setup_vac_diag_hint), s.vacDiagnostics) { a.onVacDiagnostics() } ToggleRow(host, "agent-commands", stringResource(R.string.setup_agent_commands), null, s.agentCommands) { a.onAgentCommands() } + if (com.droiddeck.launcher.agent.AgentHost.available) { + val agentContext = androidx.compose.ui.platform.LocalContext.current + ToggleRow(host, "agent-pet", stringResource(R.string.setup_agent_pet), stringResource(R.string.setup_agent_pet_hint), AgentPet.enabled) { + AgentPet.set(agentContext, it) + } + if (AgentPet.enabled && !AgentPet.allowed) ActionRow( + stringResource(R.string.setup_agent_pet_float), stringResource(R.string.setup_agent_pet_float_hint), + stringResource(R.string.setup_agent_pet_allow), onClick = { AgentPet.requestFloating(agentContext) }, + ) + } ToggleRow(host, "graphics-logs", stringResource(R.string.setup_graphics_logs), stringResource(R.string.setup_graphics_logs_hint), s.graphicsLogs) { a.onGraphicsLogs() } if (!s.adreno && com.droiddeck.launcher.session.SessionPrefs.steamGpuCompositingAllowed()) ToggleRow(host, "steam-gpu-drawing", stringResource(R.string.setup_steam_gpu_drawing), stringResource(R.string.setup_steam_gpu_drawing_hint), s.steamGpuDrawing) { a.onSteamGpuDrawing() } ActionRow(stringResource(R.string.setup_latest_logs), stringResource(R.string.drawer_logs_hint), stringResource(R.string.drawer_share_logs), a.onShareLogs, @@ -739,6 +756,17 @@ internal fun LaunchSettings(s: FrontEndState, a: FrontEndActions, host: MenuHost val context = androidx.compose.ui.platform.LocalContext.current val inputMode = androidx.compose.ui.platform.LocalInputModeManager.current val wincompKey = game?.takeIf { it.library == com.droiddeck.launcher.frontend.Library.ADDED || it.appId > 0 }?.profileKey + val frameGenProfileKey = game?.profileKey?.takeIf { it.isNotBlank() } + var gameFrameGenMode by remember(frameGenProfileKey) { + mutableStateOf(frameGenProfileKey?.let { + com.droiddeck.launcher.gpu.FrameGen.mode(context, it) + } ?: s.frameGen) + } + var gameFrameGenOverride by remember(frameGenProfileKey) { + mutableStateOf(frameGenProfileKey?.let { + com.droiddeck.launcher.gpu.FrameGen.hasGameOverride(context, it) + } ?: false) + } var wincompOpen by remember(wincompKey) { mutableStateOf(null) } val wincompPicks = remember(wincompKey, wincompOpen) { wincompKey?.let { com.droiddeck.launcher.session.WinComponents.picks(context, it) }.orEmpty() } val steamScope = game?.let { com.droiddeck.launcher.session.NoSteamLaunch.scope(it) } @@ -757,10 +785,42 @@ internal fun LaunchSettings(s: FrontEndState, a: FrontEndActions, host: MenuHost } add { m -> Box(m) { - SettingCard(stringResource(R.string.frame_gen_title), s.frameGenLabel, "card:fg", Modifier.fillMaxSize()) { + SettingCard( + stringResource(R.string.frame_gen_title), + if (frameGenProfileKey != null) + com.droiddeck.launcher.gpu.FrameGen.label(context, gameFrameGenMode) + else s.frameGenLabel, + "card:fg", Modifier.fillMaxSize() + ) { host.open = if (host.open == "fg") null else "fg" } - FrameGenMenu(s, a, host) + FrameGenMenu( + host = host, + mode = if (frameGenProfileKey != null) gameFrameGenMode else s.frameGen, + lossless = s.lossless, + onPick = { mode -> + val key = frameGenProfileKey + if (key == null) { + a.onFrameGenPick(mode) + } else { + com.droiddeck.launcher.gpu.FrameGen.setForGame(context, key, mode) + gameFrameGenMode = mode + gameFrameGenOverride = true + } + }, + onImportLossless = a.onImportLossless, + gameProfileId = frameGenProfileKey, + hasGameOverride = gameFrameGenOverride, + onResetGame = { + val key = frameGenProfileKey + if (key != null) { + com.droiddeck.launcher.gpu.FrameGen.clearGame(context, key) + gameFrameGenMode = + com.droiddeck.launcher.gpu.FrameGen.mode(context) + gameFrameGenOverride = false + } + } + ) } } if (controller != null) add { m -> SettingCard(stringResource(R.string.setup_card_controls), stringResource(R.string.setup_card_controls_hint), "card:controls", m, controller.onMapping) } @@ -857,12 +917,37 @@ internal fun GameSettingsMenus(host: MenuHost, game: com.droiddeck.launcher.fron val custom = stringResource(R.string.comp_game_fex_custom) val customSync = stringResource(R.string.game_sync_custom) val resetDone = stringResource(R.string.comp_game_reset_done, game.name) + val resKey = "game-settings-res" + val resolution = current?.let { com.droiddeck.launcher.core.GameEnvironment.gameResolution(it, scope) } + val screen = remember { com.droiddeck.launcher.session.SessionDisplay.screenSize(com.droiddeck.launcher.session.SessionDisplay.panelSize(appContext)) } + val matchScreen = stringResource(R.string.display_match_screen, screen.first, screen.second) + val scaledLabels = com.droiddeck.launcher.core.GameResolution.scales.associateWith { + stringResource(R.string.display_follow_screen_scaled, com.droiddeck.launcher.core.GameResolution.formatScale(it)) + } + fun sizeLabel(size: Pair) = "${size.first}ร—${size.second} ยท ${com.droiddeck.launcher.core.GameResolution.aspectLabel(size.first, size.second)}" + fun resolutionLabel(choice: com.droiddeck.launcher.core.GameResolution.Choice?): String = when (choice) { + null -> matchScreen + is com.droiddeck.launcher.core.GameResolution.Scaled -> (scaledLabels[choice.scale] + ?: "รท" + com.droiddeck.launcher.core.GameResolution.formatScale(choice.scale)) + + " ยท " + sizeLabel(com.droiddeck.launcher.core.GameResolution.resolve(choice, screen)) + is com.droiddeck.launcher.core.GameResolution.Fixed -> sizeLabel(choice.width to choice.height) + } + fun pickResolution(choice: com.droiddeck.launcher.core.GameResolution.Choice?) { + host.open = key + save { com.droiddeck.launcher.session.GameEnvironmentStore.setGameResolution(it, scope, choice) } + } + var editResolution by remember(scope) { mutableStateOf(false) } AnchoredMenu(host.open == key, onDismiss = { if (host.open == key) host.open = null }, title = stringResource(R.string.game_settings_menu_title, game.name)) { first -> MenuItem(stringResource(R.string.game_no_steam_title), checked = noSteam, enabled = ready, detail = stringResource(R.string.game_no_steam_detail), focusRequester = first) { val on = !noSteam save { com.droiddeck.launcher.session.GameEnvironmentStore.setGameNoSteam(it, scope, on) } } + if (noSteam) MenuItem( + stringResource(R.string.game_res_title), checked = false, enabled = ready, + detail = resolutionLabel(resolution), + trailing = { Text("โ€บ", fontSize = 16.sp, color = colors.onSurfaceVariant) }, + ) { host.open = resKey } if (!launcher) { val chosen = com.droiddeck.launcher.core.FexPreset.all.firstOrNull { it.id == fex } MenuItem( @@ -899,6 +984,45 @@ internal fun GameSettingsMenus(host: MenuHost, game: com.droiddeck.launcher.fron } } } + AnchoredMenu(host.open == resKey, onDismiss = { if (host.open == resKey) host.open = null }, title = stringResource(R.string.game_res_title)) { first -> + MenuItem(matchScreen, checked = resolution == null, enabled = ready, focusRequester = first) { pickResolution(null) } + com.droiddeck.launcher.core.GameResolution.scales.forEach { scale -> + val choice = com.droiddeck.launcher.core.GameResolution.Scaled(scale) + MenuItem(scaledLabels.getValue(scale), checked = resolution == choice, enabled = ready, + detail = sizeLabel(com.droiddeck.launcher.core.GameResolution.resolve(choice, screen))) { pickResolution(choice) } + } + com.droiddeck.launcher.core.GameResolution.aspects.forEach { aspect -> + val sizes = com.droiddeck.launcher.core.GameResolution.sizesFor(aspect, screen) + MenuItem(aspect.label, checked = resolution in aspect.sizes, enabled = ready, + detail = sizes.joinToString(" ยท ") { "${it.width}ร—${it.height}" }, + trailing = { Text("โ€บ", fontSize = 16.sp, color = colors.onSurfaceVariant) }, + ) { host.open = "$resKey-${aspect.label}" } + } + val fixed = resolution as? com.droiddeck.launcher.core.GameResolution.Fixed + val customValue = fixed?.takeIf { f -> com.droiddeck.launcher.core.GameResolution.aspects.none { f in it.sizes } } + MenuItem( + if (customValue == null) stringResource(R.string.mode_res_custom) else stringResource(R.string.mode_res_custom_value, customValue.width, customValue.height), + checked = customValue != null, enabled = ready, + detail = customValue?.let { com.droiddeck.launcher.core.GameResolution.aspectLabel(it.width, it.height) }, + ) { editResolution = true } + } + com.droiddeck.launcher.core.GameResolution.aspects.forEach { aspect -> + val aspectKey = "$resKey-${aspect.label}" + AnchoredMenu(host.open == aspectKey, onDismiss = { if (host.open == aspectKey) host.open = null }, title = aspect.label) { first -> + com.droiddeck.launcher.core.GameResolution.sizesFor(aspect, screen).forEachIndexed { index, size -> + MenuItem("${size.width}ร—${size.height}", checked = resolution == size, enabled = ready, + focusRequester = if (index == 0) first else null) { pickResolution(size) } + } + } + } + if (editResolution) CustomResolutionDialog( + (resolution as? com.droiddeck.launcher.core.GameResolution.Fixed)?.let { it.width to it.height }, + onSave = { value -> + editResolution = false + pickResolution(com.droiddeck.launcher.core.GameResolution.Fixed(value.first, value.second)) + }, + onDismiss = { editResolution = false }, + ) AnchoredMenu(host.open == fexKey, onDismiss = { if (host.open == fexKey) host.open = null }, title = stringResource(R.string.fex_preset_title)) { first -> MenuItem(useDefault, checked = fex == null, enabled = ready, detail = stringResource(generalFex.label), focusRequester = first) { host.open = key diff --git a/app/src/main/java/com/droiddeck/launcher/ui/GameDetail.kt b/app/src/main/java/com/droiddeck/launcher/ui/GameDetail.kt index f42a85de51..7aba7feb45 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/GameDetail.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/GameDetail.kt @@ -148,7 +148,7 @@ internal fun GameDetail( val narrow = LocalNarrowPane.current val stacked = narrow || LocalConfiguration.current.screenWidthDp < 700 val ref = remember(key) { GameRef.parse(key) } - val games = s.steamGames + rememberXboxCloudRows(s) + val games = s.steamGames + rememberXboxCloudRows(s) + if (s.soundtracksEnabled) emptyList() else s.soundtracks val found = ref.game(games) val known = remember(key) { arrayOfNulls>(1) } val store = ref.store ?: Store.byId(found?.source) ?: known[0]?.first @@ -280,7 +280,7 @@ internal fun GameDetail( } @Composable -private fun SourceBadge(source: String) { +internal fun SourceBadge(source: String) { val c = sourceColours(source) Row( verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(7.dp), @@ -309,7 +309,7 @@ private fun GameStatusLine(source: String, game: Library.SteamGame?, item: Catal item?.accessible == true -> listOf(stringResource(R.string.stores_eyebrow_library)) else -> listOf(stringResource(R.string.stores_eyebrow_store)) } - val size = if (folder != null && (installed != null || game != null)) diskSize(installed, folder) else (item?.sizeBytes ?: 0L).takeIf { it > 0 } + val size = if (folder != null && (installed != null || game != null)) diskSize(installed, folder) else catalogSize(item).takeIf { it > 0 } val line = (state + listOfNotNull(size?.let { formatBytes(it) })).filter { it.isNotBlank() }.joinToString(" ยท ").replaceFirstChar { it.uppercase() } val muted = colors.onBackground.copy(alpha = 0.78f) Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) { @@ -399,6 +399,7 @@ internal fun GameActions( val download = rawDownload?.takeIf { it.isActive } val failed = rawDownload?.takeIf { it.state == DownloadState.FAILED } val cloud = game?.library == Library.XBOX_CLOUD && installed == null + val downloadBytes = catalogSize(item) Actions { when { s.shortcutPicker && game != null -> { @@ -474,7 +475,7 @@ internal fun GameActions( if (item?.installable == true && item.xboxPc) { SecondaryButton( if (StoresState.isUnfinished(item)) stringResource(R.string.stores_resume_install) - else if (item.sizeBytes > 0) stringResource(R.string.stores_install_size, formatBytes(item.sizeBytes)) + else if (downloadBytes > 0) stringResource(R.string.stores_install_size, formatBytes(downloadBytes)) else stringResource(R.string.stores_install), ) { StoresState.requestInstall(ctx, item) } } @@ -492,7 +493,7 @@ internal fun GameActions( } item?.installable == true -> { InstallButton( - if (item.sizeBytes > 0) stringResource(R.string.stores_install_size, formatBytes(item.sizeBytes)) else stringResource(R.string.stores_install), + if (downloadBytes > 0) stringResource(R.string.stores_install_size, formatBytes(downloadBytes)) else stringResource(R.string.stores_install), leadOn, ) { StoresState.requestInstall(ctx, item) } if (store == Store.XBOX && item.xboxCloud) { @@ -505,7 +506,12 @@ internal fun GameActions( InstallButton(stringResource(R.string.stores_install), leadOn) { StoresState.requestInstall(ctx, item) } SecondaryButton(stringResource(R.string.stores_view_on, item.store.shortLabel)) { openStoreUrl(ctx, item) } } - item != null && item.isFree -> PrimaryButton(stringResource(R.string.stores_get_free), main = true, modifier = leadOn) { openStoreUrl(ctx, item) } + item != null && item.isFree -> { + val adding = StoresState.claiming[item.key] == true + PrimaryButton(stringResource(if (adding) R.string.stores_claiming else R.string.stores_get_free), enabled = !adding, main = true, modifier = leadOn) { + if (StoresState.canClaim(item)) StoresState.claim(ctx, item) { openStoreUrl(ctx, item) } else openStoreUrl(ctx, item) + } + } item != null -> PrimaryButton(buyLabel(item), main = true, modifier = leadOn) { openStoreUrl(ctx, item) } } if (cloud && (download != null || failed != null)) { @@ -568,13 +574,13 @@ private fun buyLabel(item: CatalogItem): String = when { } @Composable -private fun FileButtons(game: Library.SteamGame, a: FrontEndActions) { +internal fun FileButtons(game: Library.SteamGame, a: FrontEndActions) { game.gameFiles?.takeIf { it.isDirectory }?.let { dir -> SecondaryButton(stringResource(R.string.games_files), compact = true) { a.onBrowseFiles(dir) } } game.protonPrefix?.takeIf { it.isDirectory }?.let { dir -> SecondaryButton(stringResource(R.string.games_prefix), compact = true) { a.onBrowseFiles(dir) } } } @Composable -private fun GameShortcutMenu(g: Library.SteamGame, a: FrontEndActions) { +internal fun GameShortcutMenu(g: Library.SteamGame, a: FrontEndActions) { var open by remember(g.gameId) { mutableStateOf(false) } Box { SecondaryButton(stringResource(R.string.game_shortcut), compact = true) { open = !open } @@ -587,7 +593,7 @@ private fun GameShortcutMenu(g: Library.SteamGame, a: FrontEndActions) { } @Composable -private fun rememberEditArt(g: Library.SteamGame): (() -> Unit)? { +internal fun rememberEditArt(g: Library.SteamGame): (() -> Unit)? { val ctx = LocalContext.current val folder = g.gameFiles return when { @@ -601,7 +607,7 @@ private fun rememberEditArt(g: Library.SteamGame): (() -> Unit)? { } @Composable -private fun EditArtButton(g: Library.SteamGame) { +internal fun EditArtButton(g: Library.SteamGame) { val open = rememberEditArt(g) ?: return IconAction(Icons.Outlined.Edit, stringResource(R.string.game_edit_art), "game:edit", onClick = open) } @@ -658,7 +664,7 @@ internal fun IconAction(icon: androidx.compose.ui.graphics.vector.ImageVector, l } @Composable -private fun RemoveButton(title: String, game: Library.SteamGame?, installed: InstalledStoreGame?, a: FrontEndActions) { +internal fun RemoveButton(title: String, game: Library.SteamGame?, installed: InstalledStoreGame?, a: FrontEndActions) { val ctx = LocalContext.current val colors = MaterialTheme.colorScheme if ((installed?.sidecar?.store?.id ?: game?.source) == Store.BATTLENET.id && installed?.sidecar?.id?.let(BattleNetInstall::product) == null) return @@ -1011,6 +1017,13 @@ internal fun FactRow(label: String, value: String, labelWidth: androidx.compose. } } +@Composable +internal fun catalogSize(item: CatalogItem?): Long { + val ctx = LocalContext.current + if (item != null) LaunchedEffect(item.key, item.accessible) { StoreSizes.request(ctx, item) } + return item?.let { StoreSizes.size(it) } ?: 0L +} + @Composable internal fun diskSize(installed: InstalledStoreGame?, folder: File): Long? { val ctx = LocalContext.current diff --git a/app/src/main/java/com/droiddeck/launcher/ui/GameGlass.kt b/app/src/main/java/com/droiddeck/launcher/ui/GameGlass.kt index a2660d1b47..e5fd8845bd 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/GameGlass.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/GameGlass.kt @@ -38,6 +38,7 @@ import androidx.compose.ui.graphics.drawscope.drawIntoCanvas import androidx.compose.ui.graphics.drawscope.DrawScope import androidx.compose.ui.graphics.drawscope.clipRect import androidx.compose.ui.graphics.drawscope.translate +import androidx.compose.ui.draw.blur import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.graphics.luminance import androidx.compose.ui.graphics.painter.Painter @@ -147,6 +148,7 @@ internal fun GameBackdrop( fadeTop: Boolean, modifier: Modifier = Modifier, onArtPlaced: (androidx.compose.ui.geometry.Rect?) -> Unit = {}, + artBlur: androidx.compose.ui.unit.Dp = 0.dp, content: @Composable () -> Unit, ) { val ctx = LocalContext.current @@ -178,13 +180,13 @@ internal fun GameBackdrop( glass.fadeBottom(this, size) }, ) - if (art != null) ArtLayer(art, ambient ?: art, fadeTop, onArtPlaced) + if (art != null) ArtLayer(art, ambient ?: art, fadeTop, artBlur, onArtPlaced) CompositionLocalProvider(LocalGlass provides glass) { content() } } } @Composable -private fun ArtLayer(model: Any?, sample: Any?, fadeTop: Boolean, onPlaced: (androidx.compose.ui.geometry.Rect?) -> Unit) { +private fun ArtLayer(model: Any?, sample: Any?, fadeTop: Boolean, blur: androidx.compose.ui.unit.Dp, onPlaced: (androidx.compose.ui.geometry.Rect?) -> Unit) { val colors = MaterialTheme.colorScheme val light = colors.background.luminance() > 0.5f val pale = ((rememberArtBrightness(sample) - 0.28f) / 0.5f).coerceIn(0f, 1f) @@ -208,7 +210,7 @@ private fun ArtLayer(model: Any?, sample: Any?, fadeTop: Boolean, onPlaced: (and model = model, contentDescription = null, contentScale = ContentScale.Crop, alignment = BiasAlignment(0.45f, -0.35f), colorFilter = artFilter, - modifier = Modifier.matchParentSize(), + modifier = Modifier.matchParentSize().then(if (blur > 0.dp) Modifier.blur(blur) else Modifier), ) Box( Modifier.matchParentSize().drawBehind { diff --git a/app/src/main/java/com/droiddeck/launcher/ui/LibraryPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/LibraryPage.kt index 73dad7aa70..e3d76dcd1f 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/LibraryPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/LibraryPage.kt @@ -42,6 +42,7 @@ import androidx.compose.foundation.shape.CircleShape 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.BookmarkBorder import androidx.compose.material.icons.filled.FilterAlt import androidx.compose.material.icons.filled.GridView import androidx.compose.material.icons.filled.PlayArrow @@ -61,6 +62,7 @@ import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember +import androidx.compose.runtime.produceState import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier @@ -92,6 +94,11 @@ import androidx.compose.ui.unit.sp import coil.compose.AsyncImage import com.droiddeck.launcher.R import com.droiddeck.launcher.frontend.Library +import com.droiddeck.launcher.frontend.Soundtrack +import com.droiddeck.launcher.frontend.SoundtrackCollections +import com.droiddeck.launcher.frontend.SoundtrackIndex +import com.droiddeck.launcher.frontend.SoundtrackTracks +import com.droiddeck.launcher.playback.SoundtrackController import com.droiddeck.launcher.session.SessionPrefs import com.droiddeck.launcher.stores.CatalogItem import com.droiddeck.launcher.stores.Store @@ -156,7 +163,7 @@ internal fun installedFirst(entries: List): List = e internal const val LIBRARY_ALL = "all" internal fun librarySources(entries: List, order: List, always: Set = emptySet()): List = - (listOf(Library.SOURCE_STEAM) + arrangeStoreTabs(order, emptySet()).map { it.store.id } + Library.ADDED) + (listOf(Library.SOURCE_STEAM) + arrangeStoreTabs(order, emptySet()).map { it.store.id } + Library.ADDED + Library.SOURCE_COLLECTION) .filter { source -> source in always || entries.any { it.source == source } } internal object LibraryDisplay { @@ -215,14 +222,24 @@ internal fun LibraryPage(s: FrontEndState, a: FrontEndActions, selected: String, val inputMode = androidx.compose.ui.platform.LocalInputModeManager.current LaunchedEffect(Unit) { StoresState.refresh(ctx) } remember { LibraryDisplay.load(ctx) } - val stores = s.gameStoresEnabled && !s.shortcutPicker + val soundMode = selected == "soundtracks" || selected.startsWith("sound:") + val stores = s.gameStoresEnabled && !s.shortcutPicker && !soundMode val signedIn = Store.entries.filter { StoresState.isSignedIn(it) } LaunchedEffect(stores, signedIn) { if (stores) signedIn.forEach { StoresState.loadLibrary(ctx, it) } } val owned = if (stores) signedIn.associateWith { StoresState.library[it].orEmpty() } else emptyMap() val installedStore = StoresState.installed.map { it.key }.toSet() val syncing = if (stores) signedIn.mapNotNull { st -> StoresState.status[st]?.let { st to it } } else emptyList() val cloudRows = rememberXboxCloudRows(s) - val all = remember(s.steamGames, cloudRows, owned, installedStore) { libraryEntries(s.steamGames + cloudRows, owned, installedStore) } + remember { SoundtrackCollections.load(ctx) } + val savedSnapshot = SoundtrackCollections.snapshot + val favoritesLabel = stringResource(R.string.soundtracks_favorites) + val all = remember(soundMode, s.steamGames, s.soundtracks, s.soundtracksEnabled, cloudRows, owned, installedStore, savedSnapshot, favoritesLabel) { + if (soundMode) s.soundtracks.map { LibraryEntry("sound:${it.appId}", it.source, it.name, it, null, true) } + + (if (s.soundtracks.isEmpty() && savedSnapshot.favorites.isEmpty() && savedSnapshot.collections.isEmpty()) emptyList() else SoundtrackCollections.games(ctx, favoritesLabel)) + .map { LibraryEntry("sound:${it.appId}", it.source, it.name, it, null, true) } + else libraryEntries(s.steamGames + cloudRows + if (s.soundtracksEnabled) emptyList() else s.soundtracks.filter { it.library != Library.ADDED }, owned, installedStore) + } + var addingSoundtrack by remember { mutableStateOf(false) } LaunchedEffect(Unit) { XboxLibraryFilter.load(ctx) } var showUninstalled by remember(LibraryView.ownedRequest) { mutableStateOf(SessionPrefs.libraryShowUninstalled(ctx)) } var collectionShows by remember { mutableStateOf?>(null) } @@ -240,7 +257,10 @@ internal fun LibraryPage(s: FrontEndState, a: FrontEndActions, selected: String, } val itchSignedIn = owned.containsKey(Store.ITCH) val gameJoltSignedIn = owned.containsKey(Store.GAMEJOLT) - val sources = librarySources(all, SessionPrefs.storesTabOrder(ctx), listOfNotNull(Store.ITCH.id.takeIf { itchSignedIn }, Store.GAMEJOLT.id.takeIf { gameJoltSignedIn }).toSet()) + val sources = librarySources( + all, SessionPrefs.storesTabOrder(ctx), + listOfNotNull(Store.ITCH.id.takeIf { itchSignedIn && !soundMode }, Store.GAMEJOLT.id.takeIf { gameJoltSignedIn && !soundMode }, Library.SOURCE_COLLECTION.takeIf { soundMode }).toSet(), + ) val source = LibraryView.source.takeIf { it == LIBRARY_ALL || it in sources } ?: LIBRARY_ALL val q = LibraryView.query.trim().lowercase() val xboxFilter = if (source == Store.XBOX.id) XboxLibraryFilter.current else XboxLibraryFilter.ALL @@ -265,6 +285,30 @@ internal fun LibraryPage(s: FrontEndState, a: FrontEndActions, selected: String, (source == LIBRARY_ALL || it.source == source) && (q.isEmpty() || it.title.lowercase().contains(q)) && keepsXbox(xboxFilter, it) } val listUninstalled = if (collectionId == null) showUninstalled else collectionShows?.takeIf { it.first == collectionId }?.second ?: true + val trackHits by produceState>(emptyList(), soundMode, q, source, s.soundtracks) { + if (!soundMode || q.isEmpty()) { + value = emptyList() + return@produceState + } + kotlinx.coroutines.delay(150) + value = kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) { + SoundtrackIndex.build(ctx, s.soundtracks) + .filter { (source == LIBRARY_ALL || it.game.source == source) && SoundtrackTracks.matches(q, it.ref.title, it.ref.artist, it.ref.album) } + .distinctBy { it.ref.path } + .sortedWith(compareBy({ SoundtrackTracks.rank(q, it.ref.title) }, { it.ref.title.lowercase() })) + .take(100) + } + } + val shownHits = trackHits.filter { source == LIBRARY_ALL || it.game.source == source } + val hitScope = rememberCoroutineScope() + val playHit: (SoundtrackIndex.Hit) -> Unit = { hit -> + val dir = hit.game.gameFiles + if (dir != null) hitScope.launch { + val album = kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) { Soundtrack.load(ctx, dir, hit.game.art) } + SoundtrackController.play(ctx, album, hit.game.name, hit.ref.path, root = dir) + } + } + var savedDialog by remember { mutableStateOf(false) } val candidates = if (listUninstalled) matching else matching.filter { it.installed } val hiddenUninstalled = if (listUninstalled) 0 else matching.count { !it.installed } val sort = s.storesSort @@ -304,18 +348,20 @@ internal fun LibraryPage(s: FrontEndState, a: FrontEndActions, selected: String, var stable by remember { mutableStateOf(emptyList()) } val ordered = if (sizesPending) retainOrder(candidates, stable) { it.key } else sorted SideEffect { if (!sizesPending) stable = sorted } - val visible = installedFirst(ordered) + val visible = installedFirst(ordered).let { list -> + if (soundMode && source == Library.SOURCE_COLLECTION) list.sortedBy { if (it.game?.appId == SoundtrackCollections.FAVORITES_ID) 0 else 1 } else list + } val split = visible.count { it.installed }.takeIf { it in 1 until visible.size } ?: 0 - val open = selected.takeIf { it.startsWith("app:") } - val back = { onSelect("games") } + val open = selected.takeIf { it.startsWith(if (soundMode) "sound:" else "app:") } + val back = { onSelect(if (soundMode) "soundtracks" else "games") } BackHandler(enabled = open == null && LibraryView.query.isNotEmpty()) { LibraryView.query = "" } BackHandler(enabled = open != null) { back() } val lead = remember { FocusRequester() } var detailFocused by remember { mutableStateOf(false) } var lastOpened by remember { mutableStateOf(null) } val wasOpen = remember { booleanArrayOf(false) } - val backLabel = stringResource(R.string.rail_games) + val backLabel = stringResource(if (soundMode) R.string.rail_soundtracks else R.string.rail_games) LaunchedEffect(open) { val closing = open == null && wasOpen[0] wasOpen[0] = open != null @@ -349,7 +395,7 @@ internal fun LibraryPage(s: FrontEndState, a: FrontEndActions, selected: String, kotlinx.coroutines.delay(Motion.ms(240).toLong()) focusWithinFrames({ ff.last?.startsWith("card:") == true }) { if (ff.firstTileAttached > 0) ff.firstTile else FocusRequester.Default } } - if (all.isEmpty() && open == null && !itchSignedIn && !gameJoltSignedIn) { + if (!soundMode && all.isEmpty() && open == null && !itchSignedIn && !gameJoltSignedIn) { LibraryEmpty(s, a, modifier) return } @@ -385,9 +431,26 @@ internal fun LibraryPage(s: FrontEndState, a: FrontEndActions, selected: String, onOpen = { focusManager.clearFocus(force = true); onSelect(it) }, searchCleared = open != null, onFocus = { gridFocused = it }, + soundMode = soundMode, + emptyText = when { + soundMode && all.isEmpty() -> R.string.soundtracks_empty + soundMode && source == Library.SOURCE_COLLECTION && q.isEmpty() -> R.string.soundtracks_collections_empty + else -> R.string.stores_nothing_matches + }, + onAddSoundtrack = { addingSoundtrack = true }, + onCollections = { savedDialog = true }, + trackHits = shownHits, onPlayHit = playHit, ) }, - ) { key -> GameDetail(key, s, a, lead, backLabel, hopRail = "games", onBack = back) } + ) { key -> + if (soundMode || (!s.soundtracksEnabled && s.soundtracks.any { GameRef.key(it) == key })) SoundtrackDetail(key, s, a, lead, backLabel, onBack = back) + else GameDetail(key, s, a, lead, backLabel, hopRail = "games", onBack = back) + } + if (savedDialog) SavedDialog(emptyList(), onOpen = { id -> onSelect("sound:$id") }) { savedDialog = false } + if (addingSoundtrack) SyncFolderPicker(stringResource(R.string.soundtracks_add_title), null, onDismiss = { addingSoundtrack = false }) { dir -> + addingSoundtrack = false + a.onSoundtrackAdded(dir) + } } @Composable @@ -416,6 +479,8 @@ private fun LibraryGrid( sources: List, source: String, sizesPending: Boolean, syncing: List>, showUninstalled: Boolean?, onShowUninstalled: (Boolean) -> Unit, hiddenUninstalled: Int, onSource: (String) -> Unit, onCycle: (Int) -> Unit, onOpen: (String) -> Unit, onFocus: (Boolean) -> Unit, searchCleared: Boolean, + soundMode: Boolean = false, emptyText: Int = R.string.stores_nothing_matches, onAddSoundtrack: () -> Unit = {}, + onCollections: () -> Unit = {}, trackHits: List = emptyList(), onPlayHit: (SoundtrackIndex.Hit) -> Unit = {}, ) { val listMode = s.storesView == "list" val capsules = s.storesView == "capsules" @@ -438,7 +503,7 @@ private fun LibraryGrid( val next = storeGridNeighbor(index, visible.size, if (listMode) 1 else columns, direction, split) when { direction == 0 || index < 0 -> false - next == null -> direction > 0 + next == null -> direction > 0 && trackHits.isEmpty() else -> { if (key.action == KeyEvent.ACTION_DOWN) { val target = "card:${visible[next].key}" @@ -470,7 +535,7 @@ private fun LibraryGrid( contentPadding = PaddingValues(top = 4.dp, bottom = 16.dp), ) { item(key = "header", span = { GridItemSpan(maxLineSpan) }) { - Rise(0) { LibraryHeader(s, a, total, searchCleared, source == Store.XBOX.id, showUninstalled, onShowUninstalled, collections = Store.byId(source)?.takeIf { it == Store.ITCH || it == Store.GAMEJOLT }) } + Rise(0) { LibraryHeader(s, a, total, searchCleared, source == Store.XBOX.id, showUninstalled, onShowUninstalled, collections = Store.byId(source)?.takeIf { it == Store.ITCH || it == Store.GAMEJOLT }, soundMode = soundMode, onAddSoundtrack = onAddSoundtrack, onCollections = onCollections) } } item(key = "filters", span = { GridItemSpan(maxLineSpan) }) { Rise(1) { LibraryFilters(sources, source, onSource) } @@ -488,7 +553,7 @@ private fun LibraryGrid( Text(stringResource(R.string.store_section_loading), fontSize = 11.sp, color = MaterialTheme.colorScheme.onSurfaceVariant) } } - val empty = R.string.stores_nothing_matches + val empty = emptyText if (visible.isEmpty() && hiddenUninstalled > 0) item(key = "browse-owned", span = { GridItemSpan(maxLineSpan) }) { Column(horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(12.dp), modifier = Modifier.fillMaxWidth().padding(vertical = 32.dp)) { Text(stringResource(R.string.library_no_installed_matches), fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant) @@ -502,6 +567,40 @@ private fun LibraryGrid( item(key = "not-installed-label", span = { GridItemSpan(maxLineSpan) }) { SectionLabel(stringResource(R.string.stores_section_not_installed)) } libraryGrid(visible.drop(split), empty, tile) } + if (trackHits.isNotEmpty()) { + item(key = "tracks-label", span = { GridItemSpan(maxLineSpan) }) { SectionLabel(stringResource(R.string.soundtracks_tracks_heading)) } + items(trackHits, key = { "track:${it.ref.path}" }, span = { GridItemSpan(maxLineSpan) }, contentType = { "track" }) { hit -> TrackHitRow(hit, onPlayHit) } + } + } +} + +@Composable +private fun TrackHitRow(hit: SoundtrackIndex.Hit, onPlay: (SoundtrackIndex.Hit) -> Unit) { + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + val src = remember { MutableInteractionSource() } + val hot = rememberHot(src) + val shape = RoundedCornerShape(10.dp) + val cover = hit.ref.cover.takeIf { it.isNotEmpty() }?.let { java.io.File(it) }?.takeIf { it.isFile } + Row( + verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp), + modifier = Modifier.fillMaxWidth().heightIn(min = 56.dp).paneItem("trackhit:${hit.ref.path}").testTag("track-hit") + .clip(shape).glideBorder(hot, shape, pal.signal, pal.line) + .hoverable(src).clickable(role = Role.Button, interactionSource = src, indication = LocalIndication.current) { onPlay(hit) } + .controllerConfirm { onPlay(hit) } + .padding(horizontal = 10.dp, vertical = 6.dp), + ) { + Box(Modifier.size(44.dp).clip(RoundedCornerShape(8.dp)).background(artBrush(hueOf(hit.ref.album)))) { + if (cover != null) AsyncImage(model = cover, contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier.matchParentSize()) + } + Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) { + Text(hit.ref.title, fontSize = 14.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis) + Text( + listOf(hit.ref.album, hit.ref.artist).filter { it.isNotBlank() }.joinToString(" ยท "), + fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis, + ) + } + if (hit.ref.durationMs > 0) Text(Soundtrack.formatLength(hit.ref.durationMs), fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1) } } @@ -532,28 +631,31 @@ private fun LazyGridScope.libraryGrid(entries: List, empty: Int, t private fun LibraryHeader( s: FrontEndState, a: FrontEndActions, total: Int, searchCleared: Boolean, xbox: Boolean, showUninstalled: Boolean?, onShowUninstalled: (Boolean) -> Unit, collections: Store?, + soundMode: Boolean = false, onAddSoundtrack: () -> Unit = {}, onCollections: () -> Unit = {}, ) { val colors = MaterialTheme.colorScheme val narrow = LocalNarrowPane.current + val heading = stringResource(if (soundMode) R.string.rail_soundtracks else R.string.rail_games) ModeHeader( - stringResource(R.string.rail_games), LibraryView.query, { LibraryView.query = it }, - placeholder = stringResource(R.string.stores_search_library), + heading, LibraryView.query, { LibraryView.query = it }, + placeholder = stringResource(if (soundMode) R.string.soundtracks_search else R.string.stores_search_library), clearSearchFocus = searchCleared, inlineWhenStacked = true, lead = { Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.padding(start = 2.dp, end = 4.dp)) { - Text(stringResource(R.string.rail_games), fontSize = if (narrow) 20.sp else 24.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, maxLines = 1) - Text(pluralStringResource(R.plurals.mode_added_count, total, total), fontSize = 13.sp, color = colors.onSurfaceVariant, maxLines = 1) + Text(heading, fontSize = if (narrow) 20.sp else 24.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, maxLines = 1) + Text(if (soundMode) total.toString() else pluralStringResource(R.plurals.mode_added_count, total, total), fontSize = 13.sp, color = colors.onSurfaceVariant, maxLines = 1) if (s.steamGamesX64 && !narrow) ClientTag() } }, ) { + if (soundMode) HeaderIconButton(stringResource(R.string.soundtracks_saved), Icons.Filled.BookmarkBorder, "collections", onCollections) DisplayButton() - if (showUninstalled != null || xbox) LibraryFilterButton(showUninstalled, onShowUninstalled, xbox) + if (!soundMode && (showUninstalled != null || xbox)) LibraryFilterButton(showUninstalled, onShowUninstalled, xbox) if (collections != null) CollectionsButton(collections) SortButton(s, a) ViewButton(s, a) - GameFileFolderActions(s, a) - if (!s.shortcutPicker) AddGameButton { GamesDialogState.adding = true } + if (!soundMode) GameFileFolderActions(s, a) + if (!s.shortcutPicker) AddGameButton { if (soundMode) onAddSoundtrack() else GamesDialogState.adding = true } } if (s.steamGamesX64 && narrow) Box(Modifier.padding(top = 4.dp)) { ClientTag() } } @@ -570,7 +672,7 @@ private fun LibraryFilters(sources: List, source: String, onSource: (Str val store = Store.byId(src) val dot = when { store != null -> sourceColours(src).dot.copy(alpha = if (StoresState.isSignedIn(store) && StoresState.expired[store] != true) 1f else 0.35f) - src == Library.SOURCE_STEAM -> sourceColours(src).dot + src == Library.SOURCE_STEAM || src == Library.ADDED || src == Library.SOURCE_COLLECTION -> sourceColours(src).dot else -> null } SourceFilterChip(src, if (src == Library.ADDED) stringResource(R.string.library_filter_added) else store?.shortLabel ?: sourceLabel(src), source == src, dot) { onSource(src) } @@ -649,7 +751,7 @@ private fun LibraryArt(e: LibraryEntry, wide: Any?, tall: Any?, download: Downlo } ArtCard( e.title, wide, tall, download, hot, capsule, chip, - badge = if (showSource) ({ SourceChip(e.source, small = true, modifier = Modifier.align(Alignment.TopStart).padding(6.dp)) }) else null, + badge = if (showSource) ({ SourceChip(e.source, small = true, modifier = Modifier.align(Alignment.TopStart).padding(6.dp), label = favoritesBadge(e), colours = favoritesColours(e)) }) else null, ) { LibrarySize(e) } } @@ -786,7 +888,7 @@ private fun LibraryRow(e: LibraryEntry, first: Boolean, navigation: Modifier, ch Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(3.dp)) { Text(e.title, fontSize = 14.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis) Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) { - SourceChip(e.source, small = true) + SourceChip(e.source, small = true, label = favoritesBadge(e), colours = favoritesColours(e)) Text(meta.joinToString(" ยท "), fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis) } } @@ -1004,3 +1106,10 @@ private fun ViewButton(s: FrontEndState, a: FrontEndActions) { "view", ) { a.onStoresView(next) } } + +@Composable +private fun favoritesBadge(e: LibraryEntry): String? = + if (e.game?.appId == SoundtrackCollections.FAVORITES_ID && e.source == Library.SOURCE_COLLECTION) stringResource(R.string.soundtracks_favorites) else null + +private fun favoritesColours(e: LibraryEntry): SourceColours? = + if (e.game?.appId == SoundtrackCollections.FAVORITES_ID && e.source == Library.SOURCE_COLLECTION) FavoritesColours else null diff --git a/app/src/main/java/com/droiddeck/launcher/ui/MorePage.kt b/app/src/main/java/com/droiddeck/launcher/ui/MorePage.kt new file mode 100644 index 0000000000..b4d6952413 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/MorePage.kt @@ -0,0 +1,98 @@ +package com.droiddeck.launcher.ui + +import androidx.compose.foundation.LocalIndication +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.hoverable +import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.BoxWithConstraints +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.rememberScrollState +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.remember +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.Role +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 + +@Composable +internal fun MorePage(s: FrontEndState, a: FrontEndActions, onSelect: (String) -> Unit, modifier: Modifier) { + val keys = NavTabs.more(s) + val open: (String) -> Unit = { key -> if (key == "components") a.onComponents(true) else onSelect(key) } + Column(modifier.verticalScroll(rememberScrollState())) { + PageHeader(stringResource(R.string.rail_more)) { + Spacer(Modifier.weight(1f)) + SecondaryButton(stringResource(R.string.more_edit_tabs), compact = true) { + SetupTabs.openLauncher = true + SetupTabs.focusTabs = true + onSelect("setup") + } + } + BoxWithConstraints(Modifier.fillMaxWidth()) { + val gap = 12.dp + val columns = ((maxWidth + gap) / (160.dp + gap)).toInt().coerceIn(2, 5) + Column(verticalArrangement = Arrangement.spacedBy(gap)) { + keys.chunked(columns).forEachIndexed { r, row -> + Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(gap)) { + row.forEachIndexed { c, key -> + MoreTile(s, key, first = r == 0 && c == 0, Modifier.weight(1f)) { open(key) } + } + repeat(columns - row.size) { Spacer(Modifier.weight(1f)) } + } + } + } + } + } +} + +@Composable +private fun MoreTile(s: FrontEndState, key: String, first: Boolean, modifier: Modifier, onClick: () -> Unit) { + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + val (label, icon) = railLabelIcon(key) + val src = remember { MutableInteractionSource() } + val hot = rememberHot(src) + val shape = RoundedCornerShape(18.dp) + val count = railCount(s, key) + Box( + contentAlignment = Alignment.Center, + modifier = modifier + .then(if (first) Modifier.paneEntry() else Modifier.paneItem("more:$key")) + .testTag("more-$key") + .height(112.dp).clip(shape) + .background(if (hot) pal.signal.copy(alpha = 0.12f) else colors.surface) + .glideBorder(hot, shape, pal.signal, pal.line) + .hoverable(src) + .clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Tab, onClick = onClick) + .controllerConfirm(onClick = onClick), + ) { + Column(horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(8.dp)) { + Icon(icon, contentDescription = null, tint = if (hot) pal.signal else colors.onSurfaceVariant, modifier = Modifier.size(30.dp)) + Text(stringResource(label), fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, + maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.padding(horizontal = 8.dp)) + } + if (railBadge(s, key)) Box(Modifier.align(Alignment.TopEnd).padding(12.dp).size(9.dp).clip(CircleShape).background(AttentionAmber)) + if (count > 0) Box(Modifier.align(Alignment.TopEnd).padding(10.dp)) { CountPill(count) } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/NavTabs.kt b/app/src/main/java/com/droiddeck/launcher/ui/NavTabs.kt new file mode 100644 index 0000000000..46a23fabc4 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/NavTabs.kt @@ -0,0 +1,91 @@ +package com.droiddeck.launcher.ui + +import android.content.Context +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import com.droiddeck.launcher.agent.AgentHost +import com.droiddeck.launcher.agent.AgentTab +import com.droiddeck.launcher.session.SessionPrefs + +internal enum class TabPlace { BAR, MORE, HIDDEN } + +internal object NavTabs { + const val MORE = "more" + val FEATURES = setOf("stores", "soundtracks", "agent") + val ALL = listOf("steam", "games", "soundtracks", "stores", "desktop", "agent", "components", "android-apps", "setup", "updates", "trinkets") + + var order by mutableStateOf(ALL) + private set + var shelved by mutableStateOf(emptySet()) + private set + var hidden by mutableStateOf(emptySet()) + private set + + fun load(context: Context) { + order = arrange(SessionPrefs.navTabOrder(context)) + shelved = SessionPrefs.navTabShelved(context).intersect(ALL.toSet()) + hidden = SessionPrefs.navTabHidden(context).intersect(ALL.toSet()) - FEATURES - "setup" + } + + fun arrange(saved: List): List { + val listed = saved.filter { it in ALL }.distinct() + val missing = ALL.filterNot { it in listed } + val out = listed.toMutableList() + for (key in missing) { + val before = ALL.subList(0, ALL.indexOf(key)).lastOrNull { it in out } + out.add(if (before == null) 0 else out.indexOf(before) + 1, key) + } + return out + } + + fun available(s: FrontEndState, key: String): Boolean = when (key) { + "android-apps" -> s.isHomeApp + "agent" -> AgentHost.available + else -> true + } + + fun hideable(key: String) = key != "setup" + + fun place(s: FrontEndState, key: String): TabPlace = when { + featureOff(s, key) || key in hidden -> TabPlace.HIDDEN + key in shelved -> TabPlace.MORE + else -> TabPlace.BAR + } + + private fun featureOff(s: FrontEndState, key: String) = when (key) { + "stores" -> !s.gameStoresEnabled + "soundtracks" -> !s.soundtracksEnabled + "agent" -> !AgentTab.shown + else -> false + } + + fun listed(s: FrontEndState) = order.filter { available(s, it) } + + fun more(s: FrontEndState) = listed(s).filter { place(s, it) == TabPlace.MORE } + + fun bar(s: FrontEndState): List { + val shown = listed(s).filter { place(s, it) == TabPlace.BAR } + return if (more(s).isEmpty()) shown else shown + MORE + } + + fun move(context: Context, s: FrontEndState, key: String, step: Int) { + val visible = listed(s) + val at = visible.indexOf(key) + val other = visible.getOrNull(at + step) ?: return + val next = order.toMutableList() + val i = next.indexOf(key) + val j = next.indexOf(other) + next[i] = other + next[j] = key + order = next + SessionPrefs.setNavTabOrder(context, next) + } + + fun setPlace(context: Context, key: String, place: TabPlace) { + shelved = if (place == TabPlace.MORE) shelved + key else shelved - key + hidden = if (place == TabPlace.HIDDEN && hideable(key) && key !in FEATURES) hidden + key else hidden - key + SessionPrefs.setNavTabShelved(context, shelved) + SessionPrefs.setNavTabHidden(context, hidden) + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SessionDrawerPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/SessionDrawerPage.kt index a0d75f027a..cb438903b7 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SessionDrawerPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SessionDrawerPage.kt @@ -14,7 +14,7 @@ internal enum class SessionDrawerPage(val firstControl: String) { } internal fun sessionDrawerPages( - hasSecondScreen: Boolean, hasGlasses: Boolean = false, hasAgent: Boolean = com.droiddeck.launcher.agent.AgentHost.installed, + hasSecondScreen: Boolean, hasGlasses: Boolean = false, hasAgent: Boolean = com.droiddeck.launcher.agent.AgentHost.installed && com.droiddeck.launcher.agent.AgentTab.shown, ): List = SessionDrawerPage.entries.filter { (hasSecondScreen || it != SessionDrawerPage.SECOND_SCREEN) && (hasGlasses || it != SessionDrawerPage.GLASSES) && diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt b/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt index 5752578234..94f4ff1a3c 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt @@ -220,6 +220,9 @@ class DrawerActions( val hudOn: Boolean, val hudConfig: Map = emptyMap(), val frameGen: FrameGen.Mode, + val frameGenTargetGameId: String? = null, + val frameGenTargetGameName: String? = null, + val hasGameOverride: Boolean = false, val lossless: Lossless.State, val oscMode: String, val suspendPolicy: String, @@ -262,6 +265,7 @@ class DrawerActions( val onHudReset: () -> Unit = {}, val onHudExport: () -> Unit = {}, val onFrameGenPick: (FrameGen.Mode) -> Unit, + val onFrameGenReset: () -> Unit = {}, val fpsLimit: Int = 0, val onFpsLimit: (Int) -> Unit = {}, val onImportLossless: () -> Unit, @@ -558,6 +562,7 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont Modifier.weight(1f).fillMaxWidth().padding(top = 8.dp, start = 14.dp, end = 14.dp), inputModifier = focus.track(page, "agent-input"), visible = open, + startTyping = false, ) else Column( modifier = Modifier.weight(1f).fillMaxWidth().verticalScroll(pageScroll.getValue(page)), ) { CompositionLocalProvider(LocalChipMinWidth provides 96.dp, LocalCompactSettings provides true) { @@ -568,10 +573,21 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont val fgOpen = host.open == "fg" val offLabel = stringResource(R.string.frame_gen_off) val fgLabel = FrameGen.label(LocalContext.current, a.frameGen) - SettingsRow(stringResource(R.string.frame_gen_title), null, highlighted = fgOpen) { + SettingsRow( + stringResource(R.string.frame_gen_title), + if (a.frameGenTargetGameId != null) + "${stringResource(R.string.frame_gen_scope_game)} ยท ${a.frameGenTargetGameName ?: "ID ${a.frameGenTargetGameId}"}" + else stringResource(R.string.frame_gen_scope_global), + highlighted = fgOpen + ) { Box { ValueChip(fgLabel, fgOpen, modifier = focus.track(page, "fg")) { host.open = if (fgOpen) null else "fg" } - FrameGenMenu(host, a.frameGen, a.lossless, a.onFrameGenPick, a.onImportLossless) + FrameGenMenu( + host, a.frameGen, a.lossless, a.onFrameGenPick, a.onImportLossless, + gameProfileId = a.frameGenTargetGameId, + hasGameOverride = a.hasGameOverride, + onResetGame = a.onFrameGenReset, + ) } } if (a.direct) SliderRow( @@ -1351,6 +1367,12 @@ private fun SelectedGameProfileGroup(host: MenuHost, a: DrawerActions, track: (S if (!profile.fexPreset.inherited) { ProfileSummaryRow(stringResource(R.string.comp_game_fex), fexProfileLabel(profile.fexPreset)) } + if (!profile.frameGenInherited) { + ProfileSummaryRow( + stringResource(R.string.frame_gen_title), + FrameGen.label(LocalContext.current, profile.frameGen), + ) + } if (!profile.proton.inherited) { ProfileSummaryRow(stringResource(R.string.comp_proton), profileValueLabel(profile.proton)) } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SoundtrackCollectionsUi.kt b/app/src/main/java/com/droiddeck/launcher/ui/SoundtrackCollectionsUi.kt new file mode 100644 index 0000000000..2bf1314621 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/SoundtrackCollectionsUi.kt @@ -0,0 +1,295 @@ +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.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Add +import androidx.compose.material.icons.filled.Bookmark +import androidx.compose.material.icons.filled.Check +import androidx.compose.material.icons.filled.Delete +import androidx.compose.material.icons.filled.Edit +import androidx.compose.material.icons.filled.Remove +import androidx.compose.material.icons.filled.CheckBox +import androidx.compose.material.icons.filled.CheckBoxOutlineBlank +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.Icon +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.produceState +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.layout.ContentScale +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.stringResource +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.input.ImeAction +import androidx.compose.ui.text.input.KeyboardType +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.R +import com.droiddeck.launcher.frontend.Library +import com.droiddeck.launcher.frontend.Soundtrack +import com.droiddeck.launcher.frontend.SoundtrackCollections +import com.droiddeck.launcher.frontend.SoundtrackIndex +import com.droiddeck.launcher.frontend.SoundtrackTracks +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext + +@Composable +internal fun SavedDialog(pending: List, onOpen: ((Int) -> Unit)?, onDismiss: () -> Unit) { + val ctx = LocalContext.current + val colors = MaterialTheme.colorScheme + remember { SoundtrackCollections.load(ctx) } + val snapshot = SoundtrackCollections.snapshot + val favoritesLabel = stringResource(R.string.soundtracks_favorites) + var naming by remember { mutableStateOf(false) } + val rows = listOf(Triple(SoundtrackCollections.FAVORITES_ID, favoritesLabel, snapshot.favorites)) + + snapshot.collections.map { Triple(it.id, it.name, it.tracks) } + AlertDialog( + onDismissRequest = onDismiss, + title = { + Row(verticalAlignment = Alignment.CenterVertically) { + Text(stringResource(R.string.soundtracks_saved), modifier = Modifier.weight(1f)) + Icon(Icons.Filled.Bookmark, contentDescription = null, tint = colors.onSurfaceVariant) + } + }, + text = { + Column(Modifier.verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(8.dp)) { + SavedRow(stringResource(R.string.soundtracks_create_collection), stringResource(R.string.soundtracks_organise), null, "saved-create", null) { + TextButton(onClick = { naming = true }, modifier = Modifier.focusGlide(CircleShape).testTag("saved-new")) { + Icon(Icons.Filled.Add, contentDescription = null, modifier = Modifier.size(18.dp)) + Text(stringResource(R.string.soundtracks_new)) + } + } + for ((id, name, tracks) in rows) { + val cover = tracks.firstNotNullOfOrNull { t -> t.cover.takeIf { it.isNotEmpty() }?.let { java.io.File(it) }?.takeIf { it.isFile } } + val subtitle = stringResource(R.string.soundtracks_length_value, tracks.size, Soundtrack.formatLength(tracks.sumOf { it.durationMs })) + val added = pending.isNotEmpty() && pending.all { p -> tracks.any { it.path == p.path } } + SavedRow(name, subtitle, cover, "saved-$id", if (pending.isEmpty() && onOpen != null) ({ onDismiss(); onOpen(id) }) else null) { + if (pending.isNotEmpty()) CircleAction(if (added) Icons.Filled.Check else Icons.Filled.Add, name, "saved-add-$id") { + if (added) SoundtrackCollections.remove(ctx, id, pending.map { it.path }.toSet()) + else SoundtrackCollections.add(ctx, id, pending) + } + } + } + } + }, + confirmButton = { TextButton(onClick = onDismiss, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_close)) } }, + ) + if (naming) NameDialog( + stringResource(R.string.soundtracks_create_collection), "", stringResource(R.string.soundtracks_create), + onConfirm = { name -> + val id = SoundtrackCollections.create(ctx, name, pending) + if (id != null && pending.isEmpty() && onOpen != null) { onDismiss(); onOpen(id) } + id != null + }, + onDismiss = { naming = false }, + ) +} + +@Composable +private fun SavedRow(title: String, subtitle: String, cover: Any?, tag: String, onClick: (() -> Unit)?, trailing: @Composable () -> Unit) { + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + val src = remember { MutableInteractionSource() } + val hot = rememberHot(src) && onClick != null + val shape = RoundedCornerShape(10.dp) + Row( + verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp), + modifier = Modifier.fillMaxWidth().testTag(tag).clip(shape).background(if (hot) pal.signal.copy(alpha = 0.12f) else Color.Transparent) + .glideBorder(hot, shape, pal.signal, Color.Transparent) + .then( + if (onClick != null) Modifier.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Button, onClick = onClick) + .controllerConfirm(onClick = onClick) + else Modifier, + ) + .padding(vertical = 4.dp), + ) { + Box(Modifier.size(52.dp).clip(RoundedCornerShape(8.dp)).background(Color.White.copy(alpha = 0.08f))) { + if (cover != null) AsyncImage(cover, contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier.matchParentSize()) + } + Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) { + Text(title, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onSurface, maxLines = 1, overflow = TextOverflow.Ellipsis) + Text(subtitle, fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis) + } + trailing() + } +} + +@Composable +private fun CircleAction(icon: androidx.compose.ui.graphics.vector.ImageVector, label: String, tag: String, onClick: () -> Unit) { + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + val src = remember { MutableInteractionSource() } + val hot = rememberHot(src) + Box( + contentAlignment = Alignment.Center, + modifier = Modifier.testTag(tag).size(40.dp).clip(CircleShape).background(if (hot) pal.signal.copy(alpha = 0.16f) else Color.Transparent) + .border(1.dp, if (hot) pal.signal else colors.onSurface.copy(alpha = 0.7f), CircleShape) + .hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Button, onClick = onClick) + .controllerConfirm(onClick = onClick) + .semantics { contentDescription = label }, + ) { Icon(icon, contentDescription = null, tint = colors.onSurface, modifier = Modifier.size(20.dp)) } +} + +@Composable +internal fun NameDialog(title: String, initial: String, confirm: String, onConfirm: (String) -> Boolean, onDismiss: () -> Unit) { + var text by remember { mutableStateOf(initial) } + var invalid by remember { mutableStateOf(false) } + val submit: () -> Unit = { + val ok = onConfirm(text) + if (ok) onDismiss() + invalid = !ok + } + AlertDialog( + onDismissRequest = onDismiss, + title = { Text(title) }, + text = { + Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { + AdbTextField( + value = text, onValueChange = { text = it; invalid = false }, label = stringResource(R.string.soundtracks_collection_name), + keyboardType = KeyboardType.Text, imeAction = ImeAction.Done, focusOnShow = true, onDone = submit, + ) + if (invalid) Text(stringResource(R.string.soundtracks_name_invalid), fontSize = 12.sp, color = MaterialTheme.colorScheme.error) + } + }, + confirmButton = { TextButton(onClick = submit, modifier = Modifier.focusGlide(CircleShape).testTag("name-confirm")) { Text(confirm) } }, + dismissButton = { TextButton(onClick = onDismiss, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) } }, + ) +} + +@Composable +internal fun ManageDialog(id: Int, games: List, onRemoveMode: () -> Unit, onDismiss: () -> Unit) { + val ctx = LocalContext.current + val name = SoundtrackCollections.snapshot.collections.firstOrNull { it.id == id }?.name.orEmpty() + val favorites = id == SoundtrackCollections.FAVORITES_ID + var renaming by remember { mutableStateOf(false) } + var adding by remember { mutableStateOf(false) } + var deleting by remember { mutableStateOf(false) } + val shown = rememberShown(onDismiss) + val close = { shown.targetState = false } + AppDialog(shown, close, "soundtrackManage", wide = false, maxWidth = 420.dp) { + Column(verticalArrangement = Arrangement.spacedBy(6.dp), modifier = Modifier.fillMaxWidth()) { + DialogTitleRow(stringResource(R.string.soundtracks_manage), onClose = close) + if (!favorites) PickerRow(Icons.Filled.Edit, stringResource(R.string.soundtracks_rename), null) { renaming = true } + PickerRow(Icons.Filled.Add, stringResource(R.string.soundtracks_add_tracks), null) { adding = true } + PickerRow(Icons.Filled.Remove, stringResource(R.string.soundtracks_remove_tracks), null) { onDismiss(); onRemoveMode() } + if (!favorites) PickerRow(Icons.Filled.Delete, stringResource(R.string.soundtracks_delete_collection), null) { deleting = true } + } + } + if (renaming) NameDialog( + stringResource(R.string.soundtracks_rename), name, stringResource(R.string.soundtracks_rename), + onConfirm = { SoundtrackCollections.rename(ctx, id, it) }, onDismiss = { renaming = false }, + ) + if (adding) TrackPickerDialog(id, games) { adding = false } + if (deleting) ConfirmDialog( + title = stringResource(R.string.soundtracks_delete_title, name), text = stringResource(R.string.soundtracks_delete_body), + confirm = stringResource(R.string.common_delete), + onConfirm = { SoundtrackCollections.delete(ctx, id); onDismiss() }, + onDismiss = { deleting = false }, + ) +} + +@Composable +internal fun TrackPickerDialog(id: Int, games: List, onDismiss: () -> Unit) { + val ctx = LocalContext.current + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + val hits by produceState?>(null, games) { value = withContext(Dispatchers.IO) { SoundtrackIndex.build(ctx, games) } } + var query by remember { mutableStateOf("") } + var picked by remember { mutableStateOf(setOf()) } + val have = SoundtrackCollections.tracksOf(id).mapTo(HashSet()) { it.path } + val list = hits?.distinctBy { it.ref.path }?.filter { it.ref.path !in have && SoundtrackTracks.matches(query, it.ref.title, it.ref.artist, it.ref.album) } + AlertDialog( + onDismissRequest = onDismiss, + title = { Text(stringResource(R.string.soundtracks_add_tracks)) }, + text = { + Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { + AdbTextField( + value = query, onValueChange = { query = it }, label = "", keyboardType = KeyboardType.Text, imeAction = ImeAction.Search, + placeholder = stringResource(R.string.soundtracks_search_tracks), compact = true, + ) + Row(horizontalArrangement = Arrangement.spacedBy(4.dp), verticalAlignment = Alignment.CenterVertically) { + TextButton(onClick = { picked = picked + list.orEmpty().map { it.ref.path } }, modifier = Modifier.focusGlide(CircleShape)) { + Text(stringResource(R.string.soundtracks_select_all)) + } + TextButton(onClick = { picked = emptySet() }, modifier = Modifier.focusGlide(CircleShape)) { + Text(stringResource(R.string.soundtracks_deselect_all)) + } + } + if (list == null) Text(stringResource(R.string.store_section_loading), fontSize = 13.sp, color = colors.onSurfaceVariant) + else LazyColumn(Modifier.fillMaxWidth().heightIn(max = 340.dp).testTag("track-picker")) { + items(list, key = { it.ref.path }) { hit -> + val on = hit.ref.path in picked + val src = remember { MutableInteractionSource() } + val hot = rememberHot(src) + val toggle = { picked = if (on) picked - hit.ref.path else picked + hit.ref.path } + Row( + verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp), + modifier = Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp)).background(if (on) pal.signal.copy(alpha = 0.16f) else if (hot) Color.White.copy(alpha = 0.08f) else Color.Transparent) + .hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Checkbox, onClick = toggle) + .controllerConfirm(onClick = toggle).padding(horizontal = 8.dp, vertical = 8.dp), + ) { + Icon( + if (on) Icons.Filled.CheckBox else Icons.Filled.CheckBoxOutlineBlank, contentDescription = null, + tint = if (on) pal.signal else colors.onSurfaceVariant, modifier = Modifier.size(20.dp), + ) + Column(Modifier.weight(1f)) { + Text(hit.ref.title, fontSize = 14.sp, color = colors.onSurface, maxLines = 1, overflow = TextOverflow.Ellipsis) + Text( + listOf(hit.ref.album, hit.ref.artist).filter { it.isNotBlank() }.joinToString(" ยท "), + fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis, + ) + } + if (hit.ref.durationMs > 0) Text(Soundtrack.formatLength(hit.ref.durationMs), fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1) + } + } + } + } + }, + confirmButton = { + TextButton( + enabled = picked.isNotEmpty(), + onClick = { + SoundtrackCollections.add(ctx, id, hits.orEmpty().filter { it.ref.path in picked }.map { it.ref }) + onDismiss() + }, + modifier = Modifier.focusGlide(CircleShape).testTag("picker-add"), + ) { Text(stringResource(R.string.soundtracks_add_count, picked.size)) } + }, + dismissButton = { TextButton(onClick = onDismiss, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) } }, + ) +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SoundtrackDetail.kt b/app/src/main/java/com/droiddeck/launcher/ui/SoundtrackDetail.kt new file mode 100644 index 0000000000..896e94c343 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/SoundtrackDetail.kt @@ -0,0 +1,391 @@ +package com.droiddeck.launcher.ui + +import androidx.compose.foundation.LocalIndication +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.hoverable +import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.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.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.lazy.rememberLazyListState +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.BookmarkBorder +import androidx.compose.material.icons.filled.Favorite +import androidx.compose.material.icons.filled.FavoriteBorder +import androidx.compose.material.icons.filled.Pause +import androidx.compose.material.icons.filled.PlayArrow +import androidx.compose.material.icons.filled.Repeat +import androidx.compose.material.icons.filled.RepeatOne +import androidx.compose.material.icons.filled.Shuffle +import androidx.compose.material.icons.filled.SkipNext +import androidx.compose.material.icons.filled.SkipPrevious +import androidx.compose.material.icons.filled.VolumeOff +import androidx.compose.material.icons.filled.VolumeUp +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Slider +import androidx.compose.material3.SliderDefaults +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableFloatStateOf +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.produceState +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.focus.FocusRequester +import androidx.compose.ui.focus.focusRequester +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.layout.ContentScale +import androidx.compose.ui.platform.LocalConfiguration +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.stringResource +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.TextAlign +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import androidx.media3.common.Player +import coil.compose.AsyncImage +import com.droiddeck.launcher.R +import com.droiddeck.launcher.frontend.Library +import com.droiddeck.launcher.frontend.Soundtrack +import com.droiddeck.launcher.frontend.SoundtrackCollections +import com.droiddeck.launcher.frontend.SoundtrackOrder +import com.droiddeck.launcher.playback.SoundtrackController +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.delay +import kotlinx.coroutines.withContext + +@Composable +internal fun SoundtrackDetail(key: String, s: FrontEndState, a: FrontEndActions, lead: FocusRequester, backLabel: String, onBack: () -> Unit) { + val appId = remember(key) { key.removePrefix("sound:").removePrefix("app:").toIntOrNull() } + val ctx = LocalContext.current + remember { SoundtrackCollections.load(ctx) } + val favoritesLabel = stringResource(R.string.soundtracks_favorites) + val snapshot = SoundtrackCollections.snapshot + val saved = remember(snapshot, favoritesLabel) { SoundtrackCollections.games(ctx, favoritesLabel) } + val game = s.soundtracks.firstOrNull { it.appId == appId } ?: saved.firstOrNull { it.appId == appId } + LaunchedEffect(game == null, s.soundtracksLoaded) { if (game == null && s.soundtracksLoaded) onBack() } + if (game == null) return + val narrow = LocalNarrowPane.current + val stacked = narrow || LocalConfiguration.current.screenWidthDp < 700 + val root = game.gameFiles + val collectionId = if (game.source == Library.SOURCE_COLLECTION) game.appId else null + val target = remember(root, collectionId) { PlayTarget(root, collectionId) } + val loadedAlbum by produceState(null, root, game.art, SoundtrackOrder.version) { + value = root?.let { dir -> withContext(Dispatchers.IO) { Soundtrack.load(ctx, dir, game.art) } } + } + val collectionAlbum = remember(snapshot, collectionId) { collectionId?.let { SoundtrackCollections.album(ctx, it) } } + val album = collectionAlbum ?: loadedAlbum + LaunchedEffect(Unit) { SoundtrackController.connect(ctx) } + val inset = LocalDetailInset.current + val currentTrack = if (target.belongs) SoundtrackController.currentId else null + val trackArt by produceState(null, currentTrack) { + value = currentTrack?.let { id -> withContext(Dispatchers.IO) { Soundtrack.trackCover(ctx, java.io.File(id)) } } + } + val pinned = game.art?.path.orEmpty().let { it.contains("/steam-art/") || it.contains("/soundtrack-art/") } + val art: Any? = if (pinned) game.art else trackArt ?: game.art ?: album?.cover + val refs = remember(snapshot, collectionId) { collectionId?.let { id -> SoundtrackCollections.tracksOf(id).associateBy { it.path } }.orEmpty() } + val coverPath = (game.art ?: album?.cover)?.path.orEmpty() + val refOf: (Soundtrack.Track) -> SoundtrackCollections.TrackRef = { t -> + refs[t.id] ?: SoundtrackCollections.TrackRef(t.id, t.title, t.artist.ifBlank { album?.artist.orEmpty() }, game.name, t.durationMs, coverPath) + } + var selectRequest by remember { mutableIntStateOf(0) } + val onReorder: ((List) -> Unit)? = when { + collectionId != null -> ({ paths: List -> SoundtrackCollections.reorder(ctx, collectionId, paths) }) + game.library == Library.ADDED && root != null -> ({ paths: List -> SoundtrackOrder.set(ctx, root, paths) }) + else -> null + } + GameBackdrop(art, art, hueOf(game.name), fadeTop = inset.top < 8.dp, artBlur = 24.dp) { + Column(Modifier.fillMaxWidth().padding(horizontal = inset.horizontal).padding(top = inset.top)) { + Rise(0) { + Row(Modifier.fillMaxWidth().padding(bottom = 8.dp), verticalAlignment = Alignment.CenterVertically) { + Box(Modifier.glass(CircleShape)) { BackLink(backLabel, compact = true, onClick = onBack) } + Spacer(Modifier.weight(1f)) + SourceBadge(game.source) + } + } + val loaded = album + if (stacked) Column(verticalArrangement = Arrangement.spacedBy(14.dp)) { + Rise(1) { SoundtrackPlayer(game, loaded, art, lead, s, a, target, refOf, collectionId) { selectRequest++ } } + if (loaded != null) Rise(2) { + TrackPanel(loaded, game.name, target, refOf, collectionId, selectRequest, onReorder, Modifier.fillMaxWidth().height((LocalConfiguration.current.screenHeightDp * 0.55f).dp)) + } + } else Row(horizontalArrangement = Arrangement.spacedBy(28.dp), modifier = Modifier.fillMaxWidth()) { + Rise(1, Modifier.weight(0.42f)) { SoundtrackPlayer(game, loaded, art, lead, s, a, target, refOf, collectionId) { selectRequest++ } } + if (loaded != null) Rise(2, Modifier.weight(0.58f)) { + TrackPanel(loaded, game.name, target, refOf, collectionId, selectRequest, onReorder, Modifier.fillMaxWidth().height((LocalConfiguration.current.screenHeightDp * 0.72f).dp)) + } + } + } + } +} + +@Composable +private fun SoundtrackPlayer( + game: Library.SteamGame, album: Soundtrack.Album?, art: Any?, lead: FocusRequester, s: FrontEndState, a: FrontEndActions, + target: PlayTarget, refOf: (Soundtrack.Track) -> SoundtrackCollections.TrackRef, collectionId: Int?, onRemoveMode: () -> Unit, +) { + val ctx = LocalContext.current + val colors = MaterialTheme.colorScheme + val belongs = target.belongs + val playing = belongs && SoundtrackController.playing + val shownArt: Any? = art + var saving by remember { mutableStateOf(false) } + Column(verticalArrangement = Arrangement.spacedBy(14.dp), modifier = Modifier.fillMaxWidth()) { + Row(horizontalArrangement = Arrangement.spacedBy(16.dp), verticalAlignment = Alignment.Top) { + Box(Modifier.size(120.dp).clip(RoundedCornerShape(10.dp)).background(Color.Black.copy(alpha = 0.35f))) { + if (shownArt != null) AsyncImage(shownArt, contentDescription = game.name, contentScale = ContentScale.Fit, modifier = Modifier.matchParentSize().testTag("soundtrack-cover")) + } + Column(verticalArrangement = Arrangement.spacedBy(6.dp), modifier = Modifier.weight(1f)) { + Text( + game.name, fontSize = 22.sp, lineHeight = 26.sp, fontWeight = FontWeight.Black, color = colors.onBackground, + maxLines = 2, overflow = TextOverflow.Ellipsis, + ) + val artist = album?.artist.orEmpty() + if (artist.isNotBlank()) Text(artist, fontSize = 14.sp, color = colors.onBackground.copy(alpha = 0.8f), maxLines = 1, overflow = TextOverflow.Ellipsis) + if (album != null && album.tracks.isNotEmpty()) { + Text( + stringResource(R.string.soundtracks_total_length).uppercase(), fontSize = 11.sp, fontWeight = FontWeight.Bold, letterSpacing = 0.8.sp, + color = colors.onSurfaceVariant, modifier = Modifier.padding(top = 4.dp), + ) + Text( + stringResource(R.string.soundtracks_length_value, album.tracks.size, Soundtrack.formatLength(album.totalMs)), + fontSize = 13.sp, color = colors.onBackground, + ) + } + } + } + Seek(target, album) + val shuffleLabel = stringResource(R.string.soundtracks_shuffle) + val previousLabel = stringResource(R.string.soundtracks_previous) + val playLabel = stringResource(if (playing) R.string.soundtracks_pause else R.string.soundtracks_play) + val nextLabel = stringResource(R.string.soundtracks_next) + val repeatLabel = stringResource( + when (SoundtrackController.repeat) { + Player.REPEAT_MODE_ALL -> R.string.soundtracks_repeat_all + Player.REPEAT_MODE_ONE -> R.string.soundtracks_repeat_one + else -> R.string.soundtracks_repeat_off + }, + ) + val loaded = album?.takeIf { it.tracks.isNotEmpty() } + Row(horizontalArrangement = Arrangement.spacedBy(14.dp, Alignment.CenterHorizontally), verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) { + TransportButton(Icons.Filled.Shuffle, shuffleLabel, "sound:shuffle", on = belongs && SoundtrackController.shuffle, enabled = loaded != null) { + if (loaded == null) return@TransportButton + if (belongs) SoundtrackController.setShuffle(ctx, !SoundtrackController.shuffle) + else SoundtrackController.play(ctx, loaded, game.name, null, shuffled = true, root = target.root, collection = target.collection) + } + TransportButton(Icons.Filled.SkipPrevious, previousLabel, "sound:previous", enabled = loaded != null) { + if (loaded == null) return@TransportButton + if (belongs) SoundtrackController.previous(ctx) else SoundtrackController.play(ctx, loaded, game.name, null, root = target.root, collection = target.collection) + } + TransportButton( + if (playing) Icons.Filled.Pause else Icons.Filled.PlayArrow, playLabel, "sound:play", big = true, enabled = loaded != null, + modifier = Modifier.focusRequester(lead), + ) { + if (loaded != null) SoundtrackController.toggle(ctx, loaded, game.name, target.root, target.collection) + } + TransportButton(Icons.Filled.SkipNext, nextLabel, "sound:next", enabled = loaded != null) { + if (loaded == null) return@TransportButton + if (belongs) SoundtrackController.next(ctx) else SoundtrackController.play(ctx, loaded, game.name, null, root = target.root, collection = target.collection) + } + TransportButton( + if (SoundtrackController.repeat == Player.REPEAT_MODE_ONE) Icons.Filled.RepeatOne else Icons.Filled.Repeat, repeatLabel, "sound:repeat", + on = SoundtrackController.repeat != Player.REPEAT_MODE_OFF, enabled = loaded != null && belongs, + ) { SoundtrackController.cycleRepeat(ctx) } + } + val heartTrack = if (belongs) loaded?.tracks?.firstOrNull { it.id == SoundtrackController.currentId } else null + val liked = heartTrack != null && SoundtrackCollections.snapshot.favorites.any { it.path == heartTrack.id } + Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End, verticalAlignment = Alignment.CenterVertically) { + TransportButton( + if (liked) Icons.Filled.Favorite else Icons.Filled.FavoriteBorder, stringResource(R.string.soundtracks_add_favorites), "sound:favorite", + on = liked, enabled = heartTrack != null, + ) { heartTrack?.let { SoundtrackCollections.toggleFavorite(ctx, refOf(it)) } } + TransportButton(Icons.Filled.BookmarkBorder, stringResource(R.string.soundtracks_saved), "sound:saved", enabled = heartTrack != null) { saving = true } + } + if (saving && heartTrack != null) SavedDialog(listOf(refOf(heartTrack)), null) { saving = false } + Volume() + Column(verticalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth().padding(top = 4.dp)) { + SoundtrackActions(game, s, a, collectionId, onRemoveMode) + } + } +} + +@Composable +private fun Seek(target: PlayTarget, album: Soundtrack.Album?) { + val ctx = LocalContext.current + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + val belongs = target.belongs + var position by remember { mutableFloatStateOf(0f) } + var dragging by remember { mutableStateOf(false) } + val duration = if (belongs) SoundtrackController.durationMs else 0L + LaunchedEffect(belongs, SoundtrackController.currentId) { + if (!belongs) { + if (!dragging) position = 0f + return@LaunchedEffect + } + while (true) { + if (!dragging) position = SoundtrackController.position().toFloat() + delay(400) + } + } + Column(verticalArrangement = Arrangement.spacedBy(0.dp), modifier = Modifier.fillMaxWidth()) { + Slider( + value = if (duration > 0) (position / duration).coerceIn(0f, 1f) else 0f, + onValueChange = { dragging = true; position = it * duration }, + onValueChangeFinished = { dragging = false; SoundtrackController.seekTo(ctx, position.toLong()) }, + enabled = belongs && duration > 0 && album != null, + colors = SliderDefaults.colors(thumbColor = pal.signal, activeTrackColor = pal.signal, inactiveTrackColor = colors.onBackground.copy(alpha = 0.18f)), + modifier = Modifier.fillMaxWidth().testTag("soundtrack-seek"), + ) + Row(Modifier.fillMaxWidth().padding(horizontal = 4.dp)) { + Text(Soundtrack.formatLength(position.toLong()), fontSize = 11.sp, color = colors.onSurfaceVariant) + Spacer(Modifier.weight(1f)) + Text(Soundtrack.formatLength(duration), fontSize = 11.sp, color = colors.onSurfaceVariant) + } + } +} + +@Composable +private fun Volume() { + val ctx = LocalContext.current + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + var level by remember { mutableFloatStateOf(SoundtrackController.volume) } + LaunchedEffect(SoundtrackController.volume) { level = SoundtrackController.volume } + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.fillMaxWidth()) { + Icon(if (level <= 0.001f) Icons.Filled.VolumeOff else Icons.Filled.VolumeUp, contentDescription = stringResource(R.string.soundtracks_volume), tint = colors.onSurfaceVariant, modifier = Modifier.size(20.dp)) + Slider( + value = level, onValueChange = { level = it; SoundtrackController.setVolume(ctx, it) }, + colors = SliderDefaults.colors(thumbColor = pal.signal, activeTrackColor = pal.signal, inactiveTrackColor = colors.onBackground.copy(alpha = 0.18f)), + modifier = Modifier.weight(1f).testTag("soundtrack-volume"), + ) + } +} + +@Composable +private fun TransportButton( + icon: ImageVector, label: String, id: String, big: Boolean = false, on: Boolean = false, enabled: Boolean = true, + modifier: Modifier = Modifier, onClick: () -> Unit, +) { + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + val src = remember { MutableInteractionSource() } + val hot = rememberHot(src) && enabled + val size = if (big) 60.dp else 44.dp + val fill = when { + big -> pal.signal.copy(alpha = if (hot) 1f else 0.9f) + hot -> pal.signal.copy(alpha = 0.16f) + else -> Color.Transparent + } + Box( + contentAlignment = Alignment.Center, + modifier = modifier.paneItem(id).testTag(id).size(size).clip(CircleShape).background(fill) + .glideBorder(hot, CircleShape, pal.signal, if (big) Color.Transparent else Color.Transparent) + .hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Button, enabled = enabled, onClick = onClick) + .controllerConfirm(enabled = enabled, onClick = onClick) + .semantics { contentDescription = label }, + ) { + Icon( + icon, contentDescription = null, + tint = when { + big -> colors.background + !enabled -> colors.onSurfaceVariant.copy(alpha = 0.4f) + on -> pal.signal + else -> colors.onBackground + }, + modifier = Modifier.size(if (big) 34.dp else 26.dp), + ) + } +} + +@Composable +private fun SeeMoreButton(label: String, id: String, danger: Boolean = false, modifier: Modifier = Modifier, onClick: () -> Unit) { + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + val src = remember { MutableInteractionSource() } + val hot = rememberHot(src) + val shape = RoundedCornerShape(10.dp) + val accent = if (danger) colors.error else pal.signal + Box( + contentAlignment = Alignment.Center, + modifier = modifier.fillMaxWidth().paneItem(id).testTag(id).heightIn(min = 44.dp).clip(shape) + .background(if (hot) accent.copy(alpha = 0.16f) else Color.White.copy(alpha = 0.09f)) + .glideBorder(hot, shape, accent, Color.White.copy(alpha = 0.10f)) + .hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Button, onClick = onClick) + .controllerConfirm(onClick = onClick) + .padding(horizontal = 16.dp, vertical = 10.dp), + ) { + Text( + label, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, textAlign = TextAlign.Center, + color = if (danger && hot) colors.error else colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis, + ) + } +} + +@Composable +private fun SoundtrackActions(game: Library.SteamGame, s: FrontEndState, a: FrontEndActions, collectionId: Int?, onRemoveMode: () -> Unit) { + var options by remember { mutableStateOf(false) } + var managing by remember { mutableStateOf(false) } + if (collectionId != null) SeeMoreButton(stringResource(R.string.soundtracks_manage), "sound:manage") { managing = true } + if (managing && collectionId != null) ManageDialog(collectionId, s.soundtracks, onRemoveMode) { managing = false } + SeeMoreButton(stringResource(R.string.soundtracks_options), "sound:options") { options = true } + if (options) SoundtrackOptionsDialog { options = false } + game.gameFiles?.takeIf { it.isDirectory }?.let { dir -> + SeeMoreButton(stringResource(R.string.games_files), "sound:files") { a.onBrowseFiles(dir) } + } + var menu by remember(game.appId) { mutableStateOf(false) } + Box { + SeeMoreButton(stringResource(R.string.game_shortcut), "sound:shortcut") { menu = !menu } + AnchoredMenu(menu, onDismiss = { menu = false }, title = stringResource(R.string.game_shortcut)) { first -> + MenuItem(stringResource(R.string.game_shortcut_add), checked = false, focusRequester = first) { menu = false; a.onGameShortcut(game) } + MenuItem(stringResource(R.string.game_link_copy), checked = false) { menu = false; a.onCopyGameLink(game) } + } + } + var collectionArt by remember(game.appId) { mutableStateOf(false) } + val ownArt = game.library == Library.ADDED + if (ownArt) SeeMoreButton(stringResource(R.string.game_edit_art), "sound:art") { collectionArt = true } + else SeeMoreButton(stringResource(R.string.game_edit_art), "sound:art") { GamesDialogState.steamArt = game } + if (collectionArt && ownArt) CollectionArtEditor( + game.appId, game.name, game.gameFiles, + onClose = { collectionArt = false }, + onChanged = { if (collectionId != null) SoundtrackCollections.refresh() else a.onSoundtracksChanged() }, + ) + if (collectionId != null) return + var asking by remember(game.appId) { mutableStateOf(false) } + val added = game.library == Library.ADDED + val label = stringResource(if (added) R.string.edit_remove else R.string.common_uninstall) + SeeMoreButton(label, "sound:remove", danger = true) { asking = true } + if (asking) ConfirmDialog( + title = if (added) stringResource(R.string.games_remove_title, game.name) else stringResource(R.string.stores_uninstall_title, game.name), + text = if (added) stringResource(R.string.games_remove_body) else stringResource(R.string.games_uninstall_body), + confirm = label, + onConfirm = { a.onSoundtrackRemoved(game) }, + onDismiss = { asking = false }, + ) +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SoundtrackIcon.kt b/app/src/main/java/com/droiddeck/launcher/ui/SoundtrackIcon.kt new file mode 100644 index 0000000000..70c1fd0178 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/SoundtrackIcon.kt @@ -0,0 +1,15 @@ +package com.droiddeck.launcher.ui + +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.SolidColor +import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.graphics.vector.addPathNodes +import androidx.compose.ui.unit.dp + +private const val NOTES = "M8.4,4.5 L20,2 V6 L8.4,8.5 Z M8.4,4.5 H10.6 V17.5 H8.4 Z M17.9,2 H20 V15.5 H17.9 Z M7.2,14.7 A3.4,2.8 0 1,0 7.2,20.3 A3.4,2.8 0 1,0 7.2,14.7 Z M16.6,12.7 A3.4,2.8 0 1,0 16.6,18.3 A3.4,2.8 0 1,0 16.6,12.7 Z" + +internal val SoundtrackIcon: ImageVector by lazy { + ImageVector.Builder("Soundtrack", 24.dp, 24.dp, 24f, 24f) + .addPath(addPathNodes(NOTES), fill = SolidColor(Color.Black)) + .build() +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SoundtrackOptions.kt b/app/src/main/java/com/droiddeck/launcher/ui/SoundtrackOptions.kt new file mode 100644 index 0000000000..dc9fadfa28 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/SoundtrackOptions.kt @@ -0,0 +1,217 @@ +package com.droiddeck.launcher.ui + +import android.media.AudioManager +import android.media.audiofx.BassBoost +import android.media.audiofx.Equalizer +import androidx.compose.foundation.background +import androidx.compose.foundation.horizontalScroll +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.selection.selectable +import androidx.compose.foundation.selection.toggleable +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Slider +import androidx.compose.material3.SliderDefaults +import androidx.compose.material3.Switch +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.mutableLongStateOf +import androidx.compose.runtime.produceState +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.platform.LocalContext +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.droiddeck.launcher.R +import com.droiddeck.launcher.frontend.Soundtrack +import com.droiddeck.launcher.playback.SoundtrackController +import com.droiddeck.launcher.playback.SoundtrackSettings +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.delay +import kotlinx.coroutines.withContext +import kotlin.math.roundToInt + +private class EqInfo( + val bands: Int, val min: Int, val max: Int, val freqs: List, val presets: List>>, val bassSupported: Boolean, +) + +private fun readEqInfo(audio: AudioManager): EqInfo? = runCatching { + val id = audio.generateAudioSessionId() + val eq = Equalizer(0, id) + try { + val count = eq.numberOfBands.toInt() + val presets = (0 until eq.numberOfPresets.toInt()).map { preset -> + eq.usePreset(preset.toShort()) + eq.getPresetName(preset.toShort()) to (0 until count).map { eq.getBandLevel(it.toShort()).toInt() } + } + val bass = runCatching { BassBoost(0, id).let { b -> try { b.strengthSupported } finally { b.release() } } }.getOrDefault(false) + EqInfo( + count, eq.bandLevelRange[0].toInt(), eq.bandLevelRange[1].toInt(), + (0 until count).map { eq.getCenterFreq(it.toShort()) / 1000 }, presets, bass, + ) + } finally { + eq.release() + } +}.getOrNull() + +@Composable +internal fun SoundtrackOptionsDialog(onDismiss: () -> Unit) { + val ctx = LocalContext.current + LaunchedEffect(Unit) { SoundtrackSettings.load(ctx) } + AlertDialog( + onDismissRequest = onDismiss, + title = { Text(stringResource(R.string.soundtracks_options)) }, + text = { + Column(Modifier.verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(16.dp)) { + RateRow(stringResource(R.string.theme_rgb_speed), SoundtrackSettings.speed, "soundtrack-speed") { SoundtrackController.setSpeed(ctx, it) } + RateRow(stringResource(R.string.soundtracks_pitch), SoundtrackSettings.pitch, "soundtrack-pitch") { SoundtrackController.setPitch(ctx, it) } + SwitchRow(stringResource(R.string.soundtracks_skip_silence), SoundtrackSettings.skipSilence, "soundtrack-skip-silence") { + SoundtrackController.setSkipSilence(ctx, it) + } + SleepSection() + EqualizerSection() + } + }, + confirmButton = { TextButton(onClick = onDismiss, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_close)) } }, + ) +} + +@Composable +private fun RateRow(label: String, value: Float, tag: String, onChange: (Float) -> Unit) { + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + Column(verticalArrangement = Arrangement.spacedBy(2.dp)) { + Row(verticalAlignment = Alignment.CenterVertically) { + Text(label, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = colors.onSurface, modifier = Modifier.weight(1f)) + Text("%.2fร—".format(value), fontSize = 14.sp, color = colors.onSurfaceVariant) + TextButton(onClick = { onChange(1f) }, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.soundtracks_reset)) } + } + Slider( + value = value, onValueChange = { v -> (v * 20f).roundToInt().div(20f).let { if (it != value) onChange(it) } }, + valueRange = SoundtrackSettings.MIN_RATE..SoundtrackSettings.MAX_RATE, steps = 29, + colors = SliderDefaults.colors(thumbColor = pal.signal, activeTrackColor = pal.signal, inactiveTrackColor = colors.onSurface.copy(alpha = 0.18f)), + modifier = Modifier.fillMaxWidth().testTag(tag), + ) + } +} + +@Composable +private fun SwitchRow(label: String, checked: Boolean, tag: String, onChange: (Boolean) -> Unit) { + val colors = MaterialTheme.colorScheme + Row( + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier.fillMaxWidth().focusGlide(RoundedCornerShape(12.dp)).toggleable(checked, role = Role.Switch, onValueChange = onChange).padding(vertical = 4.dp).testTag(tag), + ) { + Text(label, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = colors.onSurface, modifier = Modifier.weight(1f)) + Switch(checked = checked, onCheckedChange = null) + } +} + +@Composable +private fun OptionChip(label: String, selected: Boolean, onClick: () -> Unit) { + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + val shape = RoundedCornerShape(99.dp) + Text( + label, fontSize = 13.sp, fontWeight = FontWeight.SemiBold, maxLines = 1, + color = if (selected) pal.signal else colors.onSurface, + modifier = Modifier.focusGlide(shape).clip(shape) + .background(if (selected) pal.signal.copy(alpha = 0.18f) else colors.onSurface.copy(alpha = 0.08f)) + .selectable(selected = selected, role = Role.RadioButton, onClick = onClick) + .padding(horizontal = 14.dp, vertical = 8.dp), + ) +} + +@Composable +private fun SleepSection() { + val ctx = LocalContext.current + val colors = MaterialTheme.colorScheme + var left by remember { mutableLongStateOf(0L) } + LaunchedEffect(Unit) { + while (true) { + left = SoundtrackController.sleepRemainingMs() + delay(1000) + } + } + val trackEnd = SoundtrackController.sleepTrackEnd + val timed = left > 0L + Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { + Row(verticalAlignment = Alignment.CenterVertically) { + Text(stringResource(R.string.soundtracks_sleep), fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = colors.onSurface, modifier = Modifier.weight(1f)) + if (timed) Text(stringResource(R.string.soundtracks_sleep_left, Soundtrack.formatLength(left)), fontSize = 13.sp, color = colors.onSurfaceVariant) + } + Row(Modifier.horizontalScroll(rememberScrollState()), horizontalArrangement = Arrangement.spacedBy(8.dp)) { + OptionChip(stringResource(R.string.perf_cap_off), !timed && !trackEnd) { SoundtrackController.setSleep(ctx, 0) } + for (minutes in listOf(15, 30, 60)) OptionChip(stringResource(R.string.soundtracks_sleep_minutes, minutes), false) { SoundtrackController.setSleep(ctx, minutes) } + OptionChip(stringResource(R.string.soundtracks_sleep_track_end), trackEnd) { SoundtrackController.setSleep(ctx, -1) } + } + } +} + +@Composable +private fun EqualizerSection() { + val ctx = LocalContext.current + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + val info by produceState(null) { + value = withContext(Dispatchers.IO) { readEqInfo(ctx.getSystemService(AudioManager::class.java)) } + } + val ready = info + val on = SoundtrackSettings.eqOn + val levels = ready?.let { i -> SoundtrackSettings.bands.takeIf { it.size == i.bands } ?: List(i.bands) { 0 } }.orEmpty() + val bass = SoundtrackSettings.bass + Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { + SwitchRow(stringResource(R.string.soundtracks_equalizer), on && ready != null, "soundtrack-eq") { + if (ready != null) SoundtrackController.setEqualizer(ctx, it, levels, bass) + } + if (ready == null || ready.bands == 0) { + if (ready != null) Text(stringResource(R.string.soundtracks_eq_unavailable), fontSize = 13.sp, color = colors.onSurfaceVariant) + return@Column + } + if (ready.presets.isNotEmpty()) Row(Modifier.horizontalScroll(rememberScrollState()), horizontalArrangement = Arrangement.spacedBy(8.dp)) { + for ((name, preset) in ready.presets) OptionChip(name, on && preset == levels) { SoundtrackController.setEqualizer(ctx, true, preset, bass) } + } + for (band in 0 until ready.bands) { + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) { + val hz = ready.freqs[band] + Text(if (hz >= 1000) "%.1f kHz".format(hz / 1000f) else "$hz Hz", fontSize = 12.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(end = 2.dp)) + Slider( + value = levels[band].toFloat(), valueRange = ready.min.toFloat()..ready.max.toFloat(), + onValueChange = { v -> SoundtrackController.setEqualizer(ctx, true, levels.toMutableList().also { it[band] = v.roundToInt() }, bass) }, + colors = SliderDefaults.colors(thumbColor = pal.signal, activeTrackColor = pal.signal, inactiveTrackColor = colors.onSurface.copy(alpha = 0.18f)), + modifier = Modifier.weight(1f).testTag("soundtrack-eq-$band"), + ) + } + } + if (ready.bassSupported) Column { + Text(stringResource(R.string.soundtracks_bass), fontSize = 13.sp, color = colors.onSurfaceVariant) + Slider( + value = bass.toFloat(), valueRange = 0f..1000f, + onValueChange = { v -> SoundtrackController.setEqualizer(ctx, true, levels, v.roundToInt()) }, + colors = SliderDefaults.colors(thumbColor = pal.signal, activeTrackColor = pal.signal, inactiveTrackColor = colors.onSurface.copy(alpha = 0.18f)), + modifier = Modifier.fillMaxWidth().testTag("soundtrack-bass"), + ) + } + TextButton(onClick = { SoundtrackController.setEqualizer(ctx, on, List(ready.bands) { 0 }, 0) }, modifier = Modifier.focusGlide(CircleShape)) { + Text(stringResource(R.string.soundtracks_reset)) + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SoundtrackTrackPanel.kt b/app/src/main/java/com/droiddeck/launcher/ui/SoundtrackTrackPanel.kt new file mode 100644 index 0000000000..c0769536c7 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/SoundtrackTrackPanel.kt @@ -0,0 +1,391 @@ +package com.droiddeck.launcher.ui + +import androidx.activity.compose.BackHandler +import androidx.compose.foundation.ExperimentalFoundationApi +import androidx.compose.foundation.LocalIndication +import androidx.compose.foundation.background +import androidx.compose.foundation.combinedClickable +import androidx.compose.foundation.gestures.detectDragGesturesAfterLongPress +import androidx.compose.foundation.horizontalScroll +import androidx.compose.foundation.hoverable +import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +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.rememberLazyListState +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.CheckBox +import androidx.compose.material.icons.filled.CheckBoxOutlineBlank +import androidx.compose.material.icons.filled.PlayArrow +import androidx.compose.material.icons.filled.Sort +import androidx.compose.material3.Icon +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.mutableFloatStateOf +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.rememberCoroutineScope +import kotlinx.coroutines.launch +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.rememberUpdatedState +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.graphicsLayer +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.zIndex +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.input.ImeAction +import androidx.compose.ui.text.input.KeyboardType +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.frontend.Soundtrack +import com.droiddeck.launcher.frontend.SoundtrackCollections +import com.droiddeck.launcher.frontend.SoundtrackTracks +import com.droiddeck.launcher.playback.SoundtrackController + +internal class PlayTarget(val root: java.io.File?, val collection: Int?) { + val belongs: Boolean get() = if (collection != null) SoundtrackController.belongsCollection(collection) else SoundtrackController.belongs(root) +} + +private sealed interface SoundRow { + class Disc(val number: Int, val label: String) : SoundRow + class Item(val track: Soundtrack.Track) : SoundRow +} + +private fun rowsOf(album: Soundtrack.Album): List = buildList { + for ((disc, tracks) in album.disc) { + if (album.multiDisc) add(SoundRow.Disc(disc, tracks.firstOrNull()?.discLabel ?: disc.toString())) + tracks.forEach { add(SoundRow.Item(it)) } + } +} + +@Composable +private fun sortLabel(sort: SoundtrackTracks.Sort): String = stringResource( + when (sort) { + SoundtrackTracks.Sort.DEFAULT -> R.string.soundtracks_sort_default + SoundtrackTracks.Sort.TITLE_ASC -> R.string.stores_sort_title_asc + SoundtrackTracks.Sort.TITLE_DESC -> R.string.stores_sort_title_desc + SoundtrackTracks.Sort.LONGEST -> R.string.soundtracks_sort_longest + SoundtrackTracks.Sort.SHORTEST -> R.string.soundtracks_sort_shortest + }, +) + +@Composable +internal fun TrackPanel( + album: Soundtrack.Album, title: String, target: PlayTarget, refOf: (Soundtrack.Track) -> SoundtrackCollections.TrackRef, + collectionId: Int?, selectRequest: Int, onReorder: ((List) -> Unit)?, modifier: Modifier, +) { + val ctx = LocalContext.current + val colors = MaterialTheme.colorScheme + var query by remember { mutableStateOf("") } + var sort by remember { mutableStateOf(SoundtrackTracks.Sort.DEFAULT) } + var sortMenu by remember { mutableStateOf(false) } + var selecting by remember { mutableStateOf(false) } + var picked by remember { mutableStateOf(setOf()) } + var saving by remember { mutableStateOf(false) } + val leave: () -> Unit = { + selecting = false + picked = emptySet() + } + LaunchedEffect(selectRequest) { if (selectRequest > 0) selecting = true } + BackHandler(enabled = selecting) { leave() } + val rows: List = remember(album, query, sort) { + if (sort == SoundtrackTracks.Sort.DEFAULT && query.isBlank()) rowsOf(album) + else SoundtrackTracks.sort( + album.tracks.filter { SoundtrackTracks.matches(query, it.title, it.artist) }, sort, { it.title }, { it.durationMs }, + ).map { SoundRow.Item(it) } + } + val rowIds = rows.filterIsInstance().map { it.track.id } + var working by remember(rowIds) { mutableStateOf?>(null) } + val display = working ?: rows + val canReorder = onReorder != null && sort == SoundtrackTracks.Sort.DEFAULT && query.isBlank() && selecting + var dragId by remember { mutableStateOf(null) } + var dragTotal by remember { mutableFloatStateOf(0f) } + var dragTo by remember { mutableIntStateOf(0) } + val numbers = remember(display) { + val out = HashMap() + var n = 0 + for (row in display) { + if (row is SoundRow.Disc) n = 0 + else if (row is SoundRow.Item) out[row.track.id] = ++n + } + out + } + val state = rememberLazyListState() + val scope = rememberCoroutineScope() + val drag = remember { DragState() } + fun applyDrag() { + drag.total = drag.total.coerceIn((drag.lo - drag.from) * drag.size, (drag.hi - drag.from) * drag.size) + dragTotal = drag.total + dragTo = dragTarget(drag.total, drag.size, drag.from, drag.lo, drag.hi) + } + val finishDrag: () -> Unit = { + if (dragId != null) { + val from = drag.from + val to = dragTo + if (to != from && from in drag.base.indices) { + val moved = drag.base.toMutableList().apply { add(to, removeAt(from)) } + val index = state.firstVisibleItemIndex + val offset = state.firstVisibleItemScrollOffset + working = moved + scope.launch { state.scrollToItem(index, offset) } + onReorder?.invoke(moved.filterIsInstance().map { it.track.id }) + } + dragId = null + dragTotal = 0f + dragTo = from + } + } + val rowsNow by rememberUpdatedState(rows) + val finishNow by rememberUpdatedState(finishDrag) + val current = if (target.belongs) SoundtrackController.currentId else null + var scrolledTo by remember { mutableStateOf(null) } + LaunchedEffect(album, current) { + if (current == null) { + scrolledTo = null + return@LaunchedEffect + } + if (dragId != null || current == scrolledTo) return@LaunchedEffect + val at = rows.indexOfFirst { it is SoundRow.Item && it.track.id == current } + if (at >= 0) { + scrolledTo = current + state.animateScrollToItem(at) + } + } + val chosen = album.tracks.filter { it.id in picked }.map(refOf) + Column(modifier) { + Row(Modifier.fillMaxWidth().padding(bottom = 8.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) { + Box(Modifier.weight(1f)) { + AdbTextField( + value = query, onValueChange = { query = it }, label = "", keyboardType = KeyboardType.Text, imeAction = ImeAction.Search, + placeholder = stringResource(R.string.soundtracks_search_tracks), compact = true, + ) + } + Box { + HeaderIconButton(stringResource(R.string.stores_sort), Icons.Filled.Sort, "tracks-sort") { sortMenu = !sortMenu } + AnchoredMenu(sortMenu, onDismiss = { sortMenu = false }, title = stringResource(R.string.stores_sort)) { first -> + SoundtrackTracks.Sort.values().forEachIndexed { i, option -> + MenuItem(sortLabel(option), checked = option == sort, focusRequester = if (i == 0) first else null) { + sort = option + sortMenu = false + } + } + } + } + HeaderIconButton(stringResource(R.string.soundtracks_select), Icons.Filled.CheckBox, "tracks-select") { + if (selecting) leave() else selecting = true + } + } + if (selecting) Row( + Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()).padding(bottom = 6.dp), + horizontalArrangement = Arrangement.spacedBy(2.dp), verticalAlignment = Alignment.CenterVertically, + ) { + Text(stringResource(R.string.soundtracks_selected, picked.size), fontSize = 13.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(horizontal = 6.dp)) + TextButton(onClick = { picked = rowIds.toSet() }, modifier = Modifier.focusGlide(CircleShape).testTag("tracks-select-all")) { + Text(stringResource(R.string.soundtracks_select_all)) + } + TextButton(onClick = { picked = emptySet() }, modifier = Modifier.focusGlide(CircleShape).testTag("tracks-deselect-all")) { + Text(stringResource(R.string.soundtracks_deselect_all)) + } + TextButton(enabled = picked.isNotEmpty(), onClick = { saving = true }, modifier = Modifier.focusGlide(CircleShape).testTag("tracks-add-collection")) { + Text(stringResource(R.string.soundtracks_add_to_collection)) + } + TextButton( + enabled = picked.isNotEmpty(), + onClick = { + SoundtrackCollections.add(ctx, SoundtrackCollections.FAVORITES_ID, chosen) + leave() + }, + modifier = Modifier.focusGlide(CircleShape).testTag("tracks-add-favorites"), + ) { Text(stringResource(R.string.soundtracks_add_favorites)) } + if (collectionId != null) TextButton( + enabled = picked.isNotEmpty(), + onClick = { + SoundtrackCollections.remove(ctx, collectionId, picked) + leave() + }, + modifier = Modifier.focusGlide(CircleShape).testTag("tracks-remove"), + ) { Text(stringResource(R.string.soundtracks_remove_from_collection)) } + TextButton(onClick = leave, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) } + } + if (display.isEmpty()) Text( + stringResource(if (album.tracks.isEmpty()) R.string.soundtracks_no_tracks else R.string.stores_nothing_matches), + fontSize = 13.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(top = 12.dp), + ) + else LazyColumn( + state = state, + modifier = Modifier.weight(1f).fillMaxWidth().clip(RoundedCornerShape(10.dp)).background(Color.Black.copy(alpha = 0.28f)).testTag("soundtrack-tracks"), + ) { + items(display, key = { if (it is SoundRow.Item) it.track.id else "disc-${(it as SoundRow.Disc).number}" }) { row -> + when (row) { + is SoundRow.Disc -> Text( + stringResource(R.string.soundtracks_disc, row.label), fontSize = 13.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, + modifier = Modifier.fillMaxWidth().background(Color.White.copy(alpha = 0.12f)).padding(horizontal = 12.dp, vertical = 8.dp), + ) + is SoundRow.Item -> { + val id = row.track.id + val flip = { picked = if (id in picked) picked - id else picked + id } + val dragging = dragId == id + val draggable = canReorder && id in picked + val shift = if (!canReorder) Modifier else Modifier + .zIndex(if (dragging) 1f else 0f) + .graphicsLayer { + translationY = when { + dragId == null -> 0f + dragId == id -> dragTotal + else -> { + val at = drag.index[id] ?: -1 + val f = drag.from + val t = dragTo + if (at < 0) 0f + else if (f < t && at in (f + 1)..t) -drag.size + else if (t < f && at in t until f) drag.size + else 0f + } + } + } + val dragModifier = if (!draggable) shift else shift + .pointerInput(id) { + detectDragGesturesAfterLongPress( + onDragStart = { + val base = working ?: rowsNow + val from = base.indexOfFirst { it is SoundRow.Item && it.track.id == id } + if (from >= 0) { + val disc = (base[from] as SoundRow.Item).track.disc + var lo = from + while (lo > 0 && (base[lo - 1] as? SoundRow.Item)?.track?.disc == disc) lo-- + var hi = from + while (hi < base.lastIndex && (base[hi + 1] as? SoundRow.Item)?.track?.disc == disc) hi++ + val visible = state.layoutInfo.visibleItemsInfo + val me = visible.firstOrNull { it.key == id } + val next = visible.firstOrNull { it.index == (me?.index ?: -2) + 1 && it.key != "disc-0" && base.getOrNull(from + 1) is SoundRow.Item } + val prev = visible.firstOrNull { it.index == (me?.index ?: -2) - 1 && base.getOrNull(from - 1) is SoundRow.Item } + val pitch = when { + me != null && next != null -> (next.offset - me.offset).toFloat() + me != null && prev != null -> (me.offset - prev.offset).toFloat() + else -> me?.size?.toFloat() ?: 0f + } + drag.base = base + drag.index = HashMap().also { m -> base.forEachIndexed { i, r -> if (r is SoundRow.Item) m[r.track.id] = i } } + drag.from = from + drag.lo = lo + drag.hi = hi + drag.size = if (pitch > 0f) pitch else 1f + drag.total = 0f + dragTotal = 0f + dragTo = from + dragId = id + } + }, + onDrag = { change, amount -> + change.consume() + if (dragId == id) { + drag.total += amount.y + applyDrag() + } + }, + onDragEnd = { finishNow() }, + onDragCancel = { finishNow() }, + ) + } + TrackRow( + row.track, numbers[id] ?: row.track.number, dragging, dragModifier, id == current, selecting, id in picked, + onClick = { + if (selecting) flip() + else if (id == current) SoundtrackController.toggle(ctx, album, title, target.root, target.collection) + else SoundtrackController.play(ctx, album, title, id, root = target.root, collection = target.collection) + }, + onLongClick = if (draggable) null else ({ + if (selecting) flip() + else { + selecting = true + picked = setOf(id) + } + }), + ) + } + } + } + } + } + if (saving) SavedDialog(chosen, null) { + saving = false + leave() + } +} + +@OptIn(ExperimentalFoundationApi::class) +@Composable +private fun TrackRow( + track: Soundtrack.Track, number: Int, dragging: Boolean, extra: Modifier, current: Boolean, selecting: Boolean, selected: Boolean, + onClick: () -> Unit, onLongClick: (() -> Unit)?, +) { + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + val src = remember { MutableInteractionSource() } + val hot = rememberHot(src) + val shape = RoundedCornerShape(8.dp) + val tint = if (current) pal.signal else colors.onBackground + Row( + verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp), + modifier = extra.fillMaxWidth().padding(horizontal = 4.dp, vertical = 1.dp).clip(shape) + .background(if (dragging) pal.signal.copy(alpha = 0.32f) else if (selected) pal.signal.copy(alpha = 0.24f) else if (current) pal.signal.copy(alpha = 0.14f) else if (hot) Color.White.copy(alpha = 0.08f) else Color.Transparent) + .glideBorder(hot, shape, pal.signal, Color.Transparent) + .hoverable(src) + .combinedClickable(interactionSource = src, indication = LocalIndication.current, role = Role.Button, onLongClick = onLongClick, onClick = onClick) + .controllerConfirm(onClick = onClick) + .padding(horizontal = 10.dp, vertical = 9.dp), + ) { + Box(Modifier.width(28.dp), contentAlignment = Alignment.CenterEnd) { + when { + selecting -> Icon( + if (selected) Icons.Filled.CheckBox else Icons.Filled.CheckBoxOutlineBlank, contentDescription = null, + tint = if (selected) pal.signal else colors.onSurfaceVariant, modifier = Modifier.size(20.dp), + ) + current && SoundtrackController.playing -> Icon(Icons.Filled.PlayArrow, contentDescription = null, tint = tint, modifier = Modifier.size(16.dp)) + else -> Text("$number.", fontSize = 13.sp, color = if (current) pal.signal else colors.onSurfaceVariant, maxLines = 1) + } + } + Text( + track.title, fontSize = 14.sp, color = tint, fontWeight = if (current) FontWeight.SemiBold else FontWeight.Normal, + maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f), + ) + if (track.durationMs > 0) Text(Soundtrack.formatLength(track.durationMs), fontSize = 13.sp, color = colors.onSurfaceVariant, maxLines = 1) + } +} + +private class DragState { + var base: List = emptyList() + var index: Map = emptyMap() + var from = 0 + var lo = 0 + var hi = 0 + var size = 1f + var total = 0f +} + +internal fun dragTarget(total: Float, size: Float, from: Int, lo: Int, hi: Int): Int = + (from + Math.round(total / size)).coerceIn(lo, hi) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/StoragePage.kt b/app/src/main/java/com/droiddeck/launcher/ui/StoragePage.kt index 04ff93efc9..68bcb8d27d 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/StoragePage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/StoragePage.kt @@ -714,6 +714,7 @@ private fun toolDetail(t: ToolUsage): String = when (t.reason) { ToolReason.ARM_RUNTIME -> stringResource(R.string.storage_tool_arm_runtime) ToolReason.REDISTRIBUTABLES -> stringResource(R.string.storage_tool_redist) ToolReason.FEX -> stringResource(R.string.storage_tool_fex) + ToolReason.ANTICHEAT_RUNTIME -> stringResource(R.string.storage_tool_anticheat) ToolReason.STEAM_TOOL -> stringResource(R.string.storage_tool_steam) ToolReason.OLD_RUNTIME -> stringResource(R.string.storage_tool_old_runtime) ToolReason.X86_PROTON -> stringResource(R.string.storage_tool_x86_proton) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/StoreChips.kt b/app/src/main/java/com/droiddeck/launcher/ui/StoreChips.kt index 2fea8fc891..3921df7f32 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/StoreChips.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/StoreChips.kt @@ -25,6 +25,8 @@ internal const val FLATHUB = "flathub" internal class SourceColours(val fill: Color, val ink: Color, val dot: Color) +internal val FavoritesColours = SourceColours(Color(0xFF3D1A26), Color(0xFFFFB3C8), Color(0xFFFF5C8A)) + internal fun sourceColours(source: String): SourceColours = when (source) { Store.GOG.id -> SourceColours(Color(0xFF3A1A3C), Color(0xFFE6A3EA), Color(0xFFC25BC8)) Store.EPIC.id -> SourceColours(Color(0xFF2A2A2A), Color(0xFFDDDDDD), Color(0xFFBDBDBD)) @@ -35,7 +37,9 @@ internal fun sourceColours(source: String): SourceColours = when (source) { Store.BATTLENET.id -> SourceColours(Color(0xFF0A2440), Color(0xFF9DD1FF), Color(0xFF148EFF)) Store.UBISOFT.id -> SourceColours(Color(0xFF0B1E44), Color(0xFFA8C6FF), Color(0xFF2E7DFF)) Store.EA.id -> SourceColours(Color(0xFF3A0E12), Color(0xFFFF9A9A), Color(0xFFFF4747)) + Store.ROCKSTAR.id -> SourceColours(Color(0xFF3A2A06), Color(0xFFFFD780), Color(0xFFFCAF17)) Library.SOURCE_STEAM -> SourceColours(Color(0xFF16293D), Color(0xFF7CC4FF), Color(0xFF1A9FFF)) + Library.SOURCE_COLLECTION -> SourceColours(Color(0xFF2B1A3D), Color(0xFFD2A8FF), Color(0xFFA25BFF)) FLATHUB -> SourceColours(Color(0xFF0B2E2B), Color(0xFF9FE3DD), FlathubTeal) else -> SourceColours(Color(0xFF1A1D22), Color(0xFF9AA3AF), Color(0xFF9AA3AF)) } @@ -43,6 +47,7 @@ internal fun sourceColours(source: String): SourceColours = when (source) { @Composable internal fun sourceLabel(source: String): String = when (source) { Library.SOURCE_STEAM -> stringResource(R.string.source_steam) + Library.SOURCE_COLLECTION -> stringResource(R.string.soundtracks_collections) Store.GOG.id -> Store.GOG.label Store.EPIC.id -> Store.EPIC.label Store.AMAZON.id -> Store.AMAZON.label @@ -52,14 +57,15 @@ internal fun sourceLabel(source: String): String = when (source) { Store.BATTLENET.id -> Store.BATTLENET.label Store.UBISOFT.id -> Store.UBISOFT.shortLabel Store.EA.id -> Store.EA.label + Store.ROCKSTAR.id -> Store.ROCKSTAR.shortLabel else -> stringResource(R.string.source_added) } @Composable -internal fun SourceChip(source: String, small: Boolean = false, modifier: Modifier = Modifier) { - val c = sourceColours(source) +internal fun SourceChip(source: String, small: Boolean = false, modifier: Modifier = Modifier, label: String? = null, colours: SourceColours? = null) { + val c = colours ?: sourceColours(source) Text( - sourceLabel(source), fontSize = if (small) 10.sp else 11.sp, fontWeight = FontWeight.Bold, letterSpacing = 0.4.sp, + label ?: sourceLabel(source), fontSize = if (small) 10.sp else 11.sp, fontWeight = FontWeight.Bold, letterSpacing = 0.4.sp, color = c.ink, maxLines = 1, modifier = modifier.clip(RoundedCornerShape(6.dp)).background(c.fill) .padding(horizontal = if (small) 6.dp else 8.dp, vertical = if (small) 1.dp else 2.dp), diff --git a/app/src/main/java/com/droiddeck/launcher/ui/StoresDownloads.kt b/app/src/main/java/com/droiddeck/launcher/ui/StoresDownloads.kt index 8988e16a17..0b1000e6e3 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/StoresDownloads.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/StoresDownloads.kt @@ -85,6 +85,7 @@ import com.droiddeck.launcher.R import com.droiddeck.launcher.session.SessionPrefs import com.droiddeck.launcher.stores.CatalogItem import com.droiddeck.launcher.stores.StoreLanguage +import com.droiddeck.launcher.stores.Store import com.droiddeck.launcher.stores.StoresState import com.droiddeck.launcher.stores.download.DownloadEntry import com.droiddeck.launcher.stores.download.DownloadQueue diff --git a/app/src/main/java/com/droiddeck/launcher/ui/StoresPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/StoresPage.kt index 7bc7c186d0..e5005a018e 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/StoresPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/StoresPage.kt @@ -13,6 +13,7 @@ import androidx.compose.material.icons.outlined.Folder import androidx.compose.material.icons.outlined.SdCard import androidx.compose.material.icons.outlined.Smartphone import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.ui.focus.FocusRequester import androidx.compose.ui.focus.focusProperties import androidx.compose.ui.focus.focusRequester import androidx.compose.ui.focus.onFocusChanged @@ -1072,12 +1073,20 @@ internal fun ModeHeader( var searching by remember { mutableStateOf(query.isNotEmpty()) } var focusOnOpen by remember { mutableStateOf(false) } val open by animateFloatAsState(if (searching) 1f else 0f, Motion.sp(0.75f, 420f), label = "searchOpen") + // Closing takes the field away with focus still in it; the search button gets it once it is back on screen. + val searchIcon = remember { FocusRequester() } + var toIcon by remember { mutableStateOf(false) } val close = { searching = false focusOnOpen = false + toIcon = true if (query.isNotEmpty()) onQuery("") } BackHandler(enabled = searching && !clearSearchFocus) { close() } + LaunchedEffect(toIcon, searching, open <= 0.01f) { + if (searching) toIcon = false + else if (toIcon && open <= 0.01f) { focusSoon { searchIcon }; toIcon = false } + } val heading: @Composable () -> Unit = { if (lead != null) lead() else Text( @@ -1093,7 +1102,7 @@ internal fun ModeHeader( Box(Modifier.width(w).graphicsLayer { alpha = (open * 1.6f).coerceAtMost(1f) }) { AdbTextField( value = query, onValueChange = onQuery, label = "", keyboardType = KeyboardType.Text, imeAction = ImeAction.Search, - placeholder = placeholder, compact = true, focusOnShow = focusOnOpen, + placeholder = placeholder, compact = true, showLabel = false, focusOnShow = focusOnOpen, clearFocus = clearSearchFocus || !searching, onFocusChange = { focused -> if (!focused && query.isEmpty()) { searching = false; focusOnOpen = false } }, ) @@ -1103,7 +1112,7 @@ internal fun ModeHeader( } } val searchButton: @Composable () -> Unit = { - SearchIcon(stringResource(R.string.stores_search_open)) { searching = true; focusOnOpen = true } + Box(Modifier.focusRequester(searchIcon)) { SearchIcon(stringResource(R.string.stores_search_open)) { searching = true; focusOnOpen = true } } } BoxWithConstraints(Modifier.fillMaxWidth()) { val stacked = maxWidth < NarrowPaneWidth @@ -1159,6 +1168,7 @@ internal fun storePalette(base: Palette, store: Store?): Palette { Store.BATTLENET -> Color(0xFF148EFF) to Color(0xFF0B6BD3) Store.UBISOFT -> Color(0xFF2E7DFF) to Color(0xFF1A5BD6) Store.EA -> Color(0xFFFF4747) to Color(0xFFE03030) + Store.ROCKSTAR -> Color(0xFFFCAF17) to Color(0xFFD98E00) null -> return base } val on = if (accent.luminance() > 0.18f) Color(0xFF0B0B0D) else Color.White diff --git a/app/src/main/java/com/droiddeck/launcher/ui/TabsSettings.kt b/app/src/main/java/com/droiddeck/launcher/ui/TabsSettings.kt new file mode 100644 index 0000000000..3b964d8983 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/TabsSettings.kt @@ -0,0 +1,142 @@ +package com.droiddeck.launcher.ui + +import androidx.compose.foundation.LocalIndication +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.hoverable +import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.relocation.BringIntoViewRequester +import androidx.compose.foundation.relocation.bringIntoViewRequester +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.outlined.KeyboardArrowDown +import androidx.compose.material.icons.outlined.KeyboardArrowUp +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.key +import androidx.compose.runtime.remember +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.vector.ImageVector +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.stringResource +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.agent.AgentTab + +@OptIn(androidx.compose.foundation.ExperimentalFoundationApi::class) +@Composable +internal fun TabsSettingsGroup(host: MenuHost, s: FrontEndState, a: FrontEndActions) { + val ctx = LocalContext.current + val reveal = remember { BringIntoViewRequester() } + LaunchedEffect(Unit) { + if (!SetupTabs.focusTabs) return@LaunchedEffect + SetupTabs.focusTabs = false + androidx.compose.runtime.withFrameNanos { } + reveal.bringIntoView() + } + val shown = stringResource(R.string.tabs_place_bar) + val more = stringResource(R.string.tabs_place_more) + val hidden = stringResource(R.string.tabs_place_hidden) + val keys = NavTabs.listed(s) + fun pick(key: String, place: TabPlace) { + when (key) { + "stores" -> if ((place != TabPlace.HIDDEN) != s.gameStoresEnabled) a.onGameStoresEnabled(place != TabPlace.HIDDEN) + "soundtracks" -> if ((place != TabPlace.HIDDEN) != s.soundtracksEnabled) a.onSoundtracksEnabled(place != TabPlace.HIDDEN) + "agent" -> if ((place != TabPlace.HIDDEN) != AgentTab.shown) AgentTab.set(ctx, place != TabPlace.HIDDEN) + } + NavTabs.setPlace(ctx, key, place) + } + Box(Modifier.bringIntoViewRequester(reveal)) { + SettingsGroup(stringResource(R.string.setup_group_tabs)) { + keys.forEachIndexed { index, tab -> + key(tab) { + val options = buildList { + add(TabPlace.BAR to shown) + add(TabPlace.MORE to more) + if (NavTabs.hideable(tab)) add(TabPlace.HIDDEN to hidden) + } + TabRow( + host, tab, NavTabs.place(s, tab), options, + canUp = index > 0, canDown = index < keys.lastIndex, + onMove = { step -> NavTabs.move(ctx, s, tab, step) }, + onPick = { pick(tab, it) }, + ) + } + } + } + } +} + +@Composable +private fun TabRow( + host: MenuHost, tab: String, place: TabPlace, options: List>, + canUp: Boolean, canDown: Boolean, onMove: (Int) -> Unit, onPick: (TabPlace) -> Unit, +) { + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + val (labelRes, icon) = railLabelIcon(tab) + val label = stringResource(labelRes) + val open = host.open == "tab-$tab" + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(6.dp), + modifier = Modifier.fillMaxWidth() + .background(if (open) pal.signal.copy(alpha = 0.10f) else androidx.compose.ui.graphics.Color.Transparent) + .padding(start = 14.dp, end = 10.dp, top = 6.dp, bottom = 6.dp), + ) { + Row( + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier.weight(1f).alpha(if (place == TabPlace.HIDDEN) 0.5f else 1f), + ) { + Icon(icon, contentDescription = null, tint = colors.onSurfaceVariant, modifier = Modifier.size(20.dp)) + Spacer(Modifier.width(12.dp)) + Text(label, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis) + } + MoveButton(Icons.Outlined.KeyboardArrowUp, stringResource(R.string.tabs_move_up, label), canUp, "tab-up-$tab") { onMove(-1) } + MoveButton(Icons.Outlined.KeyboardArrowDown, stringResource(R.string.tabs_move_down, label), canDown, "tab-down-$tab") { onMove(1) } + ChoiceChip(host, "tab-$tab", label, options, place, onPick = onPick) + } + Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line)) +} + +@Composable +private fun MoveButton(icon: ImageVector, description: String, enabled: Boolean, tag: String, onClick: () -> Unit) { + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + val src = remember { MutableInteractionSource() } + val hot = rememberHot(src) + Box( + contentAlignment = Alignment.Center, + modifier = Modifier.testTag(tag).size(40.dp).clip(CircleShape) + .background(colors.surfaceVariant) + .glideBorder(hot, CircleShape, pal.signal, pal.line2) + .alpha(if (enabled) 1f else 0.35f) + .hoverable(src) + .clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Button) { if (enabled) onClick() } + .controllerConfirm { if (enabled) onClick() } + .semantics { contentDescription = description }, + ) { Icon(icon, contentDescription = null, tint = if (hot) pal.signal else colors.onBackground, modifier = Modifier.size(20.dp)) } +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/UpdatesPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/UpdatesPage.kt index 990d085f15..e0622acf5e 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/UpdatesPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/UpdatesPage.kt @@ -92,6 +92,7 @@ class UpdatesActions( @OptIn(androidx.compose.foundation.ExperimentalFoundationApi::class) @Composable internal fun UpdatesPage(s: FrontEndState, a: FrontEndActions, modifier: Modifier) { + val host = rememberMenuHost() val u = s.updates val ua = a.updates val me = remember { AppUpdates.installed() } @@ -128,6 +129,12 @@ internal fun UpdatesPage(s: FrontEndState, a: FrontEndActions, modifier: Modifie Box(Modifier.weight(1.15f)) { StatusPanel(s, u, ua, me) } } } + Box(Modifier.padding(top = 18.dp)) { + ToggleRow( + host, "build-watermark", stringResource(R.string.setup_build_watermark), + stringResource(R.string.setup_build_watermark_hint), s.buildWatermark, + ) { a.onBuildWatermark() } + } } } } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/WirelessAdbFixPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/WirelessAdbFixPage.kt index 8ebfb5ad69..a685e414f3 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/WirelessAdbFixPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/WirelessAdbFixPage.kt @@ -454,6 +454,18 @@ internal fun AdbTextField( } } showSoftInputOnFocus = !bottomTyping + // B on a controller puts the keyboard away first; with no keyboard up it goes back as usual. + var hidingKeyboard = false + setOnKeyListener { view, keyCode, event -> + if (keyCode != android.view.KeyEvent.KEYCODE_BUTTON_B) return@setOnKeyListener false + if (event.action == android.view.KeyEvent.ACTION_DOWN && event.repeatCount == 0) { + hidingKeyboard = androidx.core.view.ViewCompat.getRootWindowInsets(view) + ?.isVisible(androidx.core.view.WindowInsetsCompat.Type.ime()) == true + if (hidingKeyboard) (view.context.getSystemService(android.content.Context.INPUT_METHOD_SERVICE) as? android.view.inputmethod.InputMethodManager) + ?.hideSoftInputFromWindow(view.windowToken, 0) + } + hidingKeyboard + } setOnClickListener { if (hasFocus() && !typeOnBottom(this) && bottomTypingLatest.value) showKeyboardHere(this) } setOnFocusChangeListener { _, hasFocus -> focused = hasFocus diff --git a/app/src/main/java/com/droiddeck/launcher/wayland/CompositorHost.kt b/app/src/main/java/com/droiddeck/launcher/wayland/CompositorHost.kt index 7166440029..7fcdc09620 100644 --- a/app/src/main/java/com/droiddeck/launcher/wayland/CompositorHost.kt +++ b/app/src/main/java/com/droiddeck/launcher/wayland/CompositorHost.kt @@ -50,6 +50,7 @@ object CompositorHost { refreshHz: Float, fpsLimit: Int, ): Boolean { + WaylandCompositor.nativeSetClockControl(java.io.File(context.filesDir, "${com.droiddeck.launcher.runtime.LinuxRuntime.DIR}/tmp/.bl-clock").path) ownVsyncThread = SessionPrefs.vsyncThread(context) WaylandCompositor.nativeSetRenderOnCommit(SessionPrefs.renderOnCommit(context)) pace(refreshHz, fpsLimit) @@ -135,7 +136,9 @@ object CompositorHost { vsyncRunning = false } + @Synchronized fun newSession() { + WaylandCompositor.nativeSetClockControl(null) if (started) WaylandCompositor.nativeResetFirstFrame() } diff --git a/app/src/main/java/com/droiddeck/launcher/wayland/WaylandCompositor.java b/app/src/main/java/com/droiddeck/launcher/wayland/WaylandCompositor.java index a2ac2171df..10735a1710 100644 --- a/app/src/main/java/com/droiddeck/launcher/wayland/WaylandCompositor.java +++ b/app/src/main/java/com/droiddeck/launcher/wayland/WaylandCompositor.java @@ -178,6 +178,8 @@ public final class WaylandCompositor { public static native void nativeVsync(long frameTimeNanos); + public static native void nativeSetClockControl(String path); + public static native int nativeCompositorTid(); private static native String nativeCompositorFault(); @@ -338,6 +340,7 @@ public final class WaylandCompositor { public static native int nativeFrameGenProblem(); public static native String nativeFrameGenCapsReason(); + public static native boolean nativeFrameGenActive(); public static native float[] nativeFrameGenStats(); public static native long nativeHudFrameTimes(float[] out); diff --git a/app/src/main/res/drawable/ic_repeat_all.xml b/app/src/main/res/drawable/ic_repeat_all.xml new file mode 100644 index 0000000000..c696a476a6 --- /dev/null +++ b/app/src/main/res/drawable/ic_repeat_all.xml @@ -0,0 +1,10 @@ + + + + diff --git a/app/src/main/res/drawable/ic_repeat_off.xml b/app/src/main/res/drawable/ic_repeat_off.xml new file mode 100644 index 0000000000..e989d57d7b --- /dev/null +++ b/app/src/main/res/drawable/ic_repeat_off.xml @@ -0,0 +1,11 @@ + + + + diff --git a/app/src/main/res/drawable/ic_repeat_one.xml b/app/src/main/res/drawable/ic_repeat_one.xml new file mode 100644 index 0000000000..fda860fcc2 --- /dev/null +++ b/app/src/main/res/drawable/ic_repeat_one.xml @@ -0,0 +1,10 @@ + + + + diff --git a/app/src/main/res/drawable/ic_shuffle_off.xml b/app/src/main/res/drawable/ic_shuffle_off.xml new file mode 100644 index 0000000000..3ede806a20 --- /dev/null +++ b/app/src/main/res/drawable/ic_shuffle_off.xml @@ -0,0 +1,11 @@ + + + + diff --git a/app/src/main/res/drawable/ic_shuffle_on.xml b/app/src/main/res/drawable/ic_shuffle_on.xml new file mode 100644 index 0000000000..8f62d5de55 --- /dev/null +++ b/app/src/main/res/drawable/ic_shuffle_on.xml @@ -0,0 +1,10 @@ + + + + diff --git a/app/src/main/res/drawable/ic_soundtrack.xml b/app/src/main/res/drawable/ic_soundtrack.xml new file mode 100644 index 0000000000..00839efe01 --- /dev/null +++ b/app/src/main/res/drawable/ic_soundtrack.xml @@ -0,0 +1,10 @@ + + + + diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index 573c669b9d..e3d78e199b 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -28,6 +28,8 @@ ุชุนู„ูŠู‚ ุงู„ุขู† ุฅูŠู‚ุงู ุงู„ุฌู„ุณุฉ ุชูˆู„ูŠุฏ ุงู„ุฅุทุงุฑุงุช + ุฅุนุฏุงุฏุงุช ู‡ุฐู‡ ุงู„ู„ุนุจุฉ + ุงู„ุฅุนุฏุงุฏุงุช ุงู„ุงูุชุฑุงุถูŠุฉ ุงุฎุชุฑ ูˆุถุน ุชูˆู„ูŠุฏ ุงู„ุฅุทุงุฑุงุช ุฅูŠู‚ุงู DD-FG %1$dร— @@ -486,6 +488,7 @@ ุชุดุบูŠู„ ูŠุจุฏุฃ ู…ุน Steam ูŠุจุฏุฃ ุจุฏูˆู† Steam + ุฏู‚ุฉ ุงู„ู„ุนุจุฉ ุงู„ุฅุนุฏุงุฏุงุช ุฅุนุฏุงุฏุงุช %1$s ุงู„ุงูุชุฑุงุถูŠ @@ -2289,7 +2292,6 @@ ุงู„ู…ุชุงุฌุฑ Steam ู…ุฎุตูŽู‘ุต - ุงู„ู…ุชุงุฌุฑ ูุฆุฉ ุณุฑุนุฉ ุงู„ุชู†ุฒูŠู„ ู…ุชูˆุงุฒู† ุณุฑูŠุน @@ -2335,6 +2337,7 @@ ู…ู†ู‚ุทุน ุชุซุจูŠุช ยท %1$s ุงุญุตู„ ุนู„ูŠู‡ุง ู…ุฌุงู†ู‹ุง + ุฌุงุฑู ุงู„ุฅุถุงูุฉ ุฅู„ู‰ ุงู„ู…ูƒุชุจุฉโ€ฆ ุนุฑุถ ุนู„ู‰ %1$s ุดุฑุงุก ยท %1$s ู…ุซุจูŽู‘ุชุฉ @@ -2673,7 +2676,9 @@ %1$s ยท ูŠู„ุฒู… ุฅุนุงุฏุฉ ุชุดุบูŠู„ ู‡ุฐุง ุงู„ุฌู‡ุงุฒ ุฅุฒุงู„ุฉ %1$sุŸ - ุงู„ุชุดุฎูŠุต + ุงู„ู…ุทูˆู‘ุฑ + ุนู„ุงู…ุฉ ู…ุงุฆูŠุฉ ู„ุงุณู… ุงู„ุฅุตุฏุงุฑ + ุนุฑุถ ุงุณู… ุฅุตุฏุงุฑ ุงู„ุงุฎุชุจุงุฑ ุฃูˆ Lab ุนู„ู‰ ุงู„ุดุงุดุฉ. ู…ูุนู‘ู„ ุงูุชุฑุงุถูŠู‹ุง. ุฌุงู‡ุฒ ู„ู„ู‘ุนุจ ุบูŠุฑ ุฌุงู‡ุฒ ู„ู„ู‘ุนุจ ุจุนุฏ ุจูŠุฆุฉ ุงู„ุชุดุบูŠู„ %1$s @@ -3694,6 +3699,25 @@ ู†ู‚ู„ ุฅู„ู‰ ุงู„ุฎู„ู ุฅุนุฏุงุฏุงุช ุงู„ุฃุฏุงุฉ ุฅุฒุงู„ุฉ ุงู„ุฃุฏุงุฉ + ุงู„ู…ุธู‡ุฑ + ุญุฒู…ุฉ ุงู„ุฑู…ูˆุฒ + ุงู„ุงูุชุฑุงุถูŠ ู„ู„ู†ุธุงู… + ุฎู„ููŠุฉ ุจู„ูˆู† ุงู„ุชุทุจูŠู‚ + ุญุฌู… ุงู„ุฑู…ูˆุฒ + ุตุบูŠุฑ + ู…ุชูˆุณุท + ูƒุจูŠุฑ + ุฅุฎูุงุก ุฃุณู…ุงุก ุงู„ุชุทุจูŠู‚ุงุช + ุงู„ุชุจุงุนุฏ + ุถูŠู‚ + ุนุงุฏูŠ + ูˆุงุณุน + ุชุบูŠูŠุฑ ุงู„ุฑู…ุฒ + ุฅุนุงุฏุฉ ุถุจุท ุงู„ุฑู…ุฒ + ุงู„ุจุญุซ ููŠ ุงู„ุฑู…ูˆุฒ + ุฌุงุฑู ุชุญู…ูŠู„ ุงู„ุฑู…ูˆุฒโ€ฆ + ู„ู… ูŠุชู… ุงู„ุนุซูˆุฑ ุนู„ู‰ ุฑู…ูˆุฒ. + ุฑู…ูˆุฒ ู…ุฎุตู‘ุตุฉ ุฅุถุงูุฉ ุฅู„ู‰ ู…ุฌู„ุฏ ู…ุฌู„ุฏ ุฌุฏูŠุฏ ุฅุฒุงู„ุฉ ู…ู† ุงู„ู…ุฌู„ุฏ @@ -3814,4 +3838,66 @@ ุซู„ุฌ ู‚ุฑู…ุฒูŠ + ุงู„ู…ูˆุณูŠู‚ู‰ ุงู„ุชุตูˆูŠุฑูŠุฉ + ุงู„ู…ูˆุณูŠู‚ู‰ + ุฎูŠุงุฑุงุช ุงู„ุชุดุบูŠู„ + ุงู„ู…ูุถู„ุฉ + ุงู„ู…ุฌู…ูˆุนุงุช + ู„ุง ุชูˆุฌุฏ ู…ุฌู…ูˆุนุงุช ุจุนุฏ. ุงุถุบุท ุนู„ู‰ ุฃูŠู‚ูˆู†ุฉ ุงู„ุฅุดุงุฑุฉ ุงู„ู…ุฑุฌุนูŠุฉ ู„ุฅู†ุดุงุก ู…ุฌู…ูˆุนุฉ. + ุงู„ู…ุญููˆุธุงุช + ุฅู†ุดุงุก ู…ุฌู…ูˆุนุฉ + ู†ุธู‘ู… ู…ุง ุญูุธุชู‡ + ุฌุฏูŠุฏ + ุฅู†ุดุงุก + ุงุณู… ุงู„ู…ุฌู…ูˆุนุฉ + ุฃุฏุฎู„ ุงุณู…ู‹ุง ู„ุง ุชุณุชุฎุฏู…ู‡ ุฃูŠ ู…ุฌู…ูˆุนุฉ ุฃุฎุฑู‰ + ุฅุฏุงุฑุฉ + ุฅุนุงุฏุฉ ุชุณู…ูŠุฉ + ุฅุถุงูุฉ ู…ู‚ุงุทุน + ุฅุถุงูุฉ (%1$d) + ุฅุฒุงู„ุฉ ู…ู‚ุงุทุน + ุญุฐู ุงู„ู…ุฌู…ูˆุนุฉ + ุญุฐู %1$sุŸ + ุชุจู‚ู‰ ุงู„ู…ู‚ุงุทุน ุนู„ู‰ ุฌู‡ุงุฒูƒ. ุชุชู… ุฅุฒุงู„ุฉ ุงู„ู…ุฌู…ูˆุนุฉ ูู‚ุท. + ุชุญุฏูŠุฏ + ุชุญุฏูŠุฏ ุงู„ูƒู„ + ุฅู„ุบุงุก ุชุญุฏูŠุฏ ุงู„ูƒู„ + ุชู… ุชุญุฏูŠุฏ %1$d + ุฅุถุงูุฉ ุฅู„ู‰ ู…ุฌู…ูˆุนุฉ + ุฅุถุงูุฉ ุฅู„ู‰ ุงู„ู…ูุถู„ุฉ + ุฅุฒุงู„ุฉ ู…ู† ุงู„ู…ุฌู…ูˆุนุฉ + ุงุจุญุซ ููŠ ุงู„ู…ู‚ุงุทุน + ุชุฑุชูŠุจ ุงู„ุฃู„ุจูˆู… + ุงู„ุฃุทูˆู„ ุฃูˆู„ู‹ุง + ุงู„ุฃู‚ุตุฑ ุฃูˆู„ู‹ุง + ุงู„ู…ู‚ุงุทุน + ุทุจู‚ุฉ ุงู„ุตูˆุช + ุฅุนุงุฏุฉ ุถุจุท + ุชุฎุทูŠ ุงู„ุตู…ุช + ู…ุคู‚ุช ุงู„ู†ูˆู… + %1$d ุฏ + ู†ู‡ุงูŠุฉ ุงู„ู…ู‚ุทุน + ู…ุชุจู‚ูŠ %1$s + ุงู„ู…ุนุงุฏู„ + ุชุนุฒูŠุฒ ุงู„ุฌู‡ูŠุฑ + ุงู„ู…ุนุงุฏู„ ุบูŠุฑ ู…ุชุงุญ ุนู„ู‰ ู‡ุฐุง ุงู„ุฌู‡ุงุฒ + ุชูุนูŠู„ ุฃุซู†ุงุก ุงู„ู„ุนุจ + ุงุณุชู…ุฑ ููŠ ุชุดุบูŠู„ ุงู„ู…ูˆุณูŠู‚ู‰ ุงู„ุชุตูˆูŠุฑูŠุฉ ุฃุซู†ุงุก ุชุดุบูŠู„ ุงู„ู„ุนุจุฉ + ู„ุง ุชูˆุฌุฏ ู…ูˆุณูŠู‚ู‰ ุชุตูˆูŠุฑูŠุฉ ู…ุซุจู‘ุชุฉ ุจุนุฏ. + ุงุจุญุซ ููŠ ุงู„ู…ูˆุณูŠู‚ู‰ ุงู„ุชุตูˆูŠุฑูŠุฉ + ุฅุถุงูุฉ ู…ุฌู„ุฏ ู…ูˆุณูŠู‚ู‰ ุชุตูˆูŠุฑูŠุฉ + ู„ุง ุชูˆุฌุฏ ู…ู„ูุงุช ุตูˆุชูŠุฉ ููŠ ู‡ุฐุง ุงู„ู…ุฌู„ุฏ + ุงู„ู…ุฏุฉ ุงู„ุฅุฌู…ุงู„ูŠุฉ + %1$d ู…ู‚ุทุนู‹ุง / %2$s + ุงู„ู‚ุฑุต %1$s + ุนุดูˆุงุฆูŠ + ุงู„ุณุงุจู‚ + ุชุดุบูŠู„ + ุฅูŠู‚ุงู ู…ุคู‚ุช + ุงู„ุชุงู„ูŠ + ุงู„ุชูƒุฑุงุฑ ู…ุชูˆู‚ู + ุชูƒุฑุงุฑ ุงู„ูƒู„ + ุชูƒุฑุงุฑ ู…ู‚ุทุน ูˆุงุญุฏ + ู…ุณุชูˆู‰ ุงู„ุตูˆุช + ู„ุง ุชูˆุฌุฏ ู…ู„ูุงุช ุตูˆุชูŠุฉ ููŠ ู‡ุฐู‡ ุงู„ู…ูˆุณูŠู‚ู‰ ุงู„ุชุตูˆูŠุฑูŠุฉ diff --git a/app/src/main/res/values-b+es+419/strings.xml b/app/src/main/res/values-b+es+419/strings.xml index f38bdcee46..bcd645f8f2 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -28,6 +28,8 @@ Suspender ahora Detener sesiรณn Generaciรณn de fotogramas + Ajustes para este juego + Ajustes predeterminados Elige el modo de generaciรณn de fotogramas Desactivada DD-FG %1$dร— @@ -480,6 +482,7 @@ Activado Se inicia con Steam Se inicia sin Steam + Resoluciรณn del juego Ajustes Ajustes de %1$s Predeterminado @@ -2258,7 +2261,6 @@ Tiendas Steam Personalizados - Tiendas Nivel de velocidad de descarga Equilibrado Rรกpido @@ -2304,6 +2306,7 @@ Interrumpida Instalar ยท %1$s Obtener gratis + Agregando a la bibliotecaโ€ฆ Ver en %1$s Comprar ยท %1$s Instalado @@ -2610,7 +2613,9 @@ %1$s ยท reinicio pendiente Este dispositivo ยฟQuitar %1$s? - Diagnรณstico + Desarrollador + Marca de agua de compilaciรณn + Muestra en pantalla la etiqueta de la versiรณn de prueba o Lab. Activada de forma predeterminada. Listo para jugar Aรบn no estรก listo para jugar runtime %1$s @@ -3553,6 +3558,25 @@ Mover despuรฉs Configuraciรณn del widget Quitar widget + Apariencia + Paquete de iconos + Predeterminado del sistema + Fondo con color de la app + Tamaรฑo de iconos + Pequeรฑo + Mediano + Grande + Ocultar nombres de apps + Espaciado + Denso + Normal + Amplio + Cambiar icono + Restablecer icono + Buscar iconos + Cargando iconosโ€ฆ + No se encontraron iconos. + Iconos personalizados Agregar a carpeta Carpeta nueva Quitar de la carpeta @@ -3669,4 +3693,66 @@ No se pudo importar esta disposiciรณn Nieve escarlata Superficies blancas con acentos rojos. + Bandas sonoras + Mรบsica + Opciones de reproducciรณn + Favoritos + Colecciones + Aรบn no hay colecciones. Toca el รญcono de marcador para crear una. + Guardados + Crear una colecciรณn + Organiza tus guardados + Nueva + Crear + Nombre de la colecciรณn + Ingresa un nombre que no use ninguna otra colecciรณn + Administrar + Cambiar nombre + Agregar pistas + Agregar (%1$d) + Quitar pistas + Eliminar colecciรณn + ยฟEliminar %1$s? + Las pistas permanecen en tu dispositivo. Solo se elimina la colecciรณn. + Seleccionar + Seleccionar todo + Deseleccionar todo + %1$d seleccionadas + Agregar a la colecciรณn + Agregar a favoritos + Quitar de la colecciรณn + Buscar pistas + Orden del รกlbum + Mรกs largas primero + Mรกs cortas primero + Pistas + Tono + Restablecer + Omitir silencios + Temporizador de sueรฑo + %1$d min + Fin de la pista + Quedan %1$s + Ecualizador + Refuerzo de graves + El ecualizador no estรก disponible en este dispositivo + Activar en el juego + Mantรฉn la banda sonora sonando mientras se ejecuta un juego + Aรบn no hay bandas sonoras instaladas. + Buscar bandas sonoras + Aรฑadir una carpeta de banda sonora + No hay archivos de audio en esa carpeta + Duraciรณn total + %1$d pistas / %2$s + Disco %1$s + Aleatorio + Anterior + Reproducir + Pausar + Siguiente + Repeticiรณn desactivada + Repetir todo + Repetir una + Volumen + No hay archivos de audio en esta banda sonora diff --git a/app/src/main/res/values-bg/strings.xml b/app/src/main/res/values-bg/strings.xml index 36751e5311..ce0b441579 100644 --- a/app/src/main/res/values-bg/strings.xml +++ b/app/src/main/res/values-bg/strings.xml @@ -28,6 +28,8 @@ ะŸั€ะธัะฟะธ ัะตะณะฐ ะกะฟั€ะธ ัะตัะธัั‚ะฐ ะ“ะตะฝะตั€ะธั€ะฐะฝะต ะฝะฐ ะบะฐะดั€ะธ + ะะฐัั‚ั€ะพะนะบะธ ะทะฐ ั‚ะฐะทะธ ะธะณั€ะฐ + ะะฐัั‚ั€ะพะนะบะธ ะฟะพ ะฟะพะดั€ะฐะทะฑะธั€ะฐะฝะต ะ˜ะทะฑะตั€ะตั‚ะต ั€ะตะถะธะผะฐ ะฝะฐ ะณะตะฝะตั€ะธั€ะฐะฝะต ะฝะฐ ะบะฐะดั€ะธ ะ˜ะทะบะปัŽั‡ะตะฝะพ DD-FG %1$dร— @@ -478,6 +480,7 @@ ะ’ะบะปัŽั‡ะตะฝะพ ะกั‚ะฐั€ั‚ะธั€ะฐ ััŠั Steam ะกั‚ะฐั€ั‚ะธั€ะฐ ะฑะตะท Steam + ะ ะตะทะพะปัŽั†ะธั ะฝะฐ ะธะณั€ะฐั‚ะฐ ะะฐัั‚ั€ะพะนะบะธ ะะฐัั‚ั€ะพะนะบะธ ะฝะฐ %1$s ะŸะพ ะฟะพะดั€ะฐะทะฑะธั€ะฐะฝะต @@ -2189,7 +2192,6 @@ ะœะฐะณะฐะทะธะฝะธ Steam ะŸะตั€ัะพะฝะฐะปะธะทะธั€ะฐะฝะฐ - ะœะฐะณะฐะทะธะฝะธ ะกะบะพั€ะพัั‚ ะฝะฐ ะธะทั‚ะตะณะปัะฝะต ะ‘ะฐะปะฐะฝัะธั€ะฐะฝะพ ะ‘ัŠั€ะทะพ @@ -2235,6 +2237,7 @@ ะŸั€ะตะบัŠัะฝะฐั‚ะพ ะ˜ะฝัั‚ะฐะปะฐั†ะธั ยท %1$s ะ’ะทะตะผะธ ะฑะตะทะฟะปะฐั‚ะฝะพ + ะ”ะพะฑะฐะฒัะฝะต ะฒ ะฑะธะฑะปะธะพั‚ะตะบะฐั‚ะฐโ€ฆ ะ’ะธะถ ะฒ %1$s ะšัƒะฟะธ ยท %1$s ะ˜ะฝัั‚ะฐะปะธั€ะฐะฝะฐ @@ -2565,7 +2568,9 @@ %1$s ยท ะฝัƒะถะตะฝ ะต ั€ะตัั‚ะฐั€ั‚ ะขะพะฒะฐ ัƒัั‚ั€ะพะนัั‚ะฒะพ ะŸั€ะตะผะฐั…ะฒะฐะฝะต ะฝะฐ %1$s? - ะ”ะธะฐะณะฝะพัั‚ะธะบะฐ + ะ ะฐะทั€ะฐะฑะพั‚ั‡ะธะบ + ะ’ะพะดะตะฝ ะทะฝะฐะบ ั ะตั‚ะธะบะตั‚ ะฝะฐ ะบะพะผะฟะธะปะฐั†ะธัั‚ะฐ + ะŸะพะบะฐะทะฒะฐ ะตั‚ะธะบะตั‚ะฐ ะฝะฐ ั‚ะตัั‚ะพะฒะฐั‚ะฐ ะธะปะธ Lab ะบะพะผะฟะธะปะฐั†ะธั ะฝะฐ ะตะบั€ะฐะฝะฐ. ะ’ะบะปัŽั‡ะตะฝะพ ะฟะพ ะฟะพะดั€ะฐะทะฑะธั€ะฐะฝะต. ะ“ะพั‚ะพะฒะพ ะทะฐ ะธะณั€ะฐ ะžั‰ะต ะฝะต ะต ะณะพั‚ะพะฒะพ ะทะฐ ะธะณั€ะฐ ัั€ะตะดะฐ %1$s @@ -3542,6 +3547,25 @@ ะŸั€ะตะผะตัั‚ะฒะฐะฝะต ะฟะพ-ะบัŠัะฝะพ ะะฐัั‚ั€ะพะนะบะธ ะฝะฐ ะฟั€ะธัะฟะพัะพะฑะปะตะฝะธะตั‚ะพ ะŸั€ะตะผะฐั…ะฒะฐะฝะต ะฝะฐ ะฟั€ะธัะฟะพัะพะฑะปะตะฝะธะตั‚ะพ + ะ’ัŠะฝัˆะตะฝ ะฒะธะด + ะŸะฐะบะตั‚ ั ะธะบะพะฝะธ + ะŸะพ ะฟะพะดั€ะฐะทะฑะธั€ะฐะฝะต ะพั‚ ัะธัั‚ะตะผะฐั‚ะฐ + ะคะพะฝ ะฒ ั†ะฒะตั‚ะฐ ะฝะฐ ะฟั€ะธะปะพะถะตะฝะธะตั‚ะพ + ะ ะฐะทะผะตั€ ะฝะฐ ะธะบะพะฝะธั‚ะต + ะœะฐะปัŠะบ + ะกั€ะตะดะตะฝ + ะ“ะพะปัะผ + ะกะบั€ะธะฒะฐะฝะต ะฝะฐ ะธะผะตะฝะฐั‚ะฐ + ะ ะฐะทัั‚ะพัะฝะธะต + ะŸะปัŠั‚ะฝะพ + ะกั€ะตะดะฝะพ + ะจะธั€ะพะบะพ + ะŸั€ะพะผัะฝะฐ ะฝะฐ ะธะบะพะฝะฐั‚ะฐ + ะัƒะปะธั€ะฐะฝะต ะฝะฐ ะธะบะพะฝะฐั‚ะฐ + ะขัŠั€ัะตะฝะต ะฝะฐ ะธะบะพะฝะธ + ะ˜ะบะพะฝะธั‚ะต ัะต ะทะฐั€ะตะถะดะฐั‚โ€ฆ + ะัะผะฐ ะฝะฐะผะตั€ะตะฝะธ ะธะบะพะฝะธ. + ะŸะตั€ัะพะฝะฐะปะธะทะธั€ะฐะฝะธ ะธะบะพะฝะธ ะ”ะพะฑะฐะฒัะฝะต ะฒ ะฟะฐะฟะบะฐ ะะพะฒะฐ ะฟะฐะฟะบะฐ ะŸั€ะตะผะฐั…ะฒะฐะฝะต ะพั‚ ะฟะฐะฟะบะฐั‚ะฐ @@ -3658,4 +3682,66 @@ ะะปะตะฝ ัะฝัะณ + ะกะฐัƒะฝะดั‚ั€ะฐั†ะธ + ะœัƒะทะธะบะฐ + ะžะฟั†ะธะธ ะทะฐ ะฒัŠะทะฟั€ะพะธะทะฒะตะถะดะฐะฝะต + ะ›ัŽะฑะธะผะธ + ะšะพะปะตะบั†ะธะธ + ะ’ัะต ะพั‰ะต ะฝัะผะฐ ะบะพะปะตะบั†ะธะธ. ะ”ะพะบะพัะฝะตั‚ะต ะธะบะพะฝะฐั‚ะฐ ะฝะฐ ะพั‚ะผะตั‚ะบะฐ, ะทะฐ ะดะฐ ััŠะทะดะฐะดะตั‚ะต. + ะ—ะฐะฟะฐะทะตะฝะธ + ะกัŠะทะดะฐะฒะฐะฝะต ะฝะฐ ะบะพะปะตะบั†ะธั + ะžั€ะณะฐะฝะธะทะธั€ะฐะนั‚ะต ะทะฐะฟะฐะทะตะฝะพั‚ะพ + ะะพะฒะฐ + ะกัŠะทะดะฐะน + ะ˜ะผะต ะฝะฐ ะบะพะปะตะบั†ะธัั‚ะฐ + ะ’ัŠะฒะตะดะตั‚ะต ะธะผะต, ะบะพะตั‚ะพ ะฝะต ัะต ะธะทะฟะพะปะทะฒะฐ ะพั‚ ะดั€ัƒะณะฐ ะบะพะปะตะบั†ะธั + ะฃะฟั€ะฐะฒะปะตะฝะธะต + ะŸั€ะตะธะผะตะฝัƒะฒะฐะฝะต + ะ”ะพะฑะฐะฒัะฝะต ะฝะฐ ะฟะตัะฝะธ + ะ”ะพะฑะฐะฒะธ (%1$d) + ะŸั€ะตะผะฐั…ะฒะฐะฝะต ะฝะฐ ะฟะตัะฝะธ + ะ˜ะทั‚ั€ะธะฒะฐะฝะต ะฝะฐ ะบะพะปะตะบั†ะธั + ะ”ะฐ ัะต ะธะทั‚ั€ะธะต ะปะธ %1$s? + ะŸะตัะฝะธั‚ะต ะพัั‚ะฐะฒะฐั‚ ะฝะฐ ัƒัั‚ั€ะพะนัั‚ะฒะพั‚ะพ ะฒะธ. ะŸั€ะตะผะฐั…ะฒะฐ ัะต ัะฐะผะพ ะบะพะปะตะบั†ะธัั‚ะฐ. + ะ˜ะทะฑะพั€ + ะ˜ะทะฑะตั€ะธ ะฒัะธั‡ะบะธ + ะžั‚ะผะตะฝะธ ะธะทะฑะพั€ะฐ ะฝะฐ ะฒัะธั‡ะบะธ + ะ˜ะทะฑั€ะฐะฝะธ: %1$d + ะ”ะพะฑะฐะฒะธ ะบัŠะผ ะบะพะปะตะบั†ะธั + ะ”ะพะฑะฐะฒะธ ะฒ ะปัŽะฑะธะผะธ + ะŸั€ะตะผะฐั…ะฝะธ ะพั‚ ะบะพะปะตะบั†ะธัั‚ะฐ + ะขัŠั€ัะตะฝะต ะฝะฐ ะฟะตัะฝะธ + ะšะฐั‚ะพ ะฒ ะฐะปะฑัƒะผะฐ + ะะฐะน-ะดัŠะปะณะธั‚ะต ะฟัŠั€ะฒะพ + ะะฐะน-ะบั€ะฐั‚ะบะธั‚ะต ะฟัŠั€ะฒะพ + ะŸะตัะฝะธ + ะ’ะธัะพั‡ะธะฝะฐ ะฝะฐ ั‚ะพะฝะฐ + ะัƒะปะธั€ะฐะฝะต + ะŸั€ะตัะบะฐั‡ะฐะฝะต ะฝะฐ ั‚ะธัˆะธะฝะฐ + ะขะฐะนะผะตั€ ะทะฐ ะทะฐัะฟะธะฒะฐะฝะต + %1$d ะผะธะฝ + ะšั€ะฐะน ะฝะฐ ะฟะตัะตะฝั‚ะฐ + ะžัั‚ะฐะฒะฐั‚ %1$s + ะ•ะบะฒะฐะปะฐะนะทะตั€ + ะฃัะธะปะฒะฐะฝะต ะฝะฐ ะฑะฐัะธั‚ะต + ะ•ะบะฒะฐะปะฐะนะทะตั€ัŠั‚ ะฝะต ะต ะฝะฐะปะธั‡ะตะฝ ะฝะฐ ั‚ะพะฒะฐ ัƒัั‚ั€ะพะนัั‚ะฒะพ + ะ’ะบะปัŽั‡ะธ ะฒ ะธะณั€ะฐั‚ะฐ + ะกะฐัƒะฝะดั‚ั€ะฐะบัŠั‚ ะดะฐ ะฟั€ะพะดัŠะปะถะธ ะดะฐ ัะฒะธั€ะธ, ะดะพะบะฐั‚ะพ ะฒัŠั€ะฒะธ ะธะณั€ะฐ + ะ’ัะต ะพั‰ะต ะฝัะผะฐ ะธะฝัั‚ะฐะปะธั€ะฐะฝะธ ัะฐัƒะฝะดั‚ั€ะฐั†ะธ. + ะขัŠั€ัะตะฝะต ะฝะฐ ัะฐัƒะฝะดั‚ั€ะฐั†ะธ + ะ”ะพะฑะฐะฒัะฝะต ะฝะฐ ะฟะฐะฟะบะฐ ััŠั ัะฐัƒะฝะดั‚ั€ะฐะบ + ะ’ ั‚ะฐะทะธ ะฟะฐะฟะบะฐ ะฝัะผะฐ ะฐัƒะดะธะพั„ะฐะนะปะพะฒะต + ะžะฑั‰ะฐ ะฟั€ะพะดัŠะปะถะธั‚ะตะปะฝะพัั‚ + %1$d ะฟะตัะฝะธ / %2$s + ะ”ะธัะบ %1$s + ะ ะฐะทะฑัŠั€ะบะฒะฐะฝะต + ะŸั€ะตะดะธัˆะฝะฐ + ะŸัƒัะบะฐะฝะต + ะŸะฐัƒะทะฐ + ะกะปะตะดะฒะฐั‰ะฐ + ะŸะพะฒั‚ะพั€ะตะฝะธะตั‚ะพ ะต ะธะทะบะปัŽั‡ะตะฝะพ + ะŸะพะฒั‚ะฐั€ัะฝะต ะฝะฐ ะฒัะธั‡ะบะธ + ะŸะพะฒั‚ะฐั€ัะฝะต ะฝะฐ ะตะดะฝะฐ + ะกะธะปะฐ ะฝะฐ ะทะฒัƒะบะฐ + ะ’ ั‚ะพะทะธ ัะฐัƒะฝะดั‚ั€ะฐะบ ะฝัะผะฐ ะฐัƒะดะธะพั„ะฐะนะปะพะฒะต diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index 010374a13e..d8a5d60f28 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -28,6 +28,8 @@ Pozastavit teฤ Ukonฤit relaci Generovรกnรญ snรญmkลฏ + Nastavenรญ pro tuto hru + Vรฝchozรญ nastavenรญ Vyberte reลพim generovรกnรญ snรญmkลฏ Vypnuto DD-FG %1$dร— @@ -482,6 +484,7 @@ Zapnuto Spouลกtรญ se se Steamem Spouลกtรญ se bez Steamu + Rozliลกenรญ hry Nastavenรญ Nastavenรญ %1$s Vรฝchozรญ @@ -2239,7 +2242,6 @@ Obchody Steam Vlastnรญ - Obchody รšroveลˆ rychlosti stahovรกnรญ Vyvรกลพenรฉ Rychlรฉ @@ -2285,6 +2287,7 @@ Pล™eruลกeno Instalace ยท %1$s Zรญskat zdarma + Pล™idรกvรกnรญ do knihovnyโ€ฆ Zobrazit na %1$s Koupit ยท %1$s Nainstalovรกno @@ -2619,7 +2622,9 @@ %1$s ยท ฤekรก na restart Toto zaล™รญzenรญ Odstranit %1$s? - Diagnostika + Vรฝvojรกล™ + Vodoznak s oznaฤenรญm sestavenรญ + Zobrazit na obrazovce oznaฤenรญ testovacรญho sestavenรญ nebo sestavenรญ Lab. Ve vรฝchozรญm nastavenรญ zapnutรฉ. Pล™ipraveno ke hranรญ Jeลกtฤ› nenรญ pล™ipraveno ke hranรญ runtime %1$s @@ -3618,6 +3623,25 @@ Posunout pozdฤ›ji Nastavenรญ widgetu Odebrat widget + Vzhled + Balรญฤek ikon + Vรฝchozรญ systรฉmovรฝ + Pozadรญ v barvฤ› aplikace + Velikost ikon + Malรฉ + Stล™ednรญ + Velkรฉ + Skrรฝt nรกzvy aplikacรญ + Rozestupy + Tฤ›snรฉ + Bฤ›ลพnรฉ + Volnรฉ + Zmฤ›nit ikonu + Obnovit ikonu + Hledat ikony + Naฤรญtรกnรญ ikonโ€ฆ + Nebyly nalezeny ลพรกdnรฉ ikony. + Vlastnรญ ikony Pล™idat do sloลพky Novรก sloลพka Odebrat ze sloลพky @@ -3736,4 +3760,66 @@ ล arlatovรฝ snรญh + Soundtracky + Hudba + Moลพnosti pล™ehrรกvรกnรญ + Oblรญbenรฉ + Kolekce + Zatรญm ลพรกdnรฉ kolekce. Klepnutรญm na ikonu zรกloลพky nฤ›jakou vytvoล™รญte. + Uloลพeno + Vytvoล™it kolekci + Uspoล™รกdejte si uloลพenรฉ skladby + Novรก + Vytvoล™it + Nรกzev kolekce + Zadejte nรกzev, kterรฝ nepouลพรญvรก ลพรกdnรก jinรก kolekce + Spravovat + Pล™ejmenovat + Pล™idat skladby + Pล™idat (%1$d) + Odebrat skladby + Smazat kolekci + Smazat %1$s? + Skladby zลฏstanou ve vaลกem zaล™รญzenรญ. Odstranรญ se pouze kolekce. + Vybrat + Vybrat vลกe + Zruลกit vรฝbฤ›r + Vybrรกno: %1$d + Pล™idat do kolekce + Pล™idat do oblรญbenรฝch + Odebrat z kolekce + Hledat skladby + Poล™adรญ alba + Nejdelลกรญ prvnรญ + Nejkratลกรญ prvnรญ + Skladby + Vรฝลกka tรณnu + Obnovit + Pล™eskakovat ticho + ฤŒasovaฤ vypnutรญ + %1$d min + Konec skladby + Zbรฝvรก %1$s + Ekvalizรฉr + Zesรญlenรญ basลฏ + Ekvalizรฉr nenรญ na tomto zaล™รญzenรญ k dispozici + Povolit ve hล™e + Nechat soundtrack hrรกt bฤ›hem hry + Zatรญm nejsou nainstalovรกny ลพรกdnรฉ soundtracky. + Hledat soundtracky + Pล™idat sloลพku se soundtrackem + V tรฉto sloลพce nejsou ลพรกdnรฉ zvukovรฉ soubory + Celkovรก dรฉlka + Skladeb: %1$d / %2$s + Disk %1$s + Nรกhodnฤ› + Pล™edchozรญ + Pล™ehrรกt + Pozastavit + Dalลกรญ + Opakovรกnรญ vypnuto + Opakovat vลกe + Opakovat jednu + Hlasitost + V tomto soundtracku nejsou ลพรกdnรฉ zvukovรฉ soubory diff --git a/app/src/main/res/values-da/strings.xml b/app/src/main/res/values-da/strings.xml index f0c0527365..2b47c9f391 100644 --- a/app/src/main/res/values-da/strings.xml +++ b/app/src/main/res/values-da/strings.xml @@ -28,6 +28,8 @@ Sรฆt pรฅ pause nu Afslut session Billedgenerering + Indstillinger for dette spil + Standardindstillinger Vรฆlg metode til billedgenerering Fra DD-FG %1$dร— @@ -478,6 +480,7 @@ Til Starter med Steam Starter uden Steam + Spiloplรธsning Indstillinger Indstillinger for %1$s Standard @@ -2189,7 +2192,6 @@ Butikker Steam Brugerdefineret - Butikker Downloadhastighed Afbalanceret Hurtig @@ -2235,6 +2237,7 @@ Afbrudt Installation ยท %1$s Fรฅ gratis + Fรธjer til biblioteketโ€ฆ Se pรฅ %1$s Kรธb ยท %1$s Installeret @@ -2565,7 +2568,9 @@ %1$s ยท krรฆver genstart Denne enhed Fjern %1$s? - Diagnostik + Udvikler + Vandmรฆrke med buildmรฆrkat + Vis mรฆrkatet for test- eller Lab-builden pรฅ skรฆrmen. Aktiveret som standard. Klar til at spille Ikke klar til at spille endnu runtime %1$s @@ -3542,6 +3547,25 @@ Flyt senere Widgetindstillinger Fjern widget + Udseende + Ikonpakke + Systemstandard + Baggrund i appens farve + Ikonstรธrrelse + Lille + Mellem + Stor + Skjul appnavne + Afstand + Tรฆt + Normal + Luftig + Skift ikon + Nulstil ikon + Sรธg efter ikoner + Indlรฆser ikonerโ€ฆ + Ingen ikoner fundet. + Brugerdefinerede ikoner Fรธj til mappe Ny mappe Fjern fra mappe @@ -3658,4 +3682,66 @@ Skarlagensne + Soundtracks + Musik + Afspilningsindstillinger + Favoritter + Samlinger + Ingen samlinger endnu. Tryk pรฅ bogmรฆrkeikonet for at oprette en. + Gemt + Opret en samling + Organiser dine gemte numre + Ny + Opret + Navn pรฅ samling + Angiv et navn, som ingen anden samling bruger + Administrer + Omdรธb + Tilfรธj numre + Tilfรธj (%1$d) + Fjern numre + Slet samling + Slet %1$s? + Numrene bliver pรฅ din enhed. Kun samlingen fjernes. + Vรฆlg + Vรฆlg alle + Fravรฆlg alle + %1$d valgt + Fรธj til samling + Fรธj til favoritter + Fjern fra samling + Sรธg i numre + Albumrรฆkkefรธlge + Lรฆngste fรธrst + Korteste fรธrst + Numre + Tonehรธjde + Nulstil + Spring stilhed over + Sovetimer + %1$d min. + Slut pรฅ nummer + %1$s tilbage + Equalizer + Bassforstรฆrkning + Equalizeren er ikke tilgรฆngelig pรฅ denne enhed + Aktivรฉr i spil + Lad soundtracket spille, mens et spil kรธrer + Ingen soundtracks installeret endnu. + Sรธg i soundtracks + Tilfรธj en soundtrack-mappe + Ingen lydfiler i den mappe + Samlet lรฆngde + %1$d numre / %2$s + Disk %1$s + Bland + Forrige + Afspil + Pause + Nรฆste + Gentag fra + Gentag alle + Gentag รฉn + Lydstyrke + Ingen lydfiler i dette soundtrack diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index ad656b8bb8..c2d0dcb4fc 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -28,6 +28,8 @@ Jetzt anhalten Sitzung beenden Frame-Generierung + Einstellungen fรผr dieses Spiel + Standardeinstellungen Modus der Frame-Generierung auswรคhlen Aus DD-FG %1$dร— @@ -478,6 +480,7 @@ An Startet mit Steam Startet ohne Steam + Spielauflรถsung Einstellungen Einstellungen fรผr %1$s Standard @@ -2181,7 +2184,6 @@ Stores Steam Eigene - Stores Download-Tempo Ausgewogen Schnell @@ -2227,6 +2229,7 @@ Unterbrochen Installieren ยท %1$s Kostenlos erhalten + Wird zur Bibliothek hinzugefรผgtโ€ฆ Auf %1$s ansehen Kaufen ยท %1$s Installiert @@ -2554,7 +2557,9 @@ %1$s ยท Neustart ausstehend Dieses Gerรคt %1$s entfernen? - Diagnose + Entwickler + Build-Kennzeichnung als Wasserzeichen + Kennzeichnung des Test- oder Lab-Builds auf dem Bildschirm anzeigen. StandardmรครŸig aktiviert. Bereit zum Spielen Noch nicht bereit zum Spielen Laufzeit %1$s @@ -3542,6 +3547,25 @@ Nach hinten Widget-Einstellungen Widget entfernen + Darstellung + Symbolpaket + Systemstandard + Hintergrund in App-Farbe + SymbolgrรถรŸe + Klein + Mittel + GroรŸ + App-Namen ausblenden + Abstand + Eng + Normal + Weit + Symbol รคndern + Symbol zurรผcksetzen + Symbole suchen + Symbole werden geladenโ€ฆ + Keine Symbole gefunden. + Eigene Symbole Zu Ordner hinzufรผgen Neuer Ordner Aus Ordner entfernen @@ -3658,4 +3682,66 @@ Scharlachroter Schnee + Soundtracks + Musik + Wiedergabeoptionen + Favoriten + Sammlungen + Noch keine Sammlungen. Tippe auf das Lesezeichen-Symbol, um eine zu erstellen. + Gespeichert + Sammlung erstellen + Ordne deine gespeicherten Titel + Neu + Erstellen + Name der Sammlung + Gib einen Namen ein, den keine andere Sammlung verwendet + Verwalten + Umbenennen + Titel hinzufรผgen + Hinzufรผgen (%1$d) + Titel entfernen + Sammlung lรถschen + %1$s lรถschen? + Die Titel bleiben auf deinem Gerรคt. Nur die Sammlung wird entfernt. + Auswรคhlen + Alle auswรคhlen + Alle abwรคhlen + %1$d ausgewรคhlt + Zur Sammlung hinzufรผgen + Zu Favoriten hinzufรผgen + Aus Sammlung entfernen + Titel suchen + Albumreihenfolge + Lรคngste zuerst + Kรผrzeste zuerst + Titel + Tonhรถhe + Zurรผcksetzen + Stille รผberspringen + Schlaftimer + %1$d Min. + Ende des Titels + Noch %1$s + Equalizer + Bassverstรคrkung + Der Equalizer ist auf diesem Gerรคt nicht verfรผgbar + Im Spiel aktivieren + Soundtrack wรคhrend eines Spiels weiterspielen + Noch keine Soundtracks installiert. + Soundtracks durchsuchen + Soundtrack-Ordner hinzufรผgen + Keine Audiodateien in diesem Ordner + Gesamtlรคnge + %1$d Titel / %2$s + Disc %1$s + Zufรคllig + Zurรผck + Wiedergabe + Pause + Weiter + Wiederholen aus + Alle wiederholen + Titel wiederholen + Lautstรคrke + Keine Audiodateien in diesem Soundtrack diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index 0d7d8e1c91..203a3716a2 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -28,6 +28,8 @@ ฮ‘ฮฝฮฑฯƒฯ„ฮฟฮปฮฎ ฯ„ฯŽฯฮฑ ฮ”ฮนฮฑฮบฮฟฯ€ฮฎ ฯƒฯ…ฮฝฮตฮดฯฮฏฮฑฯ‚ ฮ”ฮทฮผฮนฮฟฯ…ฯฮณฮฏฮฑ ฮบฮฑฯฮญ + ฮกฯ…ฮธฮผฮฏฯƒฮตฮนฯ‚ ฮณฮนฮฑ ฮฑฯ…ฯ„ฯŒ ฯ„ฮฟ ฯ€ฮฑฮนฯ‡ฮฝฮฏฮดฮน + ฮ ฯฮฟฮตฯ€ฮนฮปฮตฮณฮผฮญฮฝฮตฯ‚ ฯฯ…ฮธฮผฮฏฯƒฮตฮนฯ‚ ฮ•ฯ€ฮนฮปฮญฮพฯ„ฮต ฯ„ฮท ฮปฮตฮนฯ„ฮฟฯ…ฯฮณฮฏฮฑ ฮดฮทฮผฮนฮฟฯ…ฯฮณฮฏฮฑฯ‚ ฮบฮฑฯฮญ ฮ‘ฮฝฮตฮฝฮตฯฮณฯŒ DD-FG %1$dร— @@ -478,6 +480,7 @@ ฮ•ฮฝฮตฯฮณฯŒ ฮžฮตฮบฮนฮฝฮฌ ฮผฮต ฯ„ฮฟ Steam ฮžฮตฮบฮนฮฝฮฌ ฯ‡ฯ‰ฯฮฏฯ‚ ฯ„ฮฟ Steam + ฮ‘ฮฝฮฌฮปฯ…ฯƒฮท ฯ€ฮฑฮนฯ‡ฮฝฮนฮดฮนฮฟฯ ฮกฯ…ฮธฮผฮฏฯƒฮตฮนฯ‚ ฮกฯ…ฮธฮผฮฏฯƒฮตฮนฯ‚ %1$s ฮ ฯฮฟฮตฯ€ฮนฮปฮฟฮณฮฎ @@ -2189,7 +2192,6 @@ ฮšฮฑฯ„ฮฑฯƒฯ„ฮฎฮผฮฑฯ„ฮฑ Steam ฮ ฯฮฟฯƒฮฑฯฮผฮฟฯƒฮผฮญฮฝฮฟ - ฮšฮฑฯ„ฮฑฯƒฯ„ฮฎฮผฮฑฯ„ฮฑ ฮ•ฯ€ฮฏฯ€ฮตฮดฮฟ ฯ„ฮฑฯ‡ฯฯ„ฮทฯ„ฮฑฯ‚ ฮปฮฎฯˆฮทฯ‚ ฮ™ฯƒฮฟฯฯฮฟฯ€ฮทฮผฮญฮฝฮฟ ฮคฮฑฯ‡ฯ @@ -2235,6 +2237,7 @@ ฮ”ฮนฮฑฮบฯŒฯ€ฮทฮบฮต ฮ•ฮณฮบฮฑฯ„ฮฌฯƒฯ„ฮฑฯƒฮท ยท %1$s ฮ‘ฯ€ฯŒฮบฯ„ฮทฯƒฮท ฮดฯ‰ฯฮตฮฌฮฝ + ฮ ฯฮฟฯƒฮธฮฎฮบฮท ฯƒฯ„ฮท ฮฒฮนฮฒฮปฮนฮฟฮธฮฎฮบฮทโ€ฆ ฮ ฯฮฟฮฒฮฟฮปฮฎ ฯƒฯ„ฮฟ %1$s ฮ‘ฮณฮฟฯฮฌ ยท %1$s ฮ•ฮณฮบฮฑฯ„ฮตฯƒฯ„ฮทฮผฮญฮฝฮฟ @@ -2565,7 +2568,9 @@ %1$s ยท ฮฑฯ€ฮฑฮนฯ„ฮตฮฏฯ„ฮฑฮน ฮตฯ€ฮฑฮฝฮตฮบฮบฮฏฮฝฮทฯƒฮท ฮ‘ฯ…ฯ„ฮฎ ฮท ฯƒฯ…ฯƒฮบฮตฯ…ฮฎ ฮšฮฑฯ„ฮฌฯฮณฮทฯƒฮท %1$s; - ฮ”ฮนฮฑฮณฮฝฯ‰ฯƒฯ„ฮนฮบฮฌ + ฮ ฯฮฟฮณฯฮฑฮผฮผฮฑฯ„ฮนฯƒฯ„ฮฎฯ‚ + ฮฅฮดฮฑฯ„ฮฟฮณฯฮฌฯ†ฮทฮผฮฑ ฮตฯ„ฮนฮบฮญฯ„ฮฑฯ‚ ฮญฮบฮดฮฟฯƒฮทฯ‚ + ฮ•ฮผฯ†ฮฌฮฝฮนฯƒฮท ฯ„ฮทฯ‚ ฮตฯ„ฮนฮบฮญฯ„ฮฑฯ‚ ฮดฮฟฮบฮนฮผฮฑฯƒฯ„ฮนฮบฮฎฯ‚ ฮญฮบฮดฮฟฯƒฮทฯ‚ ฮฎ ฮญฮบฮดฮฟฯƒฮทฯ‚ Lab ฯƒฯ„ฮทฮฝ ฮฟฮธฯŒฮฝฮท. ฮ•ฮฝฮตฯฮณฯŒ ฮฑฯ€ฯŒ ฯ€ฯฮฟฮตฯ€ฮนฮปฮฟฮณฮฎ. ฮˆฯ„ฮฟฮนฮผฮฟ ฮณฮนฮฑ ฯ€ฮฑฮนฯ‡ฮฝฮฏฮดฮน ฮ”ฮตฮฝ ฮตฮฏฮฝฮฑฮน ฮฑฮบฯŒฮผฮฑ ฮญฯ„ฮฟฮนฮผฮฟ ฮณฮนฮฑ ฯ€ฮฑฮนฯ‡ฮฝฮฏฮดฮน runtime %1$s @@ -3542,6 +3547,25 @@ ฮœฮตฯ„ฮฑฮบฮฏฮฝฮทฯƒฮท ฮฑฯฮณฯŒฯ„ฮตฯฮฑ ฮกฯ…ฮธฮผฮฏฯƒฮตฮนฯ‚ ฮณฯฮฑฯ†ฮนฮบฮฟฯ ฯƒฯ„ฮฟฮนฯ‡ฮตฮฏฮฟฯ… ฮ‘ฯ†ฮฑฮฏฯฮตฯƒฮท ฮณฯฮฑฯ†ฮนฮบฮฟฯ ฯƒฯ„ฮฟฮนฯ‡ฮตฮฏฮฟฯ… + ฮ•ฮผฯ†ฮฌฮฝฮนฯƒฮท + ฮ ฮฑฮบฮญฯ„ฮฟ ฮตฮนฮบฮฟฮฝฮนฮดฮฏฯ‰ฮฝ + ฮ ฯฮฟฮตฯ€ฮนฮปฮฟฮณฮฎ ฯƒฯ…ฯƒฯ„ฮฎฮผฮฑฯ„ฮฟฯ‚ + ฮฆฯŒฮฝฯ„ฮฟ ฮผฮต ฯ‡ฯฯŽฮผฮฑ ฮตฯ†ฮฑฯฮผฮฟฮณฮฎฯ‚ + ฮœฮญฮณฮตฮธฮฟฯ‚ ฮตฮนฮบฮฟฮฝฮนฮดฮฏฯ‰ฮฝ + ฮœฮนฮบฯฯŒ + ฮœฮตฯƒฮฑฮฏฮฟ + ฮœฮตฮณฮฌฮปฮฟ + ฮ‘ฯ€ฯŒฮบฯฯ…ฯˆฮท ฮฟฮฝฮฟฮผฮฌฯ„ฯ‰ฮฝ ฮตฯ†ฮฑฯฮผฮฟฮณฯŽฮฝ + ฮ‘ฯ€ฯŒฯƒฯ„ฮฑฯƒฮท + ฮฃฯ„ฮตฮฝฮฎ + ฮœฮญฯ„ฯฮนฮฑ + ฮ•ฯ…ฯฮตฮฏฮฑ + ฮ‘ฮปฮปฮฑฮณฮฎ ฮตฮนฮบฮฟฮฝฮนฮดฮฏฮฟฯ… + ฮ•ฯ€ฮฑฮฝฮฑฯ†ฮฟฯฮฌ ฮตฮนฮบฮฟฮฝฮนฮดฮฏฮฟฯ… + ฮ‘ฮฝฮฑฮถฮฎฯ„ฮทฯƒฮท ฮตฮนฮบฮฟฮฝฮนฮดฮฏฯ‰ฮฝ + ฮฆฯŒฯฯ„ฯ‰ฯƒฮท ฮตฮนฮบฮฟฮฝฮนฮดฮฏฯ‰ฮฝโ€ฆ + ฮ”ฮตฮฝ ฮฒฯฮญฮธฮทฮบฮฑฮฝ ฮตฮนฮบฮฟฮฝฮฏฮดฮนฮฑ. + ฮ ฯฮฟฯƒฮฑฯฮผฮฟฯƒฮผฮญฮฝฮฑ ฮตฮนฮบฮฟฮฝฮฏฮดฮนฮฑ ฮ ฯฮฟฯƒฮธฮฎฮบฮท ฯƒฮต ฯ†ฮฌฮบฮตฮปฮฟ ฮฮญฮฟฯ‚ ฯ†ฮฌฮบฮตฮปฮฟฯ‚ ฮ‘ฯ†ฮฑฮฏฯฮตฯƒฮท ฮฑฯ€ฯŒ ฯ†ฮฌฮบฮตฮปฮฟ @@ -3658,4 +3682,66 @@ ฮšฮฑฯ„ฮฑฮบฯŒฮบฮบฮนฮฝฮฟ ฯ‡ฮนฯŒฮฝฮน + Soundtrack + ฮœฮฟฯ…ฯƒฮนฮบฮฎ + ฮ•ฯ€ฮนฮปฮฟฮณฮญฯ‚ ฮฑฮฝฮฑฯ€ฮฑฯฮฑฮณฯ‰ฮณฮฎฯ‚ + ฮ‘ฮณฮฑฯ€ฮทฮผฮญฮฝฮฑ + ฮฃฯ…ฮปฮปฮฟฮณฮญฯ‚ + ฮ”ฮตฮฝ ฯ…ฯ€ฮฌฯฯ‡ฮฟฯ…ฮฝ ฯƒฯ…ฮปฮปฮฟฮณฮญฯ‚ ฮฑฮบฯŒฮผฮท. ฮ ฮฑฯ„ฮฎฯƒฯ„ฮต ฯ„ฮฟ ฮตฮนฮบฮฟฮฝฮฏฮดฮนฮฟ ฯƒฮตฮปฮนฮดฮฟฮดฮตฮฏฮบฯ„ฮท ฮณฮนฮฑ ฮฝฮฑ ฮดฮทฮผฮนฮฟฯ…ฯฮณฮฎฯƒฮตฯ„ฮต ฮผฮฏฮฑ. + ฮ‘ฯ€ฮฟฮธฮทฮบฮตฯ…ฮผฮญฮฝฮฑ + ฮ”ฮทฮผฮนฮฟฯ…ฯฮณฮฏฮฑ ฯƒฯ…ฮปฮปฮฟฮณฮฎฯ‚ + ฮŸฯฮณฮฑฮฝฯŽฯƒฯ„ฮต ฯ„ฮฑ ฮฑฯ€ฮฟฮธฮทฮบฮตฯ…ฮผฮญฮฝฮฑ ฯƒฮฑฯ‚ + ฮฮญฮฑ + ฮ”ฮทฮผฮนฮฟฯ…ฯฮณฮฏฮฑ + ฮŒฮฝฮฟฮผฮฑ ฯƒฯ…ฮปฮปฮฟฮณฮฎฯ‚ + ฮ•ฮนฯƒฮฑฮณฮฌฮณฮตฯ„ฮต ฮญฮฝฮฑ ฯŒฮฝฮฟฮผฮฑ ฯ€ฮฟฯ… ฮดฮตฮฝ ฯ‡ฯฮทฯƒฮนฮผฮฟฯ€ฮฟฮนฮตฮฏ ฮฌฮปฮปฮท ฯƒฯ…ฮปฮปฮฟฮณฮฎ + ฮ”ฮนฮฑฯ‡ฮตฮฏฯฮนฯƒฮท + ฮœฮตฯ„ฮฟฮฝฮฟฮผฮฑฯƒฮฏฮฑ + ฮ ฯฮฟฯƒฮธฮฎฮบฮท ฮบฮฟฮผฮผฮฑฯ„ฮนฯŽฮฝ + ฮ ฯฮฟฯƒฮธฮฎฮบฮท (%1$d) + ฮšฮฑฯ„ฮฌฯฮณฮทฯƒฮท ฮบฮฟฮผฮผฮฑฯ„ฮนฯŽฮฝ + ฮ”ฮนฮฑฮณฯฮฑฯ†ฮฎ ฯƒฯ…ฮปฮปฮฟฮณฮฎฯ‚ + ฮ”ฮนฮฑฮณฯฮฑฯ†ฮฎ %1$s; + ฮคฮฑ ฮบฮฟฮผฮผฮฌฯ„ฮนฮฑ ฯ€ฮฑฯฮฑฮผฮญฮฝฮฟฯ…ฮฝ ฯƒฯ„ฮท ฯƒฯ…ฯƒฮบฮตฯ…ฮฎ ฯƒฮฑฯ‚. ฮšฮฑฯ„ฮฑฯฮณฮตฮฏฯ„ฮฑฮน ฮผฯŒฮฝฮฟ ฮท ฯƒฯ…ฮปฮปฮฟฮณฮฎ. + ฮ•ฯ€ฮนฮปฮฟฮณฮฎ + ฮ•ฯ€ฮนฮปฮฟฮณฮฎ ฯŒฮปฯ‰ฮฝ + ฮ‘ฯ€ฮฟฮตฯ€ฮนฮปฮฟฮณฮฎ ฯŒฮปฯ‰ฮฝ + %1$d ฮตฯ€ฮนฮปฮตฮณฮผฮญฮฝฮฑ + ฮ ฯฮฟฯƒฮธฮฎฮบฮท ฯƒฯ„ฮท ฯƒฯ…ฮปฮปฮฟฮณฮฎ + ฮ ฯฮฟฯƒฮธฮฎฮบฮท ฯƒฯ„ฮฑ ฮฑฮณฮฑฯ€ฮทฮผฮญฮฝฮฑ + ฮšฮฑฯ„ฮฌฯฮณฮทฯƒฮท ฮฑฯ€ฯŒ ฯ„ฮท ฯƒฯ…ฮปฮปฮฟฮณฮฎ + ฮ‘ฮฝฮฑฮถฮฎฯ„ฮทฯƒฮท ฮบฮฟฮผฮผฮฑฯ„ฮนฯŽฮฝ + ฮฃฮตฮนฯฮฌ ฮฌฮปฮผฯ€ฮฟฯ…ฮผ + ฮœฮตฮณฮฑฮปฯฯ„ฮตฯฮท ฮดฮนฮฌฯฮบฮตฮนฮฑ ฯ€ฯฯŽฯ„ฮฑ + ฮœฮนฮบฯฯŒฯ„ฮตฯฮท ฮดฮนฮฌฯฮบฮตฮนฮฑ ฯ€ฯฯŽฯ„ฮฑ + ฮšฮฟฮผฮผฮฌฯ„ฮนฮฑ + ฮคฯŒฮฝฮฟฯ‚ + ฮ•ฯ€ฮฑฮฝฮฑฯ†ฮฟฯฮฌ + ฮ ฮฑฯฮฌฮปฮตฮนฯˆฮท ฯƒฮนฯ‰ฯ€ฮฎฯ‚ + ฮงฯฮฟฮฝฮฟฮดฮนฮฑฮบฯŒฯ€ฯ„ฮทฯ‚ ฯฯ€ฮฝฮฟฯ… + %1$d ฮป. + ฮคฮญฮปฮฟฯ‚ ฮบฮฟฮผฮผฮฑฯ„ฮนฮฟฯ + ฮ‘ฯ€ฮฟฮผฮญฮฝฮฟฯ…ฮฝ %1$s + ฮ™ฯƒฮฟฯƒฯ„ฮฑฮธฮผฮนฯƒฯ„ฮฎฯ‚ + ฮ•ฮฝฮฏฯƒฯ‡ฯ…ฯƒฮท ฮผฯ€ฮฌฯƒฯ‰ฮฝ + ฮŸ ฮนฯƒฮฟฯƒฯ„ฮฑฮธฮผฮนฯƒฯ„ฮฎฯ‚ ฮดฮตฮฝ ฮตฮฏฮฝฮฑฮน ฮดฮนฮฑฮธฮญฯƒฮนฮผฮฟฯ‚ ฯƒฮต ฮฑฯ…ฯ„ฮฎ ฯ„ฮท ฯƒฯ…ฯƒฮบฮตฯ…ฮฎ + ฮ•ฮฝฮตฯฮณฮฟฯ€ฮฟฮฏฮทฯƒฮท ฮตฮฝฯ„ฯŒฯ‚ ฯ€ฮฑฮนฯ‡ฮฝฮนฮดฮนฮฟฯ + ฮ— ฮผฮฟฯ…ฯƒฮนฮบฮฎ ฯƒฯ…ฮฝฮตฯ‡ฮฏฮถฮตฮน ฮฝฮฑ ฯ€ฮฑฮฏฮถฮตฮน ฯŒฯƒฮฟ ฮตฮบฯ„ฮตฮปฮตฮฏฯ„ฮฑฮน ฮญฮฝฮฑ ฯ€ฮฑฮนฯ‡ฮฝฮฏฮดฮน + ฮ”ฮตฮฝ ฯ…ฯ€ฮฌฯฯ‡ฮฟฯ…ฮฝ ฮตฮณฮบฮฑฯ„ฮตฯƒฯ„ฮทฮผฮญฮฝฮฑ soundtrack ฮฑฮบฯŒฮผฮท. + ฮ‘ฮฝฮฑฮถฮฎฯ„ฮทฯƒฮท soundtrack + ฮ ฯฮฟฯƒฮธฮฎฮบฮท ฯ†ฮฑฮบฮญฮปฮฟฯ… soundtrack + ฮ”ฮตฮฝ ฯ…ฯ€ฮฌฯฯ‡ฮฟฯ…ฮฝ ฮฑฯฯ‡ฮตฮฏฮฑ ฮฎฯ‡ฮฟฯ… ฯƒฮต ฮฑฯ…ฯ„ฯŒฮฝ ฯ„ฮฟฮฝ ฯ†ฮฌฮบฮตฮปฮฟ + ฮฃฯ…ฮฝฮฟฮปฮนฮบฮฎ ฮดฮนฮฌฯฮบฮตฮนฮฑ + %1$d ฮบฮฟฮผฮผฮฌฯ„ฮนฮฑ / %2$s + ฮ”ฮฏฯƒฮบฮฟฯ‚ %1$s + ฮคฯ…ฯ‡ฮฑฮฏฮฑ ฯƒฮตฮนฯฮฌ + ฮ ฯฮฟฮทฮณฮฟฯฮผฮตฮฝฮฟ + ฮ‘ฮฝฮฑฯ€ฮฑฯฮฑฮณฯ‰ฮณฮฎ + ฮ ฮฑฯฯƒฮท + ฮ•ฯ€ฯŒฮผฮตฮฝฮฟ + ฮ•ฯ€ฮฑฮฝฮฌฮปฮทฯˆฮท ฮฑฮฝฮตฮฝฮตฯฮณฮฎ + ฮ•ฯ€ฮฑฮฝฮฌฮปฮทฯˆฮท ฯŒฮปฯ‰ฮฝ + ฮ•ฯ€ฮฑฮฝฮฌฮปฮทฯˆฮท ฮตฮฝฯŒฯ‚ + ฮˆฮฝฯ„ฮฑฯƒฮท + ฮ”ฮตฮฝ ฯ…ฯ€ฮฌฯฯ‡ฮฟฯ…ฮฝ ฮฑฯฯ‡ฮตฮฏฮฑ ฮฎฯ‡ฮฟฯ… ฯƒฮต ฮฑฯ…ฯ„ฯŒ ฯ„ฮฟ soundtrack diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index 1e7fb4865a..104948fff5 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -28,6 +28,8 @@ Suspender ahora Detener sesiรณn Generaciรณn de fotogramas + Ajustes para este juego + Ajustes predeterminados Elige el modo de generaciรณn de fotogramas Desactivada DD-FG %1$dร— @@ -480,6 +482,7 @@ Activado Se inicia con Steam Se inicia sin Steam + Resoluciรณn del juego Ajustes Ajustes de %1$s Predeterminado @@ -2214,7 +2217,6 @@ Tiendas Steam Personalizados - Tiendas Nivel de velocidad de descarga Equilibrado Rรกpido @@ -2260,6 +2262,7 @@ Interrumpida Instalar ยท %1$s Obtener gratis + Aรฑadiendo a la bibliotecaโ€ฆ Ver en %1$s Comprar ยท %1$s Instalado @@ -2589,7 +2592,9 @@ %1$s ยท reinicio pendiente Este dispositivo ยฟQuitar %1$s? - Diagnรณstico + Desarrollador + Marca de agua de compilaciรณn + Muestra en pantalla la etiqueta de la versiรณn de prueba o Lab. Activada de forma predeterminada. Listo para jugar Aรบn no estรก listo para jugar runtime %1$s @@ -3580,6 +3585,25 @@ Mover despuรฉs Ajustes del widget Quitar widget + Apariencia + Paquete de iconos + Predeterminado del sistema + Fondo con color de la app + Tamaรฑo de iconos + Pequeรฑo + Mediano + Grande + Ocultar nombres de aplicaciones + Espaciado + Denso + Normal + Amplio + Cambiar icono + Restablecer icono + Buscar iconos + Cargando iconosโ€ฆ + No se encontraron iconos. + Iconos personalizados Aรฑadir a carpeta Carpeta nueva Quitar de la carpeta @@ -3697,4 +3721,66 @@ Nieve escarlata + Bandas sonoras + Mรบsica + Opciones de reproducciรณn + Favoritos + Colecciones + Aรบn no hay colecciones. Toca el icono de marcador para crear una. + Guardados + Crear una colecciรณn + Organiza tus guardados + Nueva + Crear + Nombre de la colecciรณn + Introduce un nombre que no use ninguna otra colecciรณn + Gestionar + Cambiar nombre + Aรฑadir pistas + Aรฑadir (%1$d) + Quitar pistas + Eliminar colecciรณn + ยฟEliminar %1$s? + Las pistas permanecen en tu dispositivo. Solo se elimina la colecciรณn. + Seleccionar + Seleccionar todo + Deseleccionar todo + %1$d seleccionadas + Aรฑadir a la colecciรณn + Aรฑadir a favoritos + Quitar de la colecciรณn + Buscar pistas + Orden del รกlbum + Mรกs largas primero + Mรกs cortas primero + Pistas + Tono + Restablecer + Omitir silencios + Temporizador de sueรฑo + %1$d min + Fin de la pista + Quedan %1$s + Ecualizador + Refuerzo de graves + El ecualizador no estรก disponible en este dispositivo + Activar en el juego + Mantรฉn la banda sonora sonando mientras se ejecuta un juego + Aรบn no hay bandas sonoras instaladas. + Buscar bandas sonoras + Aรฑadir una carpeta de banda sonora + No hay archivos de audio en esa carpeta + Duraciรณn total + %1$d pistas / %2$s + Disco %1$s + Aleatorio + Anterior + Reproducir + Pausar + Siguiente + Repeticiรณn desactivada + Repetir todo + Repetir una + Volumen + No hay archivos de audio en esta banda sonora diff --git a/app/src/main/res/values-fi/strings.xml b/app/src/main/res/values-fi/strings.xml index ba86de4422..98ea9d8301 100644 --- a/app/src/main/res/values-fi/strings.xml +++ b/app/src/main/res/values-fi/strings.xml @@ -28,6 +28,8 @@ Keskeytรค nyt Lopeta istunto Kehysten generointi + Tรคmรคn pelin asetukset + Oletusasetukset Valitse kehysten generoinnin tila Pois DD-FG %1$dร— @@ -478,6 +480,7 @@ Pรครคllรค Kรคynnistyy Steamin kanssa Kรคynnistyy ilman Steamia + Pelin resoluutio Asetukset %1$s โ€“ asetukset Oletus @@ -2189,7 +2192,6 @@ Kaupat Steam Mukautettu - Kaupat Latausnopeuden taso Tasapainotettu Nopea @@ -2235,6 +2237,7 @@ Keskeytynyt Asenna ยท %1$s Hanki ilmaiseksi + Lisรคtรครคn kirjastoonโ€ฆ Nรคytรค %1$s:ssรค Osta ยท %1$s Asennettu @@ -2565,7 +2568,9 @@ %1$s ยท vaatii uudelleenkรคynnistyksen Tรคmรค laite Poistetaanko %1$s? - Diagnostiikka + Kehittรคjรค + Koontiversion vesileima + Nรคytรค testi- tai Lab-version tunniste nรคytรถllรค. Kรคytรถssรค oletusarvoisesti. Valmis pelattavaksi Ei vielรค valmis pelattavaksi ajoympรคristรถ %1$s @@ -3542,6 +3547,25 @@ Siirrรค myรถhemmรคksi Widgetin asetukset Poista widget + Ulkoasu + Kuvakepaketti + Jรคrjestelmรคn oletus + Taustavรคri sovelluksesta + Kuvakekoko + Pieni + Keski + Suuri + Piilota sovellusten nimet + Vรคlit + Tiivis + Normaali + Vรคljรค + Vaihda kuvake + Palauta kuvake + Hae kuvakkeita + Ladataan kuvakkeitaโ€ฆ + Kuvakkeita ei lรถytynyt. + Mukautetut kuvakkeet Lisรครค kansioon Uusi kansio Poista kansiosta @@ -3658,4 +3682,66 @@ Helakanpunainen lumi + Soundtrackit + Musiikki + Toistoasetukset + Suosikit + Kokoelmat + Ei vielรค kokoelmia. Luo sellainen napauttamalla kirjanmerkkikuvaketta. + Tallennettu + Luo kokoelma + Jรคrjestรค tallennuksesi + Uusi + Luo + Kokoelman nimi + Anna nimi, jota mikรครคn toinen kokoelma ei kรคytรค + Hallitse + Nimeรค uudelleen + Lisรครค kappaleita + Lisรครค (%1$d) + Poista kappaleita + Poista kokoelma + Poistetaanko %1$s? + Kappaleet sรคilyvรคt laitteellasi. Vain kokoelma poistetaan. + Valitse + Valitse kaikki + Poista kaikkien valinta + %1$d valittu + Lisรครค kokoelmaan + Lisรครค suosikkeihin + Poista kokoelmasta + Hae kappaleita + Albumin jรคrjestys + Pisin ensin + Lyhin ensin + Kappaleet + ร„รคnenkorkeus + Palauta + Ohita hiljaisuus + Uniajastin + %1$d min + Kappaleen loppu + %1$s jรคljellรค + Taajuuskorjain + Bassonkorostus + Taajuuskorjain ei ole kรคytettรคvissรค tรคllรค laitteella + Ota kรคyttรถรถn pelin aikana + Pidรค soundtrack soimassa pelin aikana + Soundtrackeja ei ole vielรค asennettu. + Hae soundtrackeja + Lisรครค soundtrack-kansio + Kansiossa ei ole รครคnitiedostoja + Kokonaiskesto + %1$d kappaletta / %2$s + Levy %1$s + Sekoita + Edellinen + Toista + Tauko + Seuraava + Toisto pois + Toista kaikki + Toista yksi + ร„รคnenvoimakkuus + Tรคssรค soundtrackissa ei ole รครคnitiedostoja diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index 02c4953bfb..e830f0cea4 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -28,6 +28,8 @@ Mettre en pause maintenant Terminer cette session Gรฉnรฉration d\'images + Paramรจtres pour ce jeu + Paramรจtres par dรฉfaut Sรฉlectionnez le mode de gรฉnรฉration d\'images ร  utiliser Dรฉsactivรฉ DD-FG %1$dร— @@ -480,6 +482,7 @@ Activรฉ Dรฉmarre avec Steam Dรฉmarre sans Steam + Rรฉsolution du jeu Paramรจtres Paramรจtres de %1$s Par dรฉfaut @@ -2214,7 +2217,6 @@ Boutiques Steam Personnalisรฉ - Boutiques Niveau de vitesse de tรฉlรฉchargement ร‰quilibrรฉ Rapide @@ -2260,6 +2262,7 @@ Interrompu Installer ยท %1$s Obtenir gratuitement + Ajout ร  la bibliothรจqueโ€ฆ Voir sur %1$s Acheter ยท %1$s Installรฉ @@ -2589,7 +2592,9 @@ %1$s ยท redรฉmarrage en attente Cet appareil Supprimer %1$s ? - Diagnostic + Dรฉveloppeur + Filigrane de version + Afficher le libellรฉ de la version de test ou Lab ร  lโ€™รฉcran. Activรฉ par dรฉfaut. Prรชt ร  jouer Pas encore prรชt ร  jouer environnement d\'exรฉcution %1$s @@ -3580,6 +3585,25 @@ Reculer Paramรจtres du widget Retirer le widget + Apparence + Pack d\'icรดnes + Par dรฉfaut du systรจme + Fond couleur de l\'appli + Taille des icรดnes + Petite + Moyenne + Grande + Masquer les noms des applications + Espacement + Serrรฉ + Normal + Aรฉrรฉ + Changer l\'icรดne + Rรฉinitialiser l\'icรดne + Rechercher des icรดnes + Chargement des icรดnesโ€ฆ + Aucune icรดne trouvรฉe. + Icรดnes personnalisรฉes Ajouter ร  un dossier Nouveau dossier Retirer du dossier @@ -3697,4 +3721,66 @@ Neige รฉcarlate + Bandes originales + Musique + Options de lecture + Favoris + Collections + Aucune collection pour le moment. Touchez l\'icรดne de favori pour en crรฉer une. + Enregistrรฉs + Crรฉer une collection + Organisez vos titres enregistrรฉs + Nouvelle + Crรฉer + Nom de la collection + Saisissez un nom qu\'aucune autre collection n\'utilise + Gรฉrer + Renommer + Ajouter des morceaux + Ajouter (%1$d) + Retirer des morceaux + Supprimer la collection + Supprimer %1$s ? + Les morceaux restent sur votre appareil. Seule la collection est supprimรฉe. + Sรฉlectionner + Tout sรฉlectionner + Tout dรฉsรฉlectionner + %1$d sรฉlectionnรฉ(s) + Ajouter ร  une collection + Ajouter aux favoris + Retirer de la collection + Rechercher des morceaux + Ordre de l\'album + Plus longs d\'abord + Plus courts d\'abord + Morceaux + Hauteur + Rรฉinitialiser + Ignorer les silences + Minuteur de veille + %1$d min + Fin du morceau + %1$s restantes + ร‰galiseur + Renforcement des basses + L\'รฉgaliseur n\'est pas disponible sur cet appareil + Activer en jeu + Garder la bande originale active pendant une partie + Aucune bande originale installรฉe pour le moment. + Rechercher des bandes originales + Ajouter un dossier de bande originale + Aucun fichier audio dans ce dossier + Durรฉe totale + %1$d pistes / %2$s + Disque %1$s + Alรฉatoire + Prรฉcรฉdent + Lecture + Pause + Suivant + Rรฉpรฉtition dรฉsactivรฉe + Tout rรฉpรฉter + Rรฉpรฉter une piste + Volume + Aucun fichier audio dans cette bande originale diff --git a/app/src/main/res/values-hi/strings.xml b/app/src/main/res/values-hi/strings.xml index cdacc2c56d..bb3173d10d 100644 --- a/app/src/main/res/values-hi/strings.xml +++ b/app/src/main/res/values-hi/strings.xml @@ -28,6 +28,8 @@ เค…เคญเฅ€ เคธเคธเฅเคชเฅ‡เค‚เคก เค•เคฐเฅ‡เค‚ เคธเฅ‡เคถเคจ เคฌเค‚เคฆ เค•เคฐเฅ‡เค‚ เคซเคผเฅเคฐเฅ‡เคฎ เคœเคจเคฐเฅ‡เคถเคจ + เค‡เคธ เค—เฅ‡เคฎ เค•เฅ€ เคธเฅ‡เคŸเคฟเค‚เค— + เคกเคฟเคซเคผเฅ‰เคฒเฅเคŸ เคธเฅ‡เคŸเคฟเค‚เค— เคซเคผเฅเคฐเฅ‡เคฎ เคœเคจเคฐเฅ‡เคถเคจ เคฎเฅ‹เคก เคšเฅเคจเฅ‡เค‚ เคฌเค‚เคฆ DD-FG %1$dร— @@ -478,6 +480,7 @@ เคšเคพเคฒเฅ‚ Steam เค•เฅ‡ เคธเคพเคฅ เคถเฅเคฐเฅ‚ เคนเฅ‹เคคเคพ เคนเฅˆ Steam เค•เฅ‡ เคฌเคฟเคจเคพ เคถเฅเคฐเฅ‚ เคนเฅ‹เคคเคพ เคนเฅˆ + เค—เฅ‡เคฎ เคฐเคฟเคœเคผเฅ‰เคฒเฅเคฏเฅ‚เคถเคจ เคธเฅ‡เคŸเคฟเค‚เค— %1$s เคธเฅ‡เคŸเคฟเค‚เค— เคกเคฟเคซเคผเฅ‰เคฒเฅเคŸ @@ -2189,7 +2192,6 @@ เคธเฅเคŸเฅ‹เคฐ Steam เค•เคธเฅเคŸเคฎ - เคธเฅเคŸเฅ‹เคฐ เคกเคพเค‰เคจเคฒเฅ‹เคก เคธเฅเคชเฅ€เคก เคŸเคฟเคฏเคฐ เคฌเฅˆเคฒเฅ‡เค‚เคธเฅเคก เคซเคผเคพเคธเฅเคŸ @@ -2235,6 +2237,7 @@ เคฌเคพเคงเคฟเคค เค‡เค‚เคธเฅเคŸเฅ‰เคฒ ยท %1$s เคฎเฅเคซเคผเฅเคค เคฎเฅ‡เค‚ เคชเคพเคเค‚ + เคฒเคพเค‡เคฌเฅเคฐเฅ‡เคฐเฅ€ เคฎเฅ‡เค‚ เคœเฅ‹เคกเคผเคพ เคœเคพ เคฐเคนเคพ เคนเฅˆโ€ฆ %1$s เคชเคฐ เคฆเฅ‡เค–เฅ‡เค‚ เค–เคฐเฅ€เคฆเฅ‡เค‚ ยท %1$s เค‡เค‚เคธเฅเคŸเฅ‰เคฒ เคนเฅˆ @@ -2565,7 +2568,9 @@ %1$s ยท เคฐเฅ€เคธเฅเคŸเคพเคฐเฅเคŸ เคฌเคพเค•เฅ€ เคฏเคน เคกเคฟเคตเคพเค‡เคธ %1$s เคนเคŸเคพเคเค‚? - เคกเคพเคฏเค—เฅเคจเฅ‹เคธเฅเคŸเคฟเค•เฅเคธ + เคกเฅ‡เคตเคฒเคชเคฐ + เคฌเคฟเคฒเฅเคก เคฒเฅ‡เคฌเคฒ เคตเฅ‰เคŸเคฐเคฎเคพเคฐเฅเค• + เคธเฅเค•เฅเคฐเฅ€เคจ เคชเคฐ เคŸเฅ‡เคธเฅเคŸ เคฏเคพ Lab เคฌเคฟเคฒเฅเคก เคฒเฅ‡เคฌเคฒ เคฆเคฟเค–เคพเคเคเฅค เคกเคฟเคซเคผเฅ‰เคฒเฅเคŸ เคฐเฅ‚เคช เคธเฅ‡ เคšเคพเคฒเฅ‚เฅค เค–เฅ‡เคฒเคจเฅ‡ เค•เฅ‡ เคฒเคฟเค เคคเฅˆเคฏเคพเคฐ เค…เคญเฅ€ เค–เฅ‡เคฒเคจเฅ‡ เค•เฅ‡ เคฒเคฟเค เคคเฅˆเคฏเคพเคฐ เคจเคนเฅ€เค‚ เคฐเคจเคŸเคพเค‡เคฎ %1$s @@ -3542,6 +3547,25 @@ เคฌเคพเคฆ เคฎเฅ‡เค‚ เคฒเฅ‡ เคœเคพเคเค เคตเคฟเคœเฅ‡เคŸ เคธเฅ‡เคŸเคฟเค‚เค— เคตเคฟเคœเฅ‡เคŸ เคนเคŸเคพเคเค + เคฆเคฟเค–เคพเคตเคŸ + เค†เค‡เค•เคจ เคชเฅˆเค• + เคธเคฟเคธเฅเคŸเคฎ เคกเคฟเคซเคผเฅ‰เคฒเฅเคŸ + เคเคช เค•เฅ‡ เคฐเค‚เค— เค•เคพ เคฌเฅˆเค•เค—เฅเคฐเคพเค‰เค‚เคก + เค†เค‡เค•เคจ เค•เคพ เค†เค•เคพเคฐ + เค›เฅ‹เคŸเคพ + เคฎเคงเฅเคฏเคฎ + เคฌเคกเคผเคพ + เคเคช เค•เฅ‡ เคจเคพเคฎ เค›เคฟเคชเคพเคเค‚ + เคธเฅเคชเฅ‡เคธเคฟเค‚เค— + เค•เคฎ + เคธเคพเคฎเคพเคจเฅเคฏ + เคœเคผเฅเคฏเคพเคฆเคพ + เค†เค‡เค•เคจ เคฌเคฆเคฒเฅ‡เค‚ + เค†เค‡เค•เคจ เคฐเฅ€เคธเฅ‡เคŸ เค•เคฐเฅ‡เค‚ + เค†เค‡เค•เคจ เค–เฅ‹เคœเฅ‡เค‚ + เค†เค‡เค•เคจ เคฒเฅ‹เคก เคนเฅ‹ เคฐเคนเฅ‡ เคนเฅˆเค‚โ€ฆ + เค•เฅ‹เคˆ เค†เค‡เค•เคจ เคจเคนเฅ€เค‚ เคฎเคฟเคฒเคพเฅค + เค•เคธเฅเคŸเคฎ เค†เค‡เค•เคจ เคซเคผเฅ‹เคฒเฅเคกเคฐ เคฎเฅ‡เค‚ เคœเฅ‹เคกเคผเฅ‡เค‚ เคจเคฏเคพ เคซเคผเฅ‹เคฒเฅเคกเคฐ เคซเคผเฅ‹เคฒเฅเคกเคฐ เคธเฅ‡ เคนเคŸเคพเคเค @@ -3658,4 +3682,66 @@ เค•เคฟเคฐเคฎเคฟเคœเคผเฅ€ เคฌเคฐเฅเคซ + เคธเคพเค‰เค‚เคกเคŸเฅเคฐเฅˆเค• + เคธเค‚เค—เฅ€เคค + เคชเฅเคฒเฅ‡เคฌเฅˆเค• เคตเคฟเค•เคฒเฅเคช + เคชเคธเค‚เคฆเฅ€เคฆเคพ + เค•เคฒเฅ‡เค•เฅเคถเคจ + เค…เคญเฅ€ เคคเค• เค•เฅ‹เคˆ เค•เคฒเฅ‡เค•เฅเคถเคจ เคจเคนเฅ€เค‚ เคนเฅˆเฅค เคฌเคจเคพเคจเฅ‡ เค•เฅ‡ เคฒเคฟเค เคฌเฅเค•เคฎเคพเคฐเฅเค• เค†เค‡เค•เคจ เคชเคฐ เคŸเฅˆเคช เค•เคฐเฅ‡เค‚เฅค + เคธเคนเฅ‡เคœเฅ‡ เค—เค + เค•เคฒเฅ‡เค•เฅเคถเคจ เคฌเคจเคพเคเค‚ + เค…เคชเคจเฅ‡ เคธเฅ‡เคต เคตเฅเคฏเคตเคธเฅเคฅเคฟเคค เค•เคฐเฅ‡เค‚ + เคจเคฏเคพ + เคฌเคจเคพเคเค‚ + เค•เคฒเฅ‡เค•เฅเคถเคจ เค•เคพ เคจเคพเคฎ + เคเคธเคพ เคจเคพเคฎ เคฆเคฐเฅเคœ เค•เคฐเฅ‡เค‚ เคœเฅ‹ เค•เคฟเคธเฅ€ เค…เคจเฅเคฏ เค•เคฒเฅ‡เค•เฅเคถเคจ เคฎเฅ‡เค‚ เค‰เคชเคฏเฅ‹เค— เคจ เคนเฅเค† เคนเฅ‹ + เคชเฅเคฐเคฌเค‚เคงเคฟเคค เค•เคฐเฅ‡เค‚ + เคจเคพเคฎ เคฌเคฆเคฒเฅ‡เค‚ + เคŸเฅเคฐเฅˆเค• เคœเฅ‹เคกเคผเฅ‡เค‚ + เคœเฅ‹เคกเคผเฅ‡เค‚ (%1$d) + เคŸเฅเคฐเฅˆเค• เคนเคŸเคพเคเค‚ + เค•เคฒเฅ‡เค•เฅเคถเคจ เคนเคŸเคพเคเค‚ + %1$s เคนเคŸเคพเคเค‚? + เคŸเฅเคฐเฅˆเค• เค†เคชเค•เฅ‡ เคกเคฟเคตเคพเค‡เคธ เคชเคฐ เคฐเคนเฅ‡เค‚เค—เฅ‡เฅค เค•เฅ‡เคตเคฒ เค•เคฒเฅ‡เค•เฅเคถเคจ เคนเคŸเคพเคฏเคพ เคœเคพเคเค—เคพเฅค + เคšเฅเคจเฅ‡เค‚ + เคธเคญเฅ€ เคšเฅเคจเฅ‡เค‚ + เคธเคญเฅ€ เคšเคฏเคจ เคนเคŸเคพเคเค‚ + %1$d เคšเฅเคจเฅ‡ เค—เค + เค•เคฒเฅ‡เค•เฅเคถเคจ เคฎเฅ‡เค‚ เคœเฅ‹เคกเคผเฅ‡เค‚ + เคชเคธเค‚เคฆเฅ€เคฆเคพ เคฎเฅ‡เค‚ เคœเฅ‹เคกเคผเฅ‡เค‚ + เค•เคฒเฅ‡เค•เฅเคถเคจ เคธเฅ‡ เคนเคŸเคพเคเค‚ + เคŸเฅเคฐเฅˆเค• เค–เฅ‹เคœเฅ‡เค‚ + เคเคฒเฅเคฌเคฎ เค•เฅเคฐเคฎ + เคธเคฌเคธเฅ‡ เคฒเค‚เคฌเฅ‡ เคชเคนเคฒเฅ‡ + เคธเคฌเคธเฅ‡ เค›เฅ‹เคŸเฅ‡ เคชเคนเคฒเฅ‡ + เคŸเฅเคฐเฅˆเค• + เคชเคฟเคš + เคฐเฅ€เคธเฅ‡เคŸ เค•เคฐเฅ‡เค‚ + เคฎเฅŒเคจ เค›เฅ‹เคกเคผเฅ‡เค‚ + เคธเฅเคฒเฅ€เคช เคŸเคพเค‡เคฎเคฐ + %1$d เคฎเคฟเคจเคŸ + เคŸเฅเคฐเฅˆเค• เค•เคพ เค…เค‚เคค + %1$s เคถเฅ‡เคท + เค‡เค•เฅเคตเคฒเคพเค‡เคœเคผเคฐ + เคฌเคพเคธ เคฌเฅ‚เคธเฅเคŸ + เค‡เคธ เคกเคฟเคตเคพเค‡เคธ เคชเคฐ เค‡เค•เฅเคตเคฒเคพเค‡เคœเคผเคฐ เค‰เคชเคฒเคฌเฅเคง เคจเคนเฅ€เค‚ เคนเฅˆ + เค—เฅ‡เคฎ เค•เฅ‡ เคฆเฅŒเคฐเคพเคจ เคšเคพเคฒเฅ‚ เค•เคฐเฅ‡เค‚ + เค—เฅ‡เคฎ เคšเคฒเคคเฅ‡ เคธเคฎเคฏ เคธเคพเค‰เค‚เคกเคŸเฅเคฐเฅˆเค• เคฌเคœเคคเคพ เคฐเค–เฅ‡เค‚ + เค…เคญเฅ€ เคคเค• เค•เฅ‹เคˆ เคธเคพเค‰เค‚เคกเคŸเฅเคฐเฅˆเค• เค‡เค‚เคธเฅเคŸเฅ‰เคฒ เคจเคนเฅ€เค‚ เคนเฅˆเฅค + เคธเคพเค‰เค‚เคกเคŸเฅเคฐเฅˆเค• เค–เฅ‹เคœเฅ‡เค‚ + เคธเคพเค‰เค‚เคกเคŸเฅเคฐเฅˆเค• เคซเคผเฅ‹เคฒเฅเคกเคฐ เคœเฅ‹เคกเคผเฅ‡เค‚ + เค‰เคธ เคซเคผเฅ‹เคฒเฅเคกเคฐ เคฎเฅ‡เค‚ เค•เฅ‹เคˆ เค‘เคกเคฟเคฏเฅ‹ เคซเคผเคพเค‡เคฒ เคจเคนเฅ€เค‚ เคนเฅˆ + เค•เฅเคฒ เค…เคตเคงเคฟ + %1$d เคŸเฅเคฐเฅˆเค• / %2$s + เคกเคฟเคธเฅเค• %1$s + เคถเคซเคผเคฒ + เคชเคฟเค›เคฒเคพ + เคšเคฒเคพเคเค + เคฐเฅ‹เค•เฅ‡เค‚ + เค…เค—เคฒเคพ + เคฐเคฟเคชเฅ€เคŸ เคฌเค‚เคฆ + เคธเคญเฅ€ เคฆเฅ‹เคนเคฐเคพเคเค + เคเค• เคฆเฅ‹เคนเคฐเคพเคเค + เคตเฅ‰เคฒเฅเคฏเฅ‚เคฎ + เค‡เคธ เคธเคพเค‰เค‚เคกเคŸเฅเคฐเฅˆเค• เคฎเฅ‡เค‚ เค•เฅ‹เคˆ เค‘เคกเคฟเคฏเฅ‹ เคซเคผเคพเค‡เคฒ เคจเคนเฅ€เค‚ เคนเฅˆ diff --git a/app/src/main/res/values-hu/strings.xml b/app/src/main/res/values-hu/strings.xml index 3743a26364..7ecc8c8e57 100644 --- a/app/src/main/res/values-hu/strings.xml +++ b/app/src/main/res/values-hu/strings.xml @@ -28,6 +28,8 @@ Felfรผggesztรฉs most Munkamenet leรกllรญtรกsa Kรฉpkocka-generรกlรกs + A jรกtรฉk beรกllรญtรกsai + Alapรฉrtelmezett beรกllรญtรกsok Vรกlassza ki a kรฉpkocka-generรกlรกs mรณdjรกt Ki DD-FG %1$dร— @@ -478,6 +480,7 @@ Be Steammel indul Steam nรฉlkรผl indul + Jรกtรฉk felbontรกsa Beรกllรญtรกsok %1$s beรกllรญtรกsai Alapรฉrtelmezett @@ -2189,7 +2192,6 @@ รruhรกzak Steam Egyรฉni - รruhรกzak Letรถltรฉsi sebessรฉgi szint Kiegyensรบlyozott Gyors @@ -2235,6 +2237,7 @@ Megszakรญtva Telepรญtรฉs ยท %1$s Ingyenes beszerzรฉs + Hozzรกadรกs a kรถnyvtรกrhozโ€ฆ Megtekintรฉs itt: %1$s Megvรฉtel ยท %1$s Telepรญtve @@ -2565,7 +2568,9 @@ %1$s ยท รบjraindรญtรกs szรผksรฉges Ez a kรฉszรผlรฉk Eltรกvolรญtja a %1$s-t? - Diagnosztika + Fejlesztล‘ + Buildcรญmke vรญzjelkรฉnt + A tesztbuild vagy Lab-build cรญmkรฉjรฉnek megjelenรญtรฉse a kรฉpernyล‘n. Alapรฉrtelmezรฉs szerint bekapcsolva. Kรฉszen รกll a jรกtรฉkra Mรฉg nem รกll kรฉszen a jรกtรฉkra futtatรณkรถrnyezet: %1$s @@ -3542,6 +3547,25 @@ Hรกtrรฉbb Modulbeรกllรญtรกsok Modul eltรกvolรญtรกsa + Megjelenรฉs + Ikoncsomag + Rendszer alapรฉrtelmezett + Hรกttรฉr az alkalmazรกs szรญnรฉvel + Ikonmรฉret + Kicsi + Kรถzepes + Nagy + Alkalmazรกsnevek elrejtรฉse + Tรฉrkรถz + Szลฑk + Normรกl + Tรกg + Ikon mรณdosรญtรกsa + Ikon visszaรกllรญtรกsa + Ikonok keresรฉse + Ikonok betรถltรฉseโ€ฆ + Nem talรกlhatรณ ikon. + Egyรฉni ikonok Hozzรกadรกs mappรกhoz รšj mappa Eltรกvolรญtรกs a mappรกbรณl @@ -3658,4 +3682,66 @@ Skarlรกtvรถrรถs hรณ + Soundtrackek + Zene + Lejรกtszรกsi beรกllรญtรกsok + Kedvencek + Gyลฑjtemรฉnyek + Mรฉg nincs gyลฑjtemรฉny. Koppints a kรถnyvjelzล‘ ikonra egy lรฉtrehozรกsรกhoz. + Mentve + Gyลฑjtemรฉny lรฉtrehozรกsa + Rendezd a mentรฉseidet + รšj + Lรฉtrehozรกs + Gyลฑjtemรฉny neve + Adj meg egy nevet, amelyet mรกs gyลฑjtemรฉny nem hasznรกl + Kezelรฉs + รtnevezรฉs + Szรกmok hozzรกadรกsa + Hozzรกadรกs (%1$d) + Szรกmok eltรกvolรญtรกsa + Gyลฑjtemรฉny tรถrlรฉse + Tรถrlรถd ezt: %1$s? + A szรกmok az eszkรถzรถdรถn maradnak. Csak a gyลฑjtemรฉny tรถrlล‘dik. + Kijelรถlรฉs + ร–sszes kijelรถlรฉse + Kijelรถlรฉs tรถrlรฉse + %1$d kijelรถlve + Hozzรกadรกs gyลฑjtemรฉnyhez + Hozzรกadรกs a kedvencekhez + Eltรกvolรญtรกs a gyลฑjtemรฉnybล‘l + Szรกmok keresรฉse + Albumsorrend + Leghosszabb elรถl + Legrรถvidebb elรถl + Szรกmok + Hangmagassรกg + Visszaรกllรญtรกs + Csend รกtugrรกsa + Alvรกsidล‘zรญtล‘ + %1$d perc + Szรกm vรฉge + %1$s van hรกtra + Hangszรญnszabรกlyzรณ + Mรฉlyhangerล‘sรญtรฉs + A hangszรญnszabรกlyzรณ nem รฉrhetล‘ el ezen az eszkรถzรถn + Engedรฉlyezรฉs jรกtรฉk kรถzben + A soundtrack szรณljon tovรกbb jรกtรฉk kรถzben + Mรฉg nincs telepรญtett soundtrack. + Soundtrackek keresรฉse + Soundtrack mappa hozzรกadรกsa + Nincs hangfรกjl ebben a mappรกban + Teljes hossz + %1$d szรกm / %2$s + %1$s. lemez + Keverรฉs + Elล‘zล‘ + Lejรกtszรกs + Szรผnet + Kรถvetkezล‘ + Ismรฉtlรฉs kikapcsolva + ร–sszes ismรฉtlรฉse + Egy ismรฉtlรฉse + Hangerล‘ + Nincs hangfรกjl ebben a soundtrackben diff --git a/app/src/main/res/values-in/strings.xml b/app/src/main/res/values-in/strings.xml index 395b199251..6a0a20ea14 100644 --- a/app/src/main/res/values-in/strings.xml +++ b/app/src/main/res/values-in/strings.xml @@ -28,6 +28,8 @@ Jeda sekarang Hentikan sesi Pembuatan frame + Pengaturan untuk game ini + Pengaturan bawaan Pilih mode pembuatan frame Nonaktif DD-FG %1$dร— @@ -476,6 +478,7 @@ Aktif Dimulai dengan Steam Dimulai tanpa Steam + Resolusi game Setelan Setelan %1$s Default @@ -2164,7 +2167,6 @@ Toko Steam Khusus - Toko Tingkat kecepatan unduhan Seimbang Cepat @@ -2210,6 +2212,7 @@ Terhenti Instal ยท %1$s Dapatkan gratis + Menambahkan ke pustakaโ€ฆ Lihat di %1$s Beli ยท %1$s Terinstal @@ -2538,7 +2541,9 @@ %1$s ยท perlu mulai ulang Perangkat ini Hapus %1$s? - Diagnostik + Developer + Tanda air label build + Tampilkan label build pengujian atau Lab di layar. Aktif secara default. Siap bermain Belum siap bermain runtime %1$s @@ -3513,6 +3518,25 @@ Pindahkan ke belakang Setelan widget Hapus widget + Tampilan + Paket ikon + Default sistem + Latar warna aplikasi + Ukuran ikon + Kecil + Sedang + Besar + Sembunyikan nama aplikasi + Jarak + Rapat + Normal + Longgar + Ubah ikon + Setel ulang ikon + Cari ikon + Memuat ikonโ€ฆ + Ikon tidak ditemukan. + Ikon khusus Tambahkan ke folder Folder baru Keluarkan dari folder @@ -3628,4 +3652,66 @@ Salju Kirmizi + Soundtrack + Musik + Opsi pemutaran + Favorit + Koleksi + Belum ada koleksi. Ketuk ikon penanda untuk membuatnya. + Tersimpan + Buat koleksi + Atur simpananmu + Baru + Buat + Nama koleksi + Masukkan nama yang tidak dipakai koleksi lain + Kelola + Ganti nama + Tambah lagu + Tambah (%1$d) + Hapus lagu + Hapus koleksi + Hapus %1$s? + Lagu tetap ada di perangkatmu. Hanya koleksinya yang dihapus. + Pilih + Pilih semua + Batalkan semua pilihan + %1$d dipilih + Tambahkan ke koleksi + Tambahkan ke favorit + Hapus dari koleksi + Cari lagu + Urutan album + Terpanjang dulu + Terpendek dulu + Lagu + Nada + Atur ulang + Lewati keheningan + Timer tidur + %1$d mnt + Akhir lagu + Sisa %1$s + Ekualiser + Penguat bass + Ekualiser tidak tersedia di perangkat ini + Aktifkan saat bermain + Tetap putar soundtrack saat game berjalan + Belum ada soundtrack yang terpasang. + Cari soundtrack + Tambahkan folder soundtrack + Tidak ada file audio di folder itu + Total durasi + %1$d trek / %2$s + Disk %1$s + Acak + Sebelumnya + Putar + Jeda + Berikutnya + Ulangi mati + Ulangi semua + Ulangi satu + Volume + Tidak ada file audio di soundtrack ini diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index 9d7e3392bf..792b2c47a1 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -28,6 +28,8 @@ Sospendi ora Termina sessione Generazione di frame + Impostazioni per questo gioco + Impostazioni predefinite Seleziona la modalitร  di generazione di frame Disattivata DD-FG %1$dร— @@ -480,6 +482,7 @@ Attivo Si avvia con Steam Si avvia senza Steam + Risoluzione del gioco Impostazioni Impostazioni di %1$s Predefinito @@ -2206,7 +2209,6 @@ Negozi Steam Personalizzati - Negozi Livello di velocitร  di download Bilanciato Veloce @@ -2252,6 +2254,7 @@ Interrotto Installa ยท %1$s Ottieni gratis + Aggiunta alla libreriaโ€ฆ Visualizza su %1$s Acquista ยท %1$s Installato @@ -2581,7 +2584,9 @@ %1$s ยท riavvio in attesa Questo dispositivo Rimuovere %1$s? - Diagnostica + Sviluppatore + Filigrana con etichetta build + Mostra sullo schermo lโ€™etichetta della build di test o Lab. Attiva per impostazione predefinita. Pronto per giocare Non ancora pronto per giocare runtime %1$s @@ -3580,6 +3585,25 @@ Sposta dopo Impostazioni widget Rimuovi widget + Aspetto + Pacchetto icone + Predefinito di sistema + Sfondo col colore dell\'app + Dimensione icone + Piccole + Medie + Grandi + Nascondi nomi delle app + Spaziatura + Stretta + Normale + Ampia + Cambia icona + Ripristina icona + Cerca icone + Caricamento iconeโ€ฆ + Nessuna icona trovata. + Icone personalizzate Aggiungi a cartella Nuova cartella Rimuovi dalla cartella @@ -3697,4 +3721,66 @@ Neve scarlatta + Colonne sonore + Musica + Opzioni di riproduzione + Preferiti + Raccolte + Nessuna raccolta per ora. Tocca l\'icona del segnalibro per crearne una. + Salvati + Crea una raccolta + Organizza i tuoi salvataggi + Nuova + Crea + Nome della raccolta + Inserisci un nome non usato da altre raccolte + Gestisci + Rinomina + Aggiungi brani + Aggiungi (%1$d) + Rimuovi brani + Elimina raccolta + Eliminare %1$s? + I brani restano sul dispositivo. Viene rimossa solo la raccolta. + Seleziona + Seleziona tutto + Deseleziona tutto + %1$d selezionati + Aggiungi alla raccolta + Aggiungi ai preferiti + Rimuovi dalla raccolta + Cerca brani + Ordine dell\'album + Piรน lunghi prima + Piรน brevi prima + Brani + Tonalitร  + Reimposta + Salta i silenzi + Timer di spegnimento + %1$d min + Fine del brano + Restano %1$s + Equalizzatore + Potenziamento bassi + L\'equalizzatore non รจ disponibile su questo dispositivo + Attiva in gioco + Mantieni la colonna sonora in riproduzione durante una partita + Nessuna colonna sonora installata. + Cerca colonne sonore + Aggiungi una cartella di colonna sonora + Nessun file audio in questa cartella + Durata totale + %1$d brani / %2$s + Disco %1$s + Casuale + Precedente + Riproduci + Pausa + Successivo + Ripetizione disattivata + Ripeti tutto + Ripeti uno + Volume + Nessun file audio in questa colonna sonora diff --git a/app/src/main/res/values-ja/strings.xml b/app/src/main/res/values-ja/strings.xml index 2be588f1c8..459c1d805f 100644 --- a/app/src/main/res/values-ja/strings.xml +++ b/app/src/main/res/values-ja/strings.xml @@ -28,6 +28,8 @@ ไปŠใ™ใไธ€ๆ™‚ๅœๆญข ใ‚ปใƒƒใ‚ทใƒงใƒณใ‚’็ต‚ไบ† ใƒ•ใƒฌใƒผใƒ ็”Ÿๆˆ + ใ“ใฎใ‚ฒใƒผใƒ ใฎ่จญๅฎš + ใƒ‡ใƒ•ใ‚ฉใƒซใƒˆ่จญๅฎš ไฝฟ็”จใ™ใ‚‹ใƒ•ใƒฌใƒผใƒ ็”Ÿๆˆใƒขใƒผใƒ‰ใ‚’้ธๆŠžใ—ใฆใใ ใ•ใ„ ใ‚ชใƒ• DD-FG %1$dร— @@ -476,6 +478,7 @@ ใ‚ชใƒณ Steam ใจไธ€็ท’ใซ่ตทๅ‹• Steam ใชใ—ใง่ตทๅ‹• + ใ‚ฒใƒผใƒ ใฎ่งฃๅƒๅบฆ ่จญๅฎš %1$s ใฎ่จญๅฎš ใƒ‡ใƒ•ใ‚ฉใƒซใƒˆ @@ -2164,7 +2167,6 @@ ใ‚นใƒˆใ‚ข Steam ใ‚ซใ‚นใ‚ฟใƒ  - ใ‚นใƒˆใ‚ข ใƒ€ใ‚ฆใƒณใƒญใƒผใƒ‰้€Ÿๅบฆใƒฌใƒ™ใƒซ ใƒใƒฉใƒณใ‚น ้ซ˜้€Ÿ @@ -2210,6 +2212,7 @@ ไธญๆ–ญ ใ‚คใƒณใ‚นใƒˆใƒผใƒซ ยท %1$s ็„กๆ–™ใงๅ…ฅๆ‰‹ + ใƒฉใ‚คใƒ–ใƒฉใƒชใซ่ฟฝๅŠ ไธญโ€ฆ %1$sใง่ฆ‹ใ‚‹ ่ณผๅ…ฅ ยท %1$s ใ‚คใƒณใ‚นใƒˆใƒผใƒซๆธˆใฟ @@ -2538,7 +2541,9 @@ %1$s ยท ๅ†่ตทๅ‹•ๅพ…ใก ใ“ใฎใƒ‡ใƒใ‚คใ‚น %1$sใ‚’ๅ‰Š้™คใ—ใพใ™ใ‹๏ผŸ - ่จบๆ–ญ + ้–‹็™บ่€… + ใƒ“ใƒซใƒ‰ใƒฉใƒ™ใƒซใฎ้€ใ‹ใ— + ใƒ†ใ‚นใƒˆใƒ“ใƒซใƒ‰ใพใŸใฏLabใƒ“ใƒซใƒ‰ใฎใƒฉใƒ™ใƒซใ‚’็”ป้ขใซ่กจ็คบใ—ใพใ™ใ€‚ใƒ‡ใƒ•ใ‚ฉใƒซใƒˆใงๆœ‰ๅŠนใงใ™ใ€‚ ใƒ—ใƒฌใ‚คใฎๆบ–ๅ‚™ๅฎŒไบ† ใพใ ใƒ—ใƒฌใ‚คใฎๆบ–ๅ‚™ใŒใงใใฆใ„ใพใ›ใ‚“ ๅฎŸ่กŒ็’ฐๅขƒ %1$s @@ -3513,6 +3518,25 @@ ๅพŒใ‚ใธ็งปๅ‹• ใ‚ฆใ‚ฃใ‚ธใ‚งใƒƒใƒˆใฎ่จญๅฎš ใ‚ฆใ‚ฃใ‚ธใ‚งใƒƒใƒˆใ‚’ๅ‰Š้™ค + ๅค–่ฆณ + ใ‚ขใ‚คใ‚ณใƒณใƒ‘ใƒƒใ‚ฏ + ใ‚ทใ‚นใƒ†ใƒ ใฎใƒ‡ใƒ•ใ‚ฉใƒซใƒˆ + ใ‚ขใƒ—ใƒชใฎ่‰ฒใ‚’่ƒŒๆ™ฏใซไฝฟ็”จ + ใ‚ขใ‚คใ‚ณใƒณใ‚ตใ‚คใ‚บ + ๅฐ + ไธญ + ๅคง + ใ‚ขใƒ—ใƒชๅใ‚’้ž่กจ็คบ + ้–“้š” + ็‹ญใ„ + ๆจ™ๆบ– + ๅบƒใ„ + ใ‚ขใ‚คใ‚ณใƒณใ‚’ๅค‰ๆ›ด + ใ‚ขใ‚คใ‚ณใƒณใ‚’ใƒชใ‚ปใƒƒใƒˆ + ใ‚ขใ‚คใ‚ณใƒณใ‚’ๆคœ็ดข + ใ‚ขใ‚คใ‚ณใƒณใ‚’่ชญใฟ่พผใฟไธญโ€ฆ + ใ‚ขใ‚คใ‚ณใƒณใŒ่ฆ‹ใคใ‹ใ‚Šใพใ›ใ‚“ใ€‚ + ใ‚ซใ‚นใ‚ฟใƒ ใ‚ขใ‚คใ‚ณใƒณ ใƒ•ใ‚ฉใƒซใƒ€ใซ่ฟฝๅŠ  ๆ–ฐใ—ใ„ใƒ•ใ‚ฉใƒซใƒ€ ใƒ•ใ‚ฉใƒซใƒ€ใ‹ใ‚‰ๅ‰Š้™ค @@ -3628,4 +3652,66 @@ ็ท‹่‰ฒใฎ้›ช + ใ‚ตใ‚ฆใƒณใƒ‰ใƒˆใƒฉใƒƒใ‚ฏ + ้Ÿณๆฅฝ + ๅ†็”Ÿใ‚ชใƒ—ใ‚ทใƒงใƒณ + ใŠๆฐ—ใซๅ…ฅใ‚Š + ใ‚ณใƒฌใ‚ฏใ‚ทใƒงใƒณ + ใ‚ณใƒฌใ‚ฏใ‚ทใƒงใƒณใฏใพใ ใ‚ใ‚Šใพใ›ใ‚“ใ€‚ใƒ–ใƒƒใ‚ฏใƒžใƒผใ‚ฏใ‚ขใ‚คใ‚ณใƒณใ‚’ใ‚ฟใƒƒใƒ—ใ—ใฆไฝœๆˆใงใใพใ™ใ€‚ + ไฟๅญ˜ๆธˆใฟ + ใ‚ณใƒฌใ‚ฏใ‚ทใƒงใƒณใ‚’ไฝœๆˆ + ไฟๅญ˜ใ—ใŸๆ›ฒใ‚’ๆ•ด็† + ๆ–ฐ่ฆ + ไฝœๆˆ + ใ‚ณใƒฌใ‚ฏใ‚ทใƒงใƒณๅ + ไป–ใฎใ‚ณใƒฌใ‚ฏใ‚ทใƒงใƒณใงไฝฟใ‚ใ‚Œใฆใ„ใชใ„ๅๅ‰ใ‚’ๅ…ฅๅŠ›ใ—ใฆใใ ใ•ใ„ + ็ฎก็† + ๅๅ‰ใ‚’ๅค‰ๆ›ด + ใƒˆใƒฉใƒƒใ‚ฏใ‚’่ฟฝๅŠ  + ่ฟฝๅŠ (%1$d) + ใƒˆใƒฉใƒƒใ‚ฏใ‚’ๅ‰Š้™ค + ใ‚ณใƒฌใ‚ฏใ‚ทใƒงใƒณใ‚’ๅ‰Š้™ค + %1$sใ‚’ๅ‰Š้™คใ—ใพใ™ใ‹? + ใƒˆใƒฉใƒƒใ‚ฏใฏใƒ‡ใƒใ‚คใ‚นใซๆฎ‹ใ‚Šใพใ™ใ€‚ใ‚ณใƒฌใ‚ฏใ‚ทใƒงใƒณใฎใฟใŒๅ‰Š้™คใ•ใ‚Œใพใ™ใ€‚ + ้ธๆŠž + ใ™ในใฆ้ธๆŠž + ใ™ในใฆ้ธๆŠž่งฃ้™ค + %1$dไปถ้ธๆŠžไธญ + ใ‚ณใƒฌใ‚ฏใ‚ทใƒงใƒณใซ่ฟฝๅŠ  + ใŠๆฐ—ใซๅ…ฅใ‚Šใซ่ฟฝๅŠ  + ใ‚ณใƒฌใ‚ฏใ‚ทใƒงใƒณใ‹ใ‚‰ๅ‰Š้™ค + ใƒˆใƒฉใƒƒใ‚ฏใ‚’ๆคœ็ดข + ใ‚ขใƒซใƒใƒ ้ † + ้•ทใ„้ † + ็Ÿญใ„้ † + ใƒˆใƒฉใƒƒใ‚ฏ + ใƒ”ใƒƒใƒ + ใƒชใ‚ปใƒƒใƒˆ + ็„ก้Ÿณ้ƒจๅˆ†ใ‚’ใ‚นใ‚ญใƒƒใƒ— + ใ‚นใƒชใƒผใƒ—ใ‚ฟใ‚คใƒžใƒผ + %1$dๅˆ† + ใƒˆใƒฉใƒƒใ‚ฏใฎ็ต‚ใ‚ใ‚Š + ๆฎ‹ใ‚Š %1$s + ใ‚คใ‚ณใƒฉใ‚คใ‚ถใƒผ + ไฝŽ้Ÿณใƒ–ใƒผใ‚นใƒˆ + ใ“ใฎใƒ‡ใƒใ‚คใ‚นใงใฏใ‚คใ‚ณใƒฉใ‚คใ‚ถใƒผใ‚’ไฝฟ็”จใงใใพใ›ใ‚“ + ใ‚ฒใƒผใƒ ไธญใ‚‚ๆœ‰ๅŠนใซใ™ใ‚‹ + ใ‚ฒใƒผใƒ ๅฎŸ่กŒไธญใ‚‚ใ‚ตใ‚ฆใƒณใƒ‰ใƒˆใƒฉใƒƒใ‚ฏใ‚’ๅ†็”Ÿใ—็ถšใ‘ใพใ™ + ใ‚คใƒณใ‚นใƒˆใƒผใƒซๆธˆใฟใฎใ‚ตใ‚ฆใƒณใƒ‰ใƒˆใƒฉใƒƒใ‚ฏใฏใพใ ใ‚ใ‚Šใพใ›ใ‚“ใ€‚ + ใ‚ตใ‚ฆใƒณใƒ‰ใƒˆใƒฉใƒƒใ‚ฏใ‚’ๆคœ็ดข + ใ‚ตใ‚ฆใƒณใƒ‰ใƒˆใƒฉใƒƒใ‚ฏใฎใƒ•ใ‚ฉใƒซใƒ€ใƒผใ‚’่ฟฝๅŠ  + ใใฎใƒ•ใ‚ฉใƒซใƒ€ใƒผใซ้Ÿณๅฃฐใƒ•ใ‚กใ‚คใƒซใŒใ‚ใ‚Šใพใ›ใ‚“ + ๅˆ่จˆๆ™‚้–“ + %1$d ใƒˆใƒฉใƒƒใ‚ฏ / %2$s + ใƒ‡ใ‚ฃใ‚นใ‚ฏ %1$s + ใ‚ทใƒฃใƒƒใƒ•ใƒซ + ๅ‰ใธ + ๅ†็”Ÿ + ไธ€ๆ™‚ๅœๆญข + ๆฌกใธ + ใƒชใƒ”ใƒผใƒˆใชใ— + ๅ…จๆ›ฒใƒชใƒ”ใƒผใƒˆ + 1ๆ›ฒใƒชใƒ”ใƒผใƒˆ + ้Ÿณ้‡ + ใ“ใฎใ‚ตใ‚ฆใƒณใƒ‰ใƒˆใƒฉใƒƒใ‚ฏใซ้Ÿณๅฃฐใƒ•ใ‚กใ‚คใƒซใŒใ‚ใ‚Šใพใ›ใ‚“ diff --git a/app/src/main/res/values-ko/strings.xml b/app/src/main/res/values-ko/strings.xml index 457511bbde..e6b6c42ecf 100644 --- a/app/src/main/res/values-ko/strings.xml +++ b/app/src/main/res/values-ko/strings.xml @@ -28,6 +28,8 @@ ์ง€๊ธˆ ์ผ์‹œ ์ค‘์ง€ ์„ธ์…˜ ์ข…๋ฃŒ ํ”„๋ ˆ์ž„ ์ƒ์„ฑ + ์ด ๊ฒŒ์ž„์˜ ์„ค์ • + ๊ธฐ๋ณธ ์„ค์ • ์‚ฌ์šฉํ•  ํ”„๋ ˆ์ž„ ์ƒ์„ฑ ๋ชจ๋“œ๋ฅผ ์„ ํƒํ•˜์„ธ์š” ๋” DD-FG %1$dร— @@ -476,6 +478,7 @@ ์ผœ์ง Steam๊ณผ ํ•จ๊ป˜ ์‹œ์ž‘ Steam ์—†์ด ์‹œ์ž‘ + ๊ฒŒ์ž„ ํ•ด์ƒ๋„ ์„ค์ • %1$s ์„ค์ • ๊ธฐ๋ณธ๊ฐ’ @@ -2164,7 +2167,6 @@ ์Šคํ† ์–ด Steam ์‚ฌ์šฉ์ž ์ •์˜ - ์Šคํ† ์–ด ๋‹ค์šด๋กœ๋“œ ์†๋„ ๋‹จ๊ณ„ ๊ท ํ˜• ๋น ๋ฆ„ @@ -2210,6 +2212,7 @@ ์ค‘๋‹จ๋จ ์„ค์น˜ ยท %1$s ๋ฌด๋ฃŒ๋กœ ๋ฐ›๊ธฐ + ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ์— ์ถ”๊ฐ€ํ•˜๋Š” ์ค‘โ€ฆ %1$s์—์„œ ๋ณด๊ธฐ ๊ตฌ๋งค ยท %1$s ์„ค์น˜๋จ @@ -2538,7 +2541,9 @@ %1$s ยท ์žฌ์‹œ์ž‘ ๋Œ€๊ธฐ ์ด ๊ธฐ๊ธฐ %1$s์„(๋ฅผ) ์ œ๊ฑฐํ•˜์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ? - ์ง„๋‹จ + ๊ฐœ๋ฐœ์ž + ๋นŒ๋“œ ๋ผ๋ฒจ ์›Œํ„ฐ๋งˆํฌ + ํ…Œ์ŠคํŠธ ๋˜๋Š” Lab ๋นŒ๋“œ ๋ผ๋ฒจ์„ ํ™”๋ฉด์— ํ‘œ์‹œํ•ฉ๋‹ˆ๋‹ค. ๊ธฐ๋ณธ์ ์œผ๋กœ ์ผœ์ ธ ์žˆ์Šต๋‹ˆ๋‹ค. ํ”Œ๋ ˆ์ด ์ค€๋น„ ์™„๋ฃŒ ์•„์ง ํ”Œ๋ ˆ์ดํ•  ์ค€๋น„๊ฐ€ ๋˜์ง€ ์•Š์Œ ๋Ÿฐํƒ€์ž„ %1$s @@ -3513,6 +3518,25 @@ ๋’ค๋กœ ์ด๋™ ์œ„์ ฏ ์„ค์ • ์œ„์ ฏ ์‚ญ์ œ + ์™ธ๊ด€ + ์•„์ด์ฝ˜ ํŒฉ + ์‹œ์Šคํ…œ ๊ธฐ๋ณธ๊ฐ’ + ์•ฑ ์ƒ‰์ƒ ๋ฐฐ๊ฒฝ + ์•„์ด์ฝ˜ ํฌ๊ธฐ + ์ž‘๊ฒŒ + ๋ณดํ†ต + ํฌ๊ฒŒ + ์•ฑ ์ด๋ฆ„ ์ˆจ๊ธฐ๊ธฐ + ๊ฐ„๊ฒฉ + ์ข๊ฒŒ + ๋ณดํ†ต + ๋„“๊ฒŒ + ์•„์ด์ฝ˜ ๋ณ€๊ฒฝ + ์•„์ด์ฝ˜ ์ดˆ๊ธฐํ™” + ์•„์ด์ฝ˜ ๊ฒ€์ƒ‰ + ์•„์ด์ฝ˜ ๋ถˆ๋Ÿฌ์˜ค๋Š” ์ค‘โ€ฆ + ์•„์ด์ฝ˜์„ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค. + ์‚ฌ์šฉ์ž ์ •์˜ ์•„์ด์ฝ˜ ํด๋”์— ์ถ”๊ฐ€ ์ƒˆ ํด๋” ํด๋”์—์„œ ์ œ๊ฑฐ @@ -3628,4 +3652,66 @@ ์ง„ํ™๋น› ๋ˆˆ + ์‚ฌ์šด๋“œํŠธ๋ž™ + ์Œ์•… + ์žฌ์ƒ ์˜ต์…˜ + ์ฆ๊ฒจ์ฐพ๊ธฐ + ์ปฌ๋ ‰์…˜ + ์•„์ง ์ปฌ๋ ‰์…˜์ด ์—†์Šต๋‹ˆ๋‹ค. ๋ถ๋งˆํฌ ์•„์ด์ฝ˜์„ ๋ˆŒ๋Ÿฌ ๋งŒ๋“ค์–ด ๋ณด์„ธ์š”. + ์ €์žฅ๋จ + ์ปฌ๋ ‰์…˜ ๋งŒ๋“ค๊ธฐ + ์ €์žฅํ•œ ๊ณก์„ ์ •๋ฆฌํ•˜์„ธ์š” + ์ƒˆ๋กœ ๋งŒ๋“ค๊ธฐ + ๋งŒ๋“ค๊ธฐ + ์ปฌ๋ ‰์…˜ ์ด๋ฆ„ + ๋‹ค๋ฅธ ์ปฌ๋ ‰์…˜์—์„œ ์‚ฌ์šฉํ•˜์ง€ ์•Š๋Š” ์ด๋ฆ„์„ ์ž…๋ ฅํ•˜์„ธ์š” + ๊ด€๋ฆฌ + ์ด๋ฆ„ ๋ณ€๊ฒฝ + ํŠธ๋ž™ ์ถ”๊ฐ€ + ์ถ”๊ฐ€ (%1$d) + ํŠธ๋ž™ ์ œ๊ฑฐ + ์ปฌ๋ ‰์…˜ ์‚ญ์ œ + %1$s์„(๋ฅผ) ์‚ญ์ œํ• ๊นŒ์š”? + ํŠธ๋ž™์€ ๊ธฐ๊ธฐ์— ๊ทธ๋Œ€๋กœ ๋‚จ์Šต๋‹ˆ๋‹ค. ์ปฌ๋ ‰์…˜๋งŒ ์‚ญ์ œ๋ฉ๋‹ˆ๋‹ค. + ์„ ํƒ + ๋ชจ๋‘ ์„ ํƒ + ๋ชจ๋‘ ์„ ํƒ ํ•ด์ œ + %1$d๊ฐœ ์„ ํƒ๋จ + ์ปฌ๋ ‰์…˜์— ์ถ”๊ฐ€ + ์ฆ๊ฒจ์ฐพ๊ธฐ์— ์ถ”๊ฐ€ + ์ปฌ๋ ‰์…˜์—์„œ ์ œ๊ฑฐ + ํŠธ๋ž™ ๊ฒ€์ƒ‰ + ์•จ๋ฒ” ์ˆœ์„œ + ๊ธด ์ˆœ์„œ + ์งง์€ ์ˆœ์„œ + ํŠธ๋ž™ + ํ”ผ์น˜ + ์ดˆ๊ธฐํ™” + ๋ฌด์Œ ๊ฑด๋„ˆ๋›ฐ๊ธฐ + ์ทจ์นจ ํƒ€์ด๋จธ + %1$d๋ถ„ + ํŠธ๋ž™ ๋ + %1$s ๋‚จ์Œ + ์ดํ€„๋ผ์ด์ € + ๋ฒ ์ด์Šค ๋ถ€์ŠคํŠธ + ์ด ๊ธฐ๊ธฐ์—์„œ๋Š” ์ดํ€„๋ผ์ด์ €๋ฅผ ์‚ฌ์šฉํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค + ๊ฒŒ์ž„ ์ค‘ ์‚ฌ์šฉ + ๊ฒŒ์ž„์ด ์‹คํ–‰๋˜๋Š” ๋™์•ˆ ์‚ฌ์šด๋“œํŠธ๋ž™ ๊ณ„์† ์žฌ์ƒ + ์„ค์น˜๋œ ์‚ฌ์šด๋“œํŠธ๋ž™์ด ์•„์ง ์—†์Šต๋‹ˆ๋‹ค. + ์‚ฌ์šด๋“œํŠธ๋ž™ ๊ฒ€์ƒ‰ + ์‚ฌ์šด๋“œํŠธ๋ž™ ํด๋” ์ถ”๊ฐ€ + ํ•ด๋‹น ํด๋”์— ์˜ค๋””์˜ค ํŒŒ์ผ์ด ์—†์Šต๋‹ˆ๋‹ค + ์ด ์žฌ์ƒ ์‹œ๊ฐ„ + %1$d๊ฐœ ํŠธ๋ž™ / %2$s + ๋””์Šคํฌ %1$s + ์…”ํ”Œ + ์ด์ „ + ์žฌ์ƒ + ์ผ์‹œ์ •์ง€ + ๋‹ค์Œ + ๋ฐ˜๋ณต ๋” + ์ „์ฒด ๋ฐ˜๋ณต + ํ•œ ๊ณก ๋ฐ˜๋ณต + ๋ณผ๋ฅจ + ์ด ์‚ฌ์šด๋“œํŠธ๋ž™์— ์˜ค๋””์˜ค ํŒŒ์ผ์ด ์—†์Šต๋‹ˆ๋‹ค diff --git a/app/src/main/res/values-ms/strings.xml b/app/src/main/res/values-ms/strings.xml index 10524febe1..fac7d2314f 100644 --- a/app/src/main/res/values-ms/strings.xml +++ b/app/src/main/res/values-ms/strings.xml @@ -28,6 +28,8 @@ Gantung sekarang Hentikan sesi Penjanaan bingkai + Tetapan untuk permainan ini + Tetapan lalai Pilih mod penjanaan bingkai Mati DD-FG %1$dร— @@ -476,6 +478,7 @@ Hidup Bermula dengan Steam Bermula tanpa Steam + Resolusi permainan Tetapan Tetapan %1$s Lalai @@ -2164,7 +2167,6 @@ Kedai Steam Tersuai - Kedai Tahap kelajuan muat turun Seimbang Pantas @@ -2210,6 +2212,7 @@ Terganggu Pasang ยท %1$s Dapatkan percuma + Menambah ke pustakaโ€ฆ Lihat pada %1$s Beli ยท %1$s Dipasang @@ -2538,7 +2541,9 @@ %1$s ยท perlu mula semula Peranti ini Alih keluar %1$s? - Diagnostik + Pembangun + Tera air label binaan + Paparkan label binaan ujian atau Lab pada skrin. Dihidupkan secara lalai. Sedia untuk bermain Belum sedia untuk bermain masa jalan %1$s @@ -3513,6 +3518,25 @@ Alih ke belakang Tetapan widget Alih keluar widget + Rupa + Pek ikon + Lalai sistem + Latar warna apl + Saiz ikon + Kecil + Sedang + Besar + Sembunyikan nama apl + Jarak + Rapat + Biasa + Luas + Tukar ikon + Set semula ikon + Cari ikon + Memuatkan ikonโ€ฆ + Tiada ikon ditemui. + Ikon tersuai Tambah pada folder Folder baharu Alih keluar daripada folder @@ -3628,4 +3652,66 @@ Salji Merah Skarlet + Runut bunyi + Muzik + Pilihan main balik + Kegemaran + Koleksi + Belum ada koleksi. Ketik ikon penanda buku untuk mencipta satu. + Disimpan + Cipta koleksi + Susun simpanan anda + Baharu + Cipta + Nama koleksi + Masukkan nama yang tidak digunakan oleh koleksi lain + Urus + Namakan semula + Tambah lagu + Tambah (%1$d) + Alih keluar lagu + Padam koleksi + Padam %1$s? + Lagu kekal pada peranti anda. Hanya koleksi dialih keluar. + Pilih + Pilih semua + Nyahpilih semua + %1$d dipilih + Tambah ke koleksi + Tambah ke kegemaran + Alih keluar daripada koleksi + Cari lagu + Susunan album + Terpanjang dahulu + Terpendek dahulu + Lagu + Pic + Tetapkan semula + Langkau senyap + Pemasa tidur + %1$d min + Hujung lagu + %1$s lagi + Penyama + Peningkat bes + Penyama tidak tersedia pada peranti ini + Dayakan dalam permainan + Teruskan memainkan runut bunyi semasa permainan berjalan + Belum ada runut bunyi dipasang. + Cari runut bunyi + Tambah folder runut bunyi + Tiada fail audio dalam folder itu + Jumlah tempoh + %1$d trek / %2$s + Cakera %1$s + Rawak + Sebelumnya + Main + Jeda + Seterusnya + Ulang dimatikan + Ulang semua + Ulang satu + Kelantangan + Tiada fail audio dalam runut bunyi ini diff --git a/app/src/main/res/values-nb/strings.xml b/app/src/main/res/values-nb/strings.xml index 8ac2561bab..65ddcd49c4 100644 --- a/app/src/main/res/values-nb/strings.xml +++ b/app/src/main/res/values-nb/strings.xml @@ -28,6 +28,8 @@ Sett pรฅ pause nรฅ Avslutt sesjon Bildegenerering + Innstillinger for dette spillet + Standardinnstillinger Velg modus for bildegenerering Av DD-FG %1$dร— @@ -478,6 +480,7 @@ Pรฅ Starter med Steam Starter uten Steam + Spillopplรธsning Innstillinger Innstillinger for %1$s Standard @@ -2189,7 +2192,6 @@ Butikker Steam Egendefinert - Butikker Nedlastingshastighetsnivรฅ Balansert Rask @@ -2235,6 +2237,7 @@ Avbrutt Installer ยท %1$s Hent gratis + Legger til i biblioteket โ€ฆ Vis pรฅ %1$s Kjรธp ยท %1$s Installert @@ -2565,7 +2568,9 @@ %1$s ยท krever omstart Denne enheten Fjerne %1$s? - Diagnostikk + Utvikler + Vannmerke for byggetikett + Vis etiketten for test- eller Lab-bygget pรฅ skjermen. Pรฅ som standard. Klar til รฅ spille Ikke klar til รฅ spille ennรฅ kjรธretid %1$s @@ -3542,6 +3547,25 @@ Flytt senere Modulinnstillinger Fjern modul + Utseende + Ikonpakke + Systemstandard + Bakgrunn i appens farge + Ikonstรธrrelse + Liten + Middels + Stor + Skjul appnavn + Avstand + Tett + Normal + Luftig + Endre ikon + Tilbakestill ikon + Sรธk etter ikoner + Laster inn ikonerโ€ฆ + Fant ingen ikoner. + Egendefinerte ikoner Legg til i mappe Ny mappe Fjern fra mappe @@ -3658,4 +3682,66 @@ Skarlagenssnรธ + Lydspor + Musikk + Avspillingsalternativer + Favoritter + Samlinger + Ingen samlinger ennรฅ. Trykk pรฅ bokmerkeikonet for รฅ opprette en. + Lagret + Opprett en samling + Organiser det du lagrer + Ny + Opprett + Navn pรฅ samling + Skriv inn et navn som ingen andre samlinger bruker + Administrer + Gi nytt navn + Legg til spor + Legg til (%1$d) + Fjern spor + Slett samling + Slette %1$s? + Sporene blir vรฆrende pรฅ enheten din. Bare samlingen fjernes. + Velg + Velg alle + Fjern alle valg + %1$d valgt + Legg til i samling + Legg til i favoritter + Fjern fra samling + Sรธk i spor + Albumrekkefรธlge + Lengste fรธrst + Korteste fรธrst + Spor + Tonehรธyde + Tilbakestill + Hopp over stillhet + Sรธvntimer + %1$d min + Slutten av sporet + %1$s igjen + Equalizer + Bassforsterkning + Equalizeren er ikke tilgjengelig pรฅ denne enheten + Aktiver i spill + Fortsett รฅ spille lydsporet mens et spill kjรธrer + Ingen lydspor installert ennรฅ. + Sรธk i lydspor + Legg til en lydspormappe + Ingen lydfiler i denne mappen + Total lengde + %1$d spor / %2$s + Plate %1$s + Tilfeldig rekkefรธlge + Forrige + Spill av + Pause + Neste + Gjentakelse av + Gjenta alle + Gjenta ett + Volum + Ingen lydfiler i dette lydsporet diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index a7bd52c016..8cbd96dd31 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -28,6 +28,8 @@ Nu onderbreken Sessie stoppen Framegeneratie + Instellingen voor dit spel + Standaardinstellingen Kies de modus voor framegeneratie Uit DD-FG %1$dร— @@ -478,6 +480,7 @@ Aan Start met Steam Start zonder Steam + Spelresolutie Instellingen Instellingen voor %1$s Standaard @@ -2189,7 +2192,6 @@ Winkels Steam Aangepast - Winkels Niveau voor downloadsnelheid Gebalanceerd Snel @@ -2235,6 +2237,7 @@ Onderbroken Installeren ยท %1$s Gratis verkrijgen + Toevoegen aan bibliotheekโ€ฆ Bekijken op %1$s Kopen ยท %1$s Geรฏnstalleerd @@ -2565,7 +2568,9 @@ %1$s ยท herstart nodig Dit apparaat %1$s verwijderen? - Diagnostiek + Ontwikkelaar + Buildlabel als watermerk + Toon het label van de testbuild of Lab-build op het scherm. Standaard ingeschakeld. Klaar om te spelen Nog niet klaar om te spelen runtime %1$s @@ -3542,6 +3547,25 @@ Naar achteren Widgetinstellingen Widget verwijderen + Weergave + Pictogrampakket + Systeemstandaard + Achtergrond in app-kleur + Grootte van pictogrammen + Klein + Middel + Groot + App-namen verbergen + Afstand + Krap + Normaal + Ruim + Pictogram wijzigen + Pictogram resetten + Pictogrammen zoeken + Pictogrammen ladenโ€ฆ + Geen pictogrammen gevonden. + Aangepaste pictogrammen Toevoegen aan map Nieuwe map Uit map verwijderen @@ -3658,4 +3682,66 @@ Scharlakenrode sneeuw + Soundtracks + Muziek + Afspeelopties + Favorieten + Collecties + Nog geen collecties. Tik op het bladwijzericoon om er een te maken. + Opgeslagen + Maak een collectie + Orden je opgeslagen nummers + Nieuw + Maken + Naam van collectie + Voer een naam in die geen andere collectie gebruikt + Beheren + Hernoemen + Nummers toevoegen + Toevoegen (%1$d) + Nummers verwijderen + Collectie verwijderen + %1$s verwijderen? + De nummers blijven op je apparaat. Alleen de collectie wordt verwijderd. + Selecteren + Alles selecteren + Alles deselecteren + %1$d geselecteerd + Toevoegen aan collectie + Toevoegen aan favorieten + Verwijderen uit collectie + Nummers zoeken + Albumvolgorde + Langste eerst + Kortste eerst + Nummers + Toonhoogte + Resetten + Stilte overslaan + Slaaptimer + %1$d min + Einde van het nummer + Nog %1$s + Equalizer + Basversterking + De equalizer is niet beschikbaar op dit apparaat + In-game inschakelen + Laat de soundtrack doorspelen terwijl een game draait + Nog geen soundtracks geรฏnstalleerd. + Soundtracks zoeken + Soundtrackmap toevoegen + Geen audiobestanden in deze map + Totale lengte + %1$d nummers / %2$s + Schijf %1$s + Willekeurig + Vorige + Afspelen + Pauzeren + Volgende + Herhalen uit + Alles herhalen + Eรฉn herhalen + Volume + Geen audiobestanden in deze soundtrack diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index 4d00ba2ee8..a829fda88b 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -28,6 +28,8 @@ Wstrzymaj teraz Zatrzymaj sesjฤ™ Generowanie klatek + Ustawienia tej gry + Ustawienia domyล›lne Wybierz tryb generowania klatek Wyล‚. DD-FG %1$dร— @@ -482,6 +484,7 @@ Wล‚. Uruchamia siฤ™ ze Steam Uruchamia siฤ™ bez Steam + Rozdzielczoล›ฤ‡ gry Ustawienia Ustawienia: %1$s Domyล›lne @@ -2239,7 +2242,6 @@ Sklepy Steam Wล‚asna - Sklepy Poziom szybkoล›ci pobierania Zbalansowany Szybki @@ -2285,6 +2287,7 @@ Przerwano Instalacja ยท %1$s Odbierz bezpล‚atnie + Dodawanie do bibliotekiโ€ฆ Zobacz w %1$s Kup ยท %1$s Zainstalowano @@ -2619,7 +2622,9 @@ %1$s ยท wymaga restartu To urzฤ…dzenie Usunฤ…ฤ‡ %1$s? - Diagnostyka + Programista + Znak wodny z etykietฤ… kompilacji + Pokazuj na ekranie etykietฤ™ kompilacji testowej lub Lab. Domyล›lnie wล‚ฤ…czone. Gotowe do gry Jeszcze nie gotowe do gry ล›rodowisko %1$s @@ -3618,6 +3623,25 @@ Przesuล„ pรณลบniej Ustawienia widลผetu Usuล„ widลผet + Wyglฤ…d + Pakiet ikon + Domyล›lny systemu + Tล‚o w kolorze aplikacji + Rozmiar ikon + Maล‚y + ลšredni + Duลผy + Ukryj nazwy aplikacji + Odstฤ™py + Ciasne + ลšrednie + Luลบne + Zmieล„ ikonฤ™ + Resetuj ikonฤ™ + Szukaj ikon + Wczytywanie ikonโ€ฆ + Nie znaleziono ikon. + Wล‚asne ikony Dodaj do folderu Nowy folder Usuล„ z folderu @@ -3736,4 +3760,66 @@ Szkarล‚atny ล›nieg + ลšcieลผki dลบwiฤ™kowe + Muzyka + Opcje odtwarzania + Ulubione + Kolekcje + Brak kolekcji. Dotknij ikony zakล‚adki, aby utworzyฤ‡ nowฤ…. + Zapisane + Utwรณrz kolekcjฤ™ + Uporzฤ…dkuj swoje zapisy + Nowa + Utwรณrz + Nazwa kolekcji + Wpisz nazwฤ™, ktรณrej nie uลผywa ลผadna inna kolekcja + Zarzฤ…dzaj + Zmieล„ nazwฤ™ + Dodaj utwory + Dodaj (%1$d) + Usuล„ utwory + Usuล„ kolekcjฤ™ + Usunฤ…ฤ‡ %1$s? + Utwory pozostajฤ… na urzฤ…dzeniu. Usuniฤ™ta zostanie tylko kolekcja. + Zaznacz + Zaznacz wszystko + Odznacz wszystko + Zaznaczono: %1$d + Dodaj do kolekcji + Dodaj do ulubionych + Usuล„ z kolekcji + Szukaj utworรณw + Kolejnoล›ฤ‡ z albumu + Najdล‚uลผsze najpierw + Najkrรณtsze najpierw + Utwory + Wysokoล›ฤ‡ dลบwiฤ™ku + Resetuj + Pomijaj ciszฤ™ + Wyล‚ฤ…cznik czasowy + %1$d min + Koniec utworu + Pozostaล‚o %1$s + Korektor + Wzmocnienie basรณw + Korektor nie jest dostฤ™pny na tym urzฤ…dzeniu + Wล‚ฤ…cz w grze + Odtwarzaj ล›cieลผkฤ™ dลบwiฤ™kowฤ… podczas dziaล‚ania gry + Brak zainstalowanych ล›cieลผek dลบwiฤ™kowych. + Szukaj ล›cieลผek dลบwiฤ™kowych + Dodaj folder ze ล›cieลผkฤ… dลบwiฤ™kowฤ… + Brak plikรณw audio w tym folderze + Caล‚kowity czas + Utworรณw: %1$d / %2$s + Pล‚yta %1$s + Losowo + Poprzedni + Odtwรณrz + Wstrzymaj + Nastฤ™pny + Powtarzanie wyล‚ฤ…czone + Powtarzaj wszystko + Powtarzaj jeden + Gล‚oล›noล›ฤ‡ + Brak plikรณw audio w tej ล›cieลผce dลบwiฤ™kowej diff --git a/app/src/main/res/values-pt-rPT/strings.xml b/app/src/main/res/values-pt-rPT/strings.xml index 17ff8cbac3..c2ee78a1c1 100644 --- a/app/src/main/res/values-pt-rPT/strings.xml +++ b/app/src/main/res/values-pt-rPT/strings.xml @@ -28,6 +28,8 @@ Suspender agora Terminar sessรฃo Geraรงรฃo de fotogramas + Definiรงรตes para este jogo + Definiรงรตes predefinidas Selecione o modo de geraรงรฃo de fotogramas Desligado DD-FG %1$dร— @@ -480,6 +482,7 @@ Ativado Inicia com o Steam Inicia sem o Steam + Resoluรงรฃo do jogo Definiรงรตes Definiรงรตes de %1$s Predefiniรงรฃo @@ -2206,7 +2209,6 @@ Lojas Steam Personalizados - Lojas Nรญvel de velocidade de transferรชncia Equilibrado Rรกpido @@ -2252,6 +2254,7 @@ Interrompida Instalar ยท %1$s Obter grรกtis + A adicionar ร  bibliotecaโ€ฆ Ver em %1$s Comprar ยท %1$s Instalado @@ -2581,7 +2584,9 @@ %1$s ยท reinรญcio pendente Este dispositivo Remover %1$s? - Diagnรณstico + Programador + Marca de รกgua da compilaรงรฃo + Mostrar no ecrรฃ a etiqueta da compilaรงรฃo de teste ou Lab. Ativada por predefiniรงรฃo. Pronto para jogar Ainda nรฃo estรก pronto para jogar ambiente de execuรงรฃo %1$s @@ -3580,6 +3585,25 @@ Mover para depois Definiรงรตes do widget Remover widget + Aspeto + Pacote de รญcones + Predefiniรงรฃo do sistema + Fundo na cor da app + Tamanho dos รญcones + Pequeno + Mรฉdio + Grande + Ocultar nomes das aplicaรงรตes + Espaรงamento + Justo + Normal + Amplo + Alterar รญcone + Repor รญcone + Pesquisar รญcones + A carregar รญconesโ€ฆ + Nenhum รญcone encontrado. + รcones personalizados Adicionar a pasta Nova pasta Remover da pasta @@ -3697,4 +3721,66 @@ Neve Escarlate + Bandas sonoras + Mรบsica + Opรงรตes de reproduรงรฃo + Favoritas + Coleรงรตes + Ainda nรฃo hรก coleรงรตes. Toque no รญcone de marcador para criar uma. + Guardadas + Criar uma coleรงรฃo + Organize as suas faixas guardadas + Nova + Criar + Nome da coleรงรฃo + Introduza um nome que nenhuma outra coleรงรฃo utilize + Gerir + Mudar o nome + Adicionar faixas + Adicionar (%1$d) + Remover faixas + Eliminar coleรงรฃo + Eliminar %1$s? + As faixas permanecem no seu dispositivo. Apenas a coleรงรฃo รฉ removida. + Selecionar + Selecionar tudo + Desselecionar tudo + %1$d selecionadas + Adicionar ร  coleรงรฃo + Adicionar ร s favoritas + Remover da coleรงรฃo + Pesquisar faixas + Ordem do รกlbum + Mais longas primeiro + Mais curtas primeiro + Faixas + Tom + Repor + Saltar silรชncio + Temporizador de suspensรฃo + %1$d min + Fim da faixa + Restam %1$s + Equalizador + Reforรงo de graves + O equalizador nรฃo estรก disponรญvel neste dispositivo + Ativar durante o jogo + Continuar a reproduzir a banda sonora enquanto um jogo estรก em execuรงรฃo + Ainda nรฃo hรก bandas sonoras instaladas. + Pesquisar bandas sonoras + Adicionar uma pasta de banda sonora + Nenhum ficheiro de รกudio nessa pasta + Duraรงรฃo total + %1$d faixas / %2$s + Disco %1$s + Aleatรณrio + Anterior + Reproduzir + Pausar + Seguinte + Repetiรงรฃo desativada + Repetir tudo + Repetir uma + Volume + Nenhum ficheiro de รกudio nesta banda sonora diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index 73d1a4c4c9..59b5af3105 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -28,6 +28,8 @@ Suspender agora Encerrar sessรฃo Geraรงรฃo de quadros + Configuraรงรตes para este jogo + Configuraรงรตes padrรฃo Selecione o modo de geraรงรฃo de quadros Desativada DD-FG %1$dร— @@ -480,6 +482,7 @@ Ativado Inicia com o Steam Inicia sem o Steam + Resoluรงรฃo do jogo Configuraรงรตes Configuraรงรตes de %1$s Padrรฃo @@ -2206,7 +2209,6 @@ Lojas Steam Personalizado - Lojas Nรญvel de velocidade de download Equilibrado Rรกpido @@ -2252,6 +2254,7 @@ Interrompido Instalar ยท %1$s Obter grรกtis + Adicionando ร  bibliotecaโ€ฆ Ver em %1$s Comprar ยท %1$s Instalado @@ -2581,7 +2584,9 @@ %1$s ยท reinรญcio pendente Este aparelho Remover %1$s? - Diagnรณstico + Desenvolvedor + Marca de รกgua da compilaรงรฃo + Mostrar na tela a etiqueta da compilaรงรฃo de teste ou Lab. Ativada por padrรฃo. Pronto para jogar Ainda nรฃo estรก pronto para jogar runtime %1$s @@ -3580,6 +3585,25 @@ Mover para depois Configuraรงรตes do widget Remover widget + Aparรชncia + Pacote de รญcones + Padrรฃo do sistema + Fundo na cor do app + Tamanho dos รญcones + Pequeno + Mรฉdio + Grande + Ocultar nomes dos apps + Espaรงamento + Justo + Normal + Amplo + Alterar รญcone + Redefinir รญcone + Buscar รญcones + Carregando รญconesโ€ฆ + Nenhum รญcone encontrado. + รcones personalizados Adicionar ร  pasta Nova pasta Remover da pasta @@ -3697,4 +3721,66 @@ Neve Escarlate + Trilhas sonoras + Mรบsica + Opรงรตes de reproduรงรฃo + Favoritas + Coleรงรตes + Nenhuma coleรงรฃo ainda. Toque no รญcone de marcador para criar uma. + Salvas + Criar uma coleรงรฃo + Organize suas faixas salvas + Nova + Criar + Nome da coleรงรฃo + Digite um nome que nenhuma outra coleรงรฃo use + Gerenciar + Renomear + Adicionar faixas + Adicionar (%1$d) + Remover faixas + Excluir coleรงรฃo + Excluir %1$s? + As faixas continuam no seu dispositivo. Somente a coleรงรฃo รฉ removida. + Selecionar + Selecionar tudo + Desmarcar tudo + %1$d selecionadas + Adicionar ร  coleรงรฃo + Adicionar ร s favoritas + Remover da coleรงรฃo + Pesquisar faixas + Ordem do รกlbum + Mais longas primeiro + Mais curtas primeiro + Faixas + Tom + Redefinir + Pular silรชncio + Timer de sono + %1$d min + Fim da faixa + Restam %1$s + Equalizador + Reforรงo de graves + O equalizador nรฃo estรก disponรญvel neste dispositivo + Ativar durante o jogo + Continuar tocando a trilha sonora enquanto um jogo estรก em execuรงรฃo + Nenhuma trilha sonora instalada ainda. + Pesquisar trilhas sonoras + Adicionar uma pasta de trilha sonora + Nenhum arquivo de รกudio nessa pasta + Duraรงรฃo total + %1$d faixas / %2$s + Disco %1$s + Aleatรณrio + Anterior + Reproduzir + Pausar + Prรณxima + Repetiรงรฃo desativada + Repetir tudo + Repetir uma + Volume + Nenhum arquivo de รกudio nesta trilha sonora diff --git a/app/src/main/res/values-ro/strings.xml b/app/src/main/res/values-ro/strings.xml index d3b8b9269b..4795221220 100644 --- a/app/src/main/res/values-ro/strings.xml +++ b/app/src/main/res/values-ro/strings.xml @@ -28,6 +28,8 @@ Suspendฤƒ acum Opreศ™te sesiunea Generare de cadre + Setฤƒri pentru acest joc + Setฤƒri implicite Selecteazฤƒ modul de generare a cadrelor Dezactivat DD-FG %1$dร— @@ -480,6 +482,7 @@ Activat Porneศ™te cu Steam Porneศ™te fฤƒrฤƒ Steam + Rezoluศ›ia jocului Setฤƒri Setฤƒri %1$s Implicit @@ -2214,7 +2217,6 @@ Magazine Steam Personalizat - Magazine Nivelul vitezei de descฤƒrcare Echilibrat Rapid @@ -2260,6 +2262,7 @@ รŽntreruptฤƒ Instalare ยท %1$s Obศ›ine gratuit + Se adaugฤƒ รฎn bibliotecฤƒโ€ฆ Vezi pe %1$s Cumpฤƒrฤƒ ยท %1$s Instalat @@ -2592,7 +2595,9 @@ %1$s ยท necesitฤƒ repornire Acest dispozitiv Elimini %1$s? - Diagnosticare + Dezvoltator + Filigranฤƒ cu eticheta versiunii + Afiศ™eazฤƒ pe ecran eticheta versiunii de testare sau Lab. Activatฤƒ implicit. Pregฤƒtit de joc รŽncฤƒ nepregฤƒtit de joc mediu de execuศ›ie %1$s @@ -3580,6 +3585,25 @@ Mutฤƒ mai tรขrziu Setฤƒri widget Eliminฤƒ widgetul + Aspect + Pachet de iconiศ›e + Implicit de sistem + Fundal รฎn culoarea aplicaศ›iei + Dimensiune iconiศ›e + Micฤƒ + Medie + Mare + Ascunde numele aplicaศ›iilor + Spaศ›iere + Strรขnsฤƒ + Normalฤƒ + Largฤƒ + Schimbฤƒ iconiศ›a + Reseteazฤƒ iconiศ›a + Cautฤƒ iconiศ›e + Se รฎncarcฤƒ iconiศ›eleโ€ฆ + Nu s-au gฤƒsit iconiศ›e. + Iconiศ›e personalizate Adaugฤƒ รฎn dosar Dosar nou Eliminฤƒ din dosar @@ -3697,4 +3721,66 @@ Zฤƒpadฤƒ stacojie + Coloane sonore + Muzicฤƒ + Opศ›iuni de redare + Favorite + Colecศ›ii + Nicio colecศ›ie รฎncฤƒ. Atinge pictograma de marcaj pentru a crea una. + Salvate + Creeazฤƒ o colecศ›ie + Organizeazฤƒ-ศ›i piesele salvate + Nouฤƒ + Creeazฤƒ + Numele colecศ›iei + Introdu un nume pe care nu รฎl foloseศ™te nicio altฤƒ colecศ›ie + Gestioneazฤƒ + Redenumeศ™te + Adaugฤƒ piese + Adaugฤƒ (%1$d) + Eliminฤƒ piese + ศ˜terge colecศ›ia + ศ˜tergi %1$s? + Piesele rฤƒmรขn pe dispozitiv. Se eliminฤƒ doar colecศ›ia. + Selecteazฤƒ + Selecteazฤƒ tot + Deselecteazฤƒ tot + %1$d selectate + Adaugฤƒ รฎn colecศ›ie + Adaugฤƒ la favorite + Eliminฤƒ din colecศ›ie + Cautฤƒ piese + Ordinea albumului + Cele mai lungi primele + Cele mai scurte primele + Piese + รŽnฤƒlศ›ime + Reseteazฤƒ + Omite tฤƒcerea + Temporizator de somn + %1$d min + Sfรขrศ™itul piesei + Mai sunt %1$s + Egalizator + Amplificare bas + Egalizatorul nu este disponibil pe acest dispozitiv + Activeazฤƒ รฎn joc + Continuฤƒ redarea coloanei sonore cรขt timp ruleazฤƒ un joc + Nicio coloanฤƒ sonorฤƒ instalatฤƒ รฎncฤƒ. + Cautฤƒ coloane sonore + Adaugฤƒ un dosar de coloanฤƒ sonorฤƒ + Niciun fiศ™ier audio รฎn acel dosar + Duratฤƒ totalฤƒ + Piese: %1$d ยท %2$s + Discul %1$s + Amestecare + Anterior + Redare + Pauzฤƒ + Urmฤƒtor + Repetare dezactivatฤƒ + Repetฤƒ tot + Repetฤƒ una + Volum + Niciun fiศ™ier audio รฎn aceastฤƒ coloanฤƒ sonorฤƒ diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index 89dc1b2d78..55d3431388 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -28,6 +28,8 @@ ะŸั€ะธะพัั‚ะฐะฝะพะฒะธั‚ัŒ ัะตะนั‡ะฐั ะžัั‚ะฐะฝะพะฒะธั‚ัŒ ัะตััะธัŽ ะ“ะตะฝะตั€ะฐั†ะธั ะบะฐะดั€ะพะฒ + ะะฐัั‚ั€ะพะนะบะธ ัั‚ะพะน ะธะณั€ั‹ + ะะฐัั‚ั€ะพะนะบะธ ะฟะพ ัƒะผะพะปั‡ะฐะฝะธัŽ ะ’ั‹ะฑะตั€ะธั‚ะต ั€ะตะถะธะผ ะณะตะฝะตั€ะฐั†ะธะธ ะบะฐะดั€ะพะฒ ะ’ั‹ะบะป. DD-FG %1$dร— @@ -501,6 +503,7 @@ ะ’ะบะปัŽั‡ะตะฝะพ ะ—ะฐะฟัƒัะบะฐะตั‚ัั ัะพ Steam ะ—ะฐะฟัƒัะบะฐะตั‚ัั ะฑะตะท Steam + ะ ะฐะทั€ะตัˆะตะฝะธะต ะธะณั€ั‹ ะะฐัั‚ั€ะพะนะบะธ ะะฐัั‚ั€ะพะนะบะธ %1$s ะŸะพ ัƒะผะพะปั‡ะฐะฝะธัŽ @@ -2322,7 +2325,6 @@ ะœะฐะณะฐะทะธะฝั‹ Steam ะกะฒะพะธ - ะœะฐะณะฐะทะธะฝั‹ ะฃั€ะพะฒะตะฝัŒ ัะบะพั€ะพัั‚ะธ ะทะฐะณั€ัƒะทะบะธ ะกะฑะฐะปะฐะฝัะธั€ะพะฒะฐะฝะฝั‹ะน ะ‘ั‹ัั‚ั€ั‹ะน @@ -2368,6 +2370,7 @@ ะŸั€ะตั€ะฒะฐะฝะพ ะฃัั‚ะฐะฝะพะฒะธั‚ัŒ ยท %1$s ะŸะพะปัƒั‡ะธั‚ัŒ ะฑะตัะฟะปะฐั‚ะฝะพ + ะ”ะพะฑะฐะฒะปะตะฝะธะต ะฒ ะฑะธะฑะปะธะพั‚ะตะบัƒโ€ฆ ะžั‚ะบั€ั‹ั‚ัŒ ะฒ %1$s ะšัƒะฟะธั‚ัŒ ยท %1$s ะฃัั‚ะฐะฝะพะฒะปะตะฝะพ @@ -2699,7 +2702,9 @@ %1$s ยท ะฝัƒะถะตะฝ ะฟะตั€ะตะทะฐะฟัƒัะบ ะญั‚ะพ ัƒัั‚ั€ะพะนัั‚ะฒะพ ะฃะดะฐะปะธั‚ัŒ %1$s? - ะ”ะธะฐะณะฝะพัั‚ะธะบะฐ + ะ ะฐะทั€ะฐะฑะพั‚ั‡ะธะบ + ะ’ะพะดัะฝะพะน ะทะฝะฐะบ ั ะผะตั‚ะบะพะน ัะฑะพั€ะบะธ + ะŸะพะบะฐะทั‹ะฒะฐั‚ัŒ ะฝะฐ ัะบั€ะฐะฝะต ะผะตั‚ะบัƒ ั‚ะตัั‚ะพะฒะพะน ัะฑะพั€ะบะธ ะธะปะธ ัะฑะพั€ะบะธ Lab. ะ’ะบะปัŽั‡ะตะฝะพ ะฟะพ ัƒะผะพะปั‡ะฐะฝะธัŽ. ะ“ะพั‚ะพะฒะพ ะบ ะธะณั€ะต ะŸะพะบะฐ ะฝะต ะณะพั‚ะพะฒะพ ะบ ะธะณั€ะต ัั€ะตะดะฐ ะฒั‹ะฟะพะปะฝะตะฝะธั %1$s @@ -3701,6 +3706,25 @@ ะŸะตั€ะตะผะตัั‚ะธั‚ัŒ ะฟะพะทะถะต ะะฐัั‚ั€ะพะนะบะธ ะฒะธะดะถะตั‚ะฐ ะฃะดะฐะปะธั‚ัŒ ะฒะธะดะถะตั‚ + ะ’ะฝะตัˆะฝะธะน ะฒะธะด + ะะฐะฑะพั€ ะธะบะพะฝะพะบ + ะšะฐะบ ะฒ ัะธัั‚ะตะผะต + ะคะพะฝ ั†ะฒะตั‚ะฐ ะฟั€ะธะปะพะถะตะฝะธั + ะ ะฐะทะผะตั€ ะธะบะพะฝะพะบ + ะœะตะปะบะธะต + ะกั€ะตะดะฝะธะต + ะšั€ัƒะฟะฝั‹ะต + ะกะบั€ั‹ั‚ัŒ ะฝะฐะทะฒะฐะฝะธั ะฟั€ะธะปะพะถะตะฝะธะน + ะžั‚ัั‚ัƒะฟั‹ + ะฃะทะบะพ + ะกั€ะตะดะฝะต + ะจะธั€ะพะบะพ + ะกะผะตะฝะธั‚ัŒ ะธะบะพะฝะบัƒ + ะกะฑั€ะพัะธั‚ัŒ ะธะบะพะฝะบัƒ + ะŸะพะธัะบ ะธะบะพะฝะพะบ + ะ—ะฐะณั€ัƒะทะบะฐ ะธะบะพะฝะพะบโ€ฆ + ะ˜ะบะพะฝะบะธ ะฝะต ะฝะฐะนะดะตะฝั‹. + ะกะฒะพะธ ะธะบะพะฝะบะธ ะ”ะพะฑะฐะฒะธั‚ัŒ ะฒ ะฟะฐะฟะบัƒ ะะพะฒะฐั ะฟะฐะฟะบะฐ ะฃะฑั€ะฐั‚ัŒ ะธะท ะฟะฐะฟะบะธ @@ -3819,4 +3843,66 @@ ะะปั‹ะน ัะฝะตะณ + ะกะฐัƒะฝะดั‚ั€ะตะบะธ + ะœัƒะทั‹ะบะฐ + ะŸะฐั€ะฐะผะตั‚ั€ั‹ ะฒะพัะฟั€ะพะธะทะฒะตะดะตะฝะธั + ะ˜ะทะฑั€ะฐะฝะฝะพะต + ะšะพะปะปะตะบั†ะธะธ + ะšะพะปะปะตะบั†ะธะน ะฟะพะบะฐ ะฝะตั‚. ะะฐะถะผะธั‚ะต ะฝะฐ ะทะฝะฐั‡ะพะบ ะทะฐะบะปะฐะดะบะธ, ั‡ั‚ะพะฑั‹ ัะพะทะดะฐั‚ัŒ ะตั‘. + ะกะพั…ั€ะฐะฝะตะฝะพ + ะกะพะทะดะฐั‚ัŒ ะบะพะปะปะตะบั†ะธัŽ + ะฃะฟะพั€ัะดะพั‡ะธั‚ะต ัะพั…ั€ะฐะฝั‘ะฝะฝะพะต + ะะพะฒะฐั + ะกะพะทะดะฐั‚ัŒ + ะะฐะทะฒะฐะฝะธะต ะบะพะปะปะตะบั†ะธะธ + ะ’ะฒะตะดะธั‚ะต ะฝะฐะทะฒะฐะฝะธะต, ะบะพั‚ะพั€ะพะต ะฝะต ะธัะฟะพะปัŒะทัƒะตั‚ัั ะฒ ะดั€ัƒะณะพะน ะบะพะปะปะตะบั†ะธะธ + ะฃะฟั€ะฐะฒะปะตะฝะธะต + ะŸะตั€ะตะธะผะตะฝะพะฒะฐั‚ัŒ + ะ”ะพะฑะฐะฒะธั‚ัŒ ั‚ั€ะตะบะธ + ะ”ะพะฑะฐะฒะธั‚ัŒ (%1$d) + ะฃะฑั€ะฐั‚ัŒ ั‚ั€ะตะบะธ + ะฃะดะฐะปะธั‚ัŒ ะบะพะปะปะตะบั†ะธัŽ + ะฃะดะฐะปะธั‚ัŒ %1$s? + ะขั€ะตะบะธ ะพัั‚ะฐะฝัƒั‚ัั ะฝะฐ ัƒัั‚ั€ะพะนัั‚ะฒะต. ะ‘ัƒะดะตั‚ ัƒะดะฐะปะตะฝะฐ ั‚ะพะปัŒะบะพ ะบะพะปะปะตะบั†ะธั. + ะ’ั‹ะฑั€ะฐั‚ัŒ + ะ’ั‹ะฑั€ะฐั‚ัŒ ะฒัะต + ะกะฝัั‚ัŒ ะฒั‹ะฑะพั€ + ะ’ั‹ะฑั€ะฐะฝะพ: %1$d + ะ”ะพะฑะฐะฒะธั‚ัŒ ะฒ ะบะพะปะปะตะบั†ะธัŽ + ะ”ะพะฑะฐะฒะธั‚ัŒ ะฒ ะธะทะฑั€ะฐะฝะฝะพะต + ะฃะฑั€ะฐั‚ัŒ ะธะท ะบะพะปะปะตะบั†ะธะธ + ะŸะพะธัะบ ั‚ั€ะตะบะพะฒ + ะŸะพั€ัะดะพะบ ะฒ ะฐะปัŒะฑะพะผะต + ะกะฝะฐั‡ะฐะปะฐ ะดะปะธะฝะฝั‹ะต + ะกะฝะฐั‡ะฐะปะฐ ะบะพั€ะพั‚ะบะธะต + ะขั€ะตะบะธ + ะ’ั‹ัะพั‚ะฐ ั‚ะพะฝะฐ + ะกะฑั€ะพัะธั‚ัŒ + ะŸั€ะพะฟัƒัะบะฐั‚ัŒ ั‚ะธัˆะธะฝัƒ + ะขะฐะนะผะตั€ ัะฝะฐ + %1$d ะผะธะฝ + ะšะพะฝะตั† ั‚ั€ะตะบะฐ + ะžัั‚ะฐะปะพััŒ %1$s + ะญะบะฒะฐะปะฐะนะทะตั€ + ะฃัะธะปะตะฝะธะต ะฑะฐัะฐ + ะญะบะฒะฐะปะฐะนะทะตั€ ะฝะตะดะพัั‚ัƒะฟะตะฝ ะฝะฐ ัั‚ะพะผ ัƒัั‚ั€ะพะนัั‚ะฒะต + ะ’ะบะปัŽั‡ะธั‚ัŒ ะฒ ะธะณั€ะต + ะŸั€ะพะดะพะปะถะฐั‚ัŒ ะฒะพัะฟั€ะพะธะทะฒะตะดะตะฝะธะต ัะฐัƒะฝะดั‚ั€ะตะบะฐ ะฒะพ ะฒั€ะตะผั ะธะณั€ั‹ + ะกะฐัƒะฝะดั‚ั€ะตะบะธ ะตั‰ั‘ ะฝะต ัƒัั‚ะฐะฝะพะฒะปะตะฝั‹. + ะŸะพะธัะบ ัะฐัƒะฝะดั‚ั€ะตะบะพะฒ + ะ”ะพะฑะฐะฒะธั‚ัŒ ะฟะฐะฟะบัƒ ัะฐัƒะฝะดั‚ั€ะตะบะฐ + ะ’ ัั‚ะพะน ะฟะฐะฟะบะต ะฝะตั‚ ะฐัƒะดะธะพั„ะฐะนะปะพะฒ + ะžะฑั‰ะฐั ะดะปะธั‚ะตะปัŒะฝะพัั‚ัŒ + ะขั€ะตะบะพะฒ: %1$d / %2$s + ะ”ะธัะบ %1$s + ะŸะตั€ะตะผะตัˆะฐั‚ัŒ + ะะฐะทะฐะด + ะ’ะพัะฟั€ะพะธะทะฒะตัั‚ะธ + ะŸะฐัƒะทะฐ + ะ”ะฐะปะตะต + ะŸะพะฒั‚ะพั€ ะฒั‹ะบะปัŽั‡ะตะฝ + ะŸะพะฒั‚ะพั€ัั‚ัŒ ะฒัั‘ + ะŸะพะฒั‚ะพั€ัั‚ัŒ ะพะดะธะฝ + ะ“ั€ะพะผะบะพัั‚ัŒ + ะ’ ัั‚ะพะผ ัะฐัƒะฝะดั‚ั€ะตะบะต ะฝะตั‚ ะฐัƒะดะธะพั„ะฐะนะปะพะฒ diff --git a/app/src/main/res/values-sv/strings.xml b/app/src/main/res/values-sv/strings.xml index c8a3088a00..fedeebf4c6 100644 --- a/app/src/main/res/values-sv/strings.xml +++ b/app/src/main/res/values-sv/strings.xml @@ -28,6 +28,8 @@ Pausa nu Stoppa sessionen Bildrutegenerering + Instรคllningar fรถr det hรคr spelet + Standardinstรคllningar Vรคlj lรคge fรถr bildrutegenerering Av DD-FG %1$dร— @@ -478,6 +480,7 @@ Pรฅ Startar med Steam Startar utan Steam + Spelupplรถsning Instรคllningar Instรคllningar fรถr %1$s Standard @@ -2189,7 +2192,6 @@ Butiker Steam Egna - Butiker Nedladdningshastighet Balanserad Snabb @@ -2235,6 +2237,7 @@ Avbruten Installation ยท %1$s Hรคmta gratis + Lรคgger till i biblioteket โ€ฆ Visa pรฅ %1$s Kรถp ยท %1$s Installerat @@ -2565,7 +2568,9 @@ %1$s ยท krรคver omstart Den hรคr enheten Ta bort %1$s? - Diagnostik + Utvecklare + Vattenstรคmpel med byggetikett + Visa testbyggets eller Lab-byggets etikett pรฅ skรคrmen. Aktiverad som standard. Redo att spela Inte redo att spela รคn runtime %1$s @@ -3542,6 +3547,25 @@ Flytta senare Widgetinstรคllningar Ta bort widget + Utseende + Ikonpaket + Systemstandard + Bakgrund i appens fรคrg + Ikonstorlek + Liten + Mellan + Stor + Dรถlj appnamn + Avstรฅnd + Tรคtt + Normalt + Luftigt + ร„ndra ikon + ร…terstรคll ikon + Sรถk ikoner + Lรคser in ikonerโ€ฆ + Inga ikoner hittades. + Anpassade ikoner Lรคgg till i mapp Ny mapp Ta bort frรฅn mapp @@ -3658,4 +3682,66 @@ Scharlakansrรถd snรถ + Soundtracks + Musik + Uppspelningsalternativ + Favoriter + Samlingar + Inga samlingar รคn. Tryck pรฅ bokmรคrkesikonen fรถr att skapa en. + Sparade + Skapa en samling + Organisera dina sparade spรฅr + Ny + Skapa + Samlingens namn + Ange ett namn som ingen annan samling anvรคnder + Hantera + Byt namn + Lรคgg till spรฅr + Lรคgg till (%1$d) + Ta bort spรฅr + Ta bort samling + Ta bort %1$s? + Spรฅren finns kvar pรฅ din enhet. Bara samlingen tas bort. + Vรคlj + Vรคlj alla + Avmarkera alla + %1$d valda + Lรคgg till i samling + Lรคgg till i favoriter + Ta bort frรฅn samling + Sรถk spรฅr + Albumordning + Lรคngst fรถrst + Kortast fรถrst + Spรฅr + Tonhรถjd + ร…terstรคll + Hoppa รถver tystnad + Insomningstimer + %1$d min + Slutet av spรฅret + %1$s kvar + Equalizer + Basfรถrstรคrkning + Equalizern รคr inte tillgรคnglig pรฅ den hรคr enheten + Aktivera i spel + Fortsรคtt spela soundtracket medan ett spel kรถrs + Inga soundtracks installerade รคn. + Sรถk bland soundtracks + Lรคgg till en soundtrackmapp + Inga ljudfiler i den mappen + Total lรคngd + %1$d spรฅr / %2$s + Skiva %1$s + Blanda + Fรถregรฅende + Spela + Pausa + Nรคsta + Upprepning av + Upprepa alla + Upprepa ett + Volym + Inga ljudfiler i detta soundtrack diff --git a/app/src/main/res/values-th/strings.xml b/app/src/main/res/values-th/strings.xml index 4bbe6cf467..0f72c64631 100644 --- a/app/src/main/res/values-th/strings.xml +++ b/app/src/main/res/values-th/strings.xml @@ -28,6 +28,8 @@ เธซเธขเธธเธ”เธŠเธฑเนˆเธงเธ„เธฃเธฒเธงเธ•เธญเธ™เธ™เธตเน‰ เธซเธขเธธเธ”เน€เธ‹เธชเธŠเธฑเธ™ เธเธฒเธฃเธชเธฃเน‰เธฒเธ‡เน€เธŸเธฃเธก + เธเธฒเธฃเธ•เธฑเน‰เธ‡เธ„เนˆเธฒเธชเธณเธซเธฃเธฑเธšเน€เธเธกเธ™เธตเน‰ + เธเธฒเธฃเธ•เธฑเน‰เธ‡เธ„เนˆเธฒเน€เธฃเธดเนˆเธกเธ•เน‰เธ™ เน€เธฅเธทเธญเธเน‚เธซเธกเธ”เธเธฒเธฃเธชเธฃเน‰เธฒเธ‡เน€เธŸเธฃเธก เธ›เธดเธ” DD-FG %1$dร— @@ -476,6 +478,7 @@ เน€เธ›เธดเธ” เน€เธฃเธดเนˆเธกเธžเธฃเน‰เธญเธก Steam เน€เธฃเธดเนˆเธกเน‚เธ”เธขเน„เธกเนˆเนƒเธŠเน‰ Steam + เธ„เธงเธฒเธกเธฅเธฐเน€เธญเธตเธขเธ”เธ‚เธญเธ‡เน€เธเธก เธเธฒเธฃเธ•เธฑเน‰เธ‡เธ„เนˆเธฒ เธเธฒเธฃเธ•เธฑเน‰เธ‡เธ„เนˆเธฒ %1$s เธ„เนˆเธฒเน€เธฃเธดเนˆเธกเธ•เน‰เธ™ @@ -2164,7 +2167,6 @@ เธชเน‚เธ•เธฃเนŒ Steam เธเธณเธซเธ™เธ”เน€เธญเธ‡ - เธชเน‚เธ•เธฃเนŒ เธฃเธฐเธ”เธฑเธšเธ„เธงเธฒเธกเน€เธฃเน‡เธงเธเธฒเธฃเธ”เธฒเธงเธ™เนŒเน‚เธซเธฅเธ” เธชเธกเธ”เธธเธฅ เน€เธฃเน‡เธง @@ -2210,6 +2212,7 @@ เธ–เธนเธเธ‚เธฑเธ”เธˆเธฑเธ‡เธซเธงเธฐ เธ•เธดเธ”เธ•เธฑเน‰เธ‡ ยท %1$s เธฃเธฑเธšเน„เธ›เน€เธฅเธขเธŸเธฃเธต + เธเธณเธฅเธฑเธ‡เน€เธžเธดเนˆเธกเธฅเธ‡เนƒเธ™เธ„เธฅเธฑเธ‡โ€ฆ เธ”เธนเธšเธ™ %1$s เธ‹เธทเน‰เธญ ยท %1$s เธ•เธดเธ”เธ•เธฑเน‰เธ‡เนเธฅเน‰เธง @@ -2538,7 +2541,9 @@ %1$s ยท เธ•เน‰เธญเธ‡เธฃเธตเธชเธ•เธฒเธฃเนŒเธ• เธญเธธเธ›เธเธฃเธ“เนŒเธ™เธตเน‰ เธฅเธš %1$s? - เธเธฒเธฃเธงเธดเธ™เธดเธˆเธ‰เธฑเธข + เธ™เธฑเธเธžเธฑเธ’เธ™เธฒ + เธฅเธฒเธขเธ™เน‰เธณเธ›เน‰เธฒเธขเธŠเธทเนˆเธญเธšเธดเธฅเธ”เนŒ + เนเธชเธ”เธ‡เธ›เน‰เธฒเธขเธŠเธทเนˆเธญเธšเธดเธฅเธ”เนŒเธ—เธ”เธชเธญเธšเธซเธฃเธทเธญเธšเธดเธฅเธ”เนŒ Lab เธšเธ™เธซเธ™เน‰เธฒเธˆเธญ เน€เธ›เธดเธ”เน„เธงเน‰เน‚เธ”เธขเธ„เนˆเธฒเน€เธฃเธดเนˆเธกเธ•เน‰เธ™ เธžเธฃเน‰เธญเธกเน€เธฅเนˆเธ™เนเธฅเน‰เธง เธขเธฑเธ‡เน„เธกเนˆเธžเธฃเน‰เธญเธกเน€เธฅเนˆเธ™ เธฃเธฑเธ™เน„เธ—เธกเนŒ %1$s @@ -3513,6 +3518,25 @@ เธขเน‰เธฒเธขเน„เธ›เธซเธฅเธฑเธ‡ เธเธฒเธฃเธ•เธฑเน‰เธ‡เธ„เนˆเธฒเธงเธดเธ”เน€เธˆเน‡เธ• เธ™เธณเธงเธดเธ”เน€เธˆเน‡เธ•เธญเธญเธ + เธฃเธนเธ›เธฅเธฑเธเธฉเธ“เนŒ + เธŠเธธเธ”เน„เธญเธ„เธญเธ™ + เธ„เนˆเธฒเน€เธฃเธดเนˆเธกเธ•เน‰เธ™เธ‚เธญเธ‡เธฃเธฐเธšเธš + เธžเธทเน‰เธ™เธซเธฅเธฑเธ‡เธชเธตเธ‚เธญเธ‡เนเธญเธ› + เธ‚เธ™เธฒเธ”เน„เธญเธ„เธญเธ™ + เน€เธฅเน‡เธ + เธ›เธฒเธ™เธเธฅเธฒเธ‡ + เนƒเธซเธเนˆ + เธ‹เนˆเธญเธ™เธŠเธทเนˆเธญเนเธญเธ› + เธฃเธฐเธขเธฐเธซเนˆเธฒเธ‡ + เธŠเธดเธ” + เธ›เธเธ•เธด + เธเธงเน‰เธฒเธ‡ + เน€เธ›เธฅเธตเนˆเธขเธ™เน„เธญเธ„เธญเธ™ + เธฃเธตเน€เธ‹เน‡เธ•เน„เธญเธ„เธญเธ™ + เธ„เน‰เธ™เธซเธฒเน„เธญเธ„เธญเธ™ + เธเธณเธฅเธฑเธ‡เน‚เธซเธฅเธ”เน„เธญเธ„เธญเธ™โ€ฆ + เน„เธกเนˆเธžเธšเน„เธญเธ„เธญเธ™ + เน„เธญเธ„เธญเธ™เธ—เธตเนˆเธเธณเธซเธ™เธ”เน€เธญเธ‡ เน€เธžเธดเนˆเธกเธฅเธ‡เนƒเธ™เน‚เธŸเธฅเน€เธ”เธญเธฃเนŒ เน‚เธŸเธฅเน€เธ”เธญเธฃเนŒเนƒเธซเธกเนˆ เธ™เธณเธญเธญเธเธˆเธฒเธเน‚เธŸเธฅเน€เธ”เธญเธฃเนŒ @@ -3628,4 +3652,66 @@ เธซเธดเธกเธฐเธชเธตเนเธ”เธ‡เธŠเธฒเธ” + เธ‹เธฒเธงเธ”เนŒเนเธ—เธฃเน‡เธ + เน€เธžเธฅเธ‡ + เธ•เธฑเธงเน€เธฅเธทเธญเธเธเธฒเธฃเน€เธฅเนˆเธ™ + เธฃเธฒเธขเธเธฒเธฃเน‚เธ›เธฃเธ” + เธ„เธญเธฅเน€เธฅเธเธŠเธฑเธ™ + เธขเธฑเธ‡เน„เธกเนˆเธกเธตเธ„เธญเธฅเน€เธฅเธเธŠเธฑเธ™ เนเธ•เธฐเน„เธญเธ„เธญเธ™เธšเธธเนŠเธเธกเธฒเธฃเนŒเธเน€เธžเธทเนˆเธญเธชเธฃเน‰เธฒเธ‡ + เธšเธฑเธ™เธ—เธถเธเนเธฅเน‰เธง + เธชเธฃเน‰เธฒเธ‡เธ„เธญเธฅเน€เธฅเธเธŠเธฑเธ™ + เธˆเธฑเธ”เธฃเธฐเน€เธšเธตเธขเธšเธฃเธฒเธขเธเธฒเธฃเธ—เธตเนˆเธšเธฑเธ™เธ—เธถเธเน„เธงเน‰ + เนƒเธซเธกเนˆ + เธชเธฃเน‰เธฒเธ‡ + เธŠเธทเนˆเธญเธ„เธญเธฅเน€เธฅเธเธŠเธฑเธ™ + เธ›เน‰เธญเธ™เธŠเธทเนˆเธญเธ—เธตเนˆเน„เธกเนˆเธ‹เน‰เธณเธเธฑเธšเธ„เธญเธฅเน€เธฅเธเธŠเธฑเธ™เธญเธทเนˆเธ™ + เธˆเธฑเธ”เธเธฒเธฃ + เน€เธ›เธฅเธตเนˆเธขเธ™เธŠเธทเนˆเธญ + เน€เธžเธดเนˆเธกเนเธ—เธฃเน‡เธ + เน€เธžเธดเนˆเธก (%1$d) + เน€เธญเธฒเนเธ—เธฃเน‡เธเธญเธญเธ + เธฅเธšเธ„เธญเธฅเน€เธฅเธเธŠเธฑเธ™ + เธฅเธš %1$s เธซเธฃเธทเธญเน„เธกเนˆ? + เนเธ—เธฃเน‡เธเธขเธฑเธ‡เธญเธขเธนเนˆเนƒเธ™เธญเธธเธ›เธเธฃเธ“เนŒเธ‚เธญเธ‡เธ„เธธเธ“ เธˆเธฐเธฅเธšเน€เธ‰เธžเธฒเธฐเธ„เธญเธฅเน€เธฅเธเธŠเธฑเธ™ + เน€เธฅเธทเธญเธ + เน€เธฅเธทเธญเธเธ—เธฑเน‰เธ‡เธซเธกเธ” + เธขเธเน€เธฅเธดเธเธเธฒเธฃเน€เธฅเธทเธญเธเธ—เธฑเน‰เธ‡เธซเธกเธ” + เน€เธฅเธทเธญเธเนเธฅเน‰เธง %1$d เธฃเธฒเธขเธเธฒเธฃ + เน€เธžเธดเนˆเธกเนƒเธ™เธ„เธญเธฅเน€เธฅเธเธŠเธฑเธ™ + เน€เธžเธดเนˆเธกเนƒเธ™เธฃเธฒเธขเธเธฒเธฃเน‚เธ›เธฃเธ” + เน€เธญเธฒเธญเธญเธเธˆเธฒเธเธ„เธญเธฅเน€เธฅเธเธŠเธฑเธ™ + เธ„เน‰เธ™เธซเธฒเนเธ—เธฃเน‡เธ + เธฅเธณเธ”เธฑเธšเธญเธฑเธฅเธšเธฑเน‰เธก + เธขเธฒเธงเธ—เธตเนˆเธชเธธเธ”เธเนˆเธญเธ™ + เธชเธฑเน‰เธ™เธ—เธตเนˆเธชเธธเธ”เธเนˆเธญเธ™ + เนเธ—เธฃเน‡เธ + เธฃเธฐเธ”เธฑเธšเน€เธชเธตเธขเธ‡ + เธฃเธตเน€เธ‹เน‡เธ• + เธ‚เน‰เธฒเธกเธŠเนˆเธงเธ‡เน€เธ‡เธตเธขเธš + เธ•เธฑเน‰เธ‡เน€เธงเธฅเธฒเธ›เธดเธ” + %1$d เธ™เธฒเธ—เธต + เธˆเธšเนเธ—เธฃเน‡เธ + เน€เธซเธฅเธทเธญ %1$s + เธญเธตเธ„เธงเธญเน„เธฅเน€เธ‹เธญเธฃเนŒ + เน€เธžเธดเนˆเธกเน€เธชเธตเธขเธ‡เน€เธšเธช + เธญเธธเธ›เธเธฃเธ“เนŒเธ™เธตเน‰เน„เธกเนˆเธฃเธญเธ‡เธฃเธฑเธšเธญเธตเธ„เธงเธญเน„เธฅเน€เธ‹เธญเธฃเนŒ + เน€เธ›เธดเธ”เนƒเธŠเน‰เธ‚เธ“เธฐเน€เธฅเนˆเธ™เน€เธเธก + เน€เธฅเนˆเธ™เธ‹เธฒเธงเธ”เนŒเนเธ—เธฃเน‡เธเธ•เนˆเธญเน„เธ›เธ‚เธ“เธฐเธ—เธตเนˆเน€เธเธกเธ—เธณเธ‡เธฒเธ™ + เธขเธฑเธ‡เน„เธกเนˆเธกเธตเธ‹เธฒเธงเธ”เนŒเนเธ—เธฃเน‡เธเธ—เธตเนˆเธ•เธดเธ”เธ•เธฑเน‰เธ‡ + เธ„เน‰เธ™เธซเธฒเธ‹เธฒเธงเธ”เนŒเนเธ—เธฃเน‡เธ + เน€เธžเธดเนˆเธกเน‚เธŸเธฅเน€เธ”เธญเธฃเนŒเธ‹เธฒเธงเธ”เนŒเนเธ—เธฃเน‡เธ + เน„เธกเนˆเธžเธšเน„เธŸเธฅเนŒเน€เธชเธตเธขเธ‡เนƒเธ™เน‚เธŸเธฅเน€เธ”เธญเธฃเนŒเธ™เธฑเน‰เธ™ + เธ„เธงเธฒเธกเธขเธฒเธงเธ—เธฑเน‰เธ‡เธซเธกเธ” + %1$d เนเธ—เธฃเน‡เธ / %2$s + เธ”เธดเธชเธเนŒ %1$s + เธชเธธเนˆเธก + เธเนˆเธญเธ™เธซเธ™เน‰เธฒ + เน€เธฅเนˆเธ™ + เธซเธขเธธเธ”เธŠเธฑเนˆเธงเธ„เธฃเธฒเธง + เธ–เธฑเธ”เน„เธ› + เธ›เธดเธ”เธเธฒเธฃเน€เธฅเนˆเธ™เธ‹เน‰เธณ + เน€เธฅเนˆเธ™เธ‹เน‰เธณเธ—เธฑเน‰เธ‡เธซเธกเธ” + เน€เธฅเนˆเธ™เธ‹เน‰เธณเธซเธ™เธถเนˆเธ‡เน€เธžเธฅเธ‡ + เธฃเธฐเธ”เธฑเธšเน€เธชเธตเธขเธ‡ + เน„เธกเนˆเธžเธšเน„เธŸเธฅเนŒเน€เธชเธตเธขเธ‡เนƒเธ™เธ‹เธฒเธงเธ”เนŒเนเธ—เธฃเน‡เธเธ™เธตเน‰ diff --git a/app/src/main/res/values-tr/strings.xml b/app/src/main/res/values-tr/strings.xml index 1d53a2d478..1700875b0b 100644 --- a/app/src/main/res/values-tr/strings.xml +++ b/app/src/main/res/values-tr/strings.xml @@ -28,6 +28,8 @@ ลžimdi askฤฑya al Oturumu durdur Kare oluลŸturma + Bu oyunun ayarlarฤฑ + Varsayฤฑlan ayarlar Kare oluลŸturma modunu seรงin Kapalฤฑ DD-FG %1$dร— @@ -478,6 +480,7 @@ Aรงฤฑk Steam ile baลŸlar Steam olmadan baลŸlar + Oyun รงรถzรผnรผrlรผฤŸรผ Ayarlar %1$s Ayarlarฤฑ Varsayฤฑlan @@ -2181,7 +2184,6 @@ MaฤŸazalar Steam ร–zel - MaฤŸazalar ฤฐndirme hฤฑzฤฑ katmanฤฑ Dengeli Hฤฑzlฤฑ @@ -2227,6 +2229,7 @@ Kesintiye uฤŸradฤฑ Yรผkle ยท %1$s รœcretsiz al + KitaplฤฑฤŸa ekleniyorโ€ฆ %1$s\'te gรถrรผntรผle Satฤฑn al ยท %1$s Yรผklรผ @@ -2554,7 +2557,9 @@ %1$s ยท yeniden baลŸlatma bekliyor Bu cihaz %1$s kaldฤฑrฤฑlsฤฑn mฤฑ? - Tanฤฑlama + GeliลŸtirici + Derleme etiketi filigranฤฑ + Test veya Lab derlemesinin etiketini ekranda gรถsterir. Varsayฤฑlan olarak aรงฤฑktฤฑr. Oynamaya hazฤฑr Henรผz oynamaya hazฤฑr deฤŸil รงalฤฑลŸma ortamฤฑ %1$s @@ -3542,6 +3547,25 @@ Arkaya taลŸฤฑ Widget ayarlarฤฑ Widgetโ€™ฤฑ kaldฤฑr + Gรถrรผnรผm + Simge paketi + Sistem varsayฤฑlanฤฑ + Uygulama rengi arka plan + Simge boyutu + Kรผรงรผk + Orta + Bรผyรผk + Uygulama adlarฤฑnฤฑ gizle + Aralฤฑk + Dar + Normal + GeniลŸ + Simgeyi deฤŸiลŸtir + Simgeyi sฤฑfฤฑrla + Simge ara + Simgeler yรผkleniyorโ€ฆ + Simge bulunamadฤฑ. + ร–zel simgeler Klasรถre ekle Yeni klasรถr Klasรถrden รงฤฑkar @@ -3658,4 +3682,66 @@ Kฤฑzฤฑl Kar + Oyun mรผzikleri + Mรผzik + Oynatma seรงenekleri + Favoriler + Koleksiyonlar + Henรผz koleksiyon yok. OluลŸturmak iรงin yer imi simgesine dokun. + Kaydedilenler + Koleksiyon oluลŸtur + Kayฤฑtlarฤฑnฤฑ dรผzenle + Yeni + OluลŸtur + Koleksiyon adฤฑ + BaลŸka bir koleksiyonun kullanmadฤฑฤŸฤฑ bir ad gir + Yรถnet + Yeniden adlandฤฑr + Parรงa ekle + Ekle (%1$d) + Parรงalarฤฑ kaldฤฑr + Koleksiyonu sil + %1$s silinsin mi? + Parรงalar cihazฤฑnda kalฤฑr. Yalnฤฑzca koleksiyon kaldฤฑrฤฑlฤฑr. + Seรง + Tรผmรผnรผ seรง + Tรผm seรงimleri kaldฤฑr + %1$d seรงildi + Koleksiyona ekle + Favorilere ekle + Koleksiyondan kaldฤฑr + Parรงa ara + Albรผm sฤฑrasฤฑ + ร–nce en uzun + ร–nce en kฤฑsa + Parรงalar + Perde + Sฤฑfฤฑrla + SessizliฤŸi atla + Uyku zamanlayฤฑcฤฑsฤฑ + %1$d dk + Parรงanฤฑn sonu + %1$s kaldฤฑ + Ekolayzฤฑr + Bas gรผรงlendirme + Ekolayzฤฑr bu cihazda kullanฤฑlamฤฑyor + Oyun iรงinde etkinleลŸtir + Oyun รงalฤฑลŸฤฑrken oyun mรผziฤŸi รงalmaya devam etsin + Henรผz oyun mรผziฤŸi yรผklenmedi. + Oyun mรผziklerinde ara + Oyun mรผziฤŸi klasรถrรผ ekle + Bu klasรถrde ses dosyasฤฑ yok + Toplam sรผre + %1$d parรงa / %2$s + Disk %1$s + KarฤฑลŸtฤฑr + ร–nceki + Oynat + Duraklat + Sonraki + Tekrar kapalฤฑ + Tรผmรผnรผ tekrarla + Birini tekrarla + Ses dรผzeyi + Bu oyun mรผziฤŸinde ses dosyasฤฑ yok diff --git a/app/src/main/res/values-uk/strings.xml b/app/src/main/res/values-uk/strings.xml index 79eb4138e0..de74d56817 100644 --- a/app/src/main/res/values-uk/strings.xml +++ b/app/src/main/res/values-uk/strings.xml @@ -28,6 +28,8 @@ ะŸั€ะธะทัƒะฟะธะฝะธั‚ะธ ะทะฐั€ะฐะท ะ—ะฐะฒะตั€ัˆะธั‚ะธ ัะตะฐะฝั ะ“ะตะฝะตั€ะฐั†ั–ั ะบะฐะดั€ั–ะฒ + ะะฐะปะฐัˆั‚ัƒะฒะฐะฝะฝั ั†ั–ั”ั— ะณั€ะธ + ะขะธะฟะพะฒั– ะฝะฐะปะฐัˆั‚ัƒะฒะฐะฝะฝั ะ’ะธะฑะตั€ั–ั‚ัŒ ั€ะตะถะธะผ ะณะตะฝะตั€ะฐั†ั–ั— ะบะฐะดั€ั–ะฒ ะ’ะธะผะบ. DD-FG %1$dร— @@ -482,6 +484,7 @@ ะฃะฒั–ะผะบะฝะตะฝะพ ะ—ะฐะฟัƒัะบะฐั”ั‚ัŒัั ะทั– Steam ะ—ะฐะฟัƒัะบะฐั”ั‚ัŒัั ะฑะตะท Steam + ะ ะพะทะดั–ะปัŒะฝะฐ ะทะดะฐั‚ะฝั–ัั‚ัŒ ะณั€ะธ ะะฐะปะฐัˆั‚ัƒะฒะฐะฝะฝั ะะฐะปะฐัˆั‚ัƒะฒะฐะฝะฝั %1$s ะ—ะฐ ะทะฐะผะพะฒั‡ัƒะฒะฐะฝะฝัะผ @@ -2239,7 +2242,6 @@ ะœะฐะณะฐะทะธะฝะธ Steam ะ’ะปะฐัะฝะฐ - ะœะฐะณะฐะทะธะฝะธ ะ ั–ะฒะตะฝัŒ ัˆะฒะธะดะบะพัั‚ั– ะทะฐะฒะฐะฝั‚ะฐะถะตะฝะฝั ะ—ะฑะฐะปะฐะฝัะพะฒะฐะฝะธะน ะจะฒะธะดะบะธะน @@ -2285,6 +2287,7 @@ ะŸะตั€ะตั€ะฒะฐะฝะพ ะ’ัั‚ะฐะฝะพะฒะธั‚ะธ ยท %1$s ะžั‚ั€ะธะผะฐั‚ะธ ะฑะตะทะบะพัˆั‚ะพะฒะฝะพ + ะ”ะพะดะฐะฒะฐะฝะฝั ะดะพ ะฑั–ะฑะปั–ะพั‚ะตะบะธโ€ฆ ะŸะตั€ะตะณะปัะฝัƒั‚ะธ ะฝะฐ %1$s ะšัƒะฟะธั‚ะธ ยท %1$s ะ’ัั‚ะฐะฝะพะฒะปะตะฝะพ @@ -2619,7 +2622,9 @@ %1$s ยท ะฟะพั‚ั€ั–ะฑะตะฝ ะฟะตั€ะตะทะฐะฟัƒัะบ ะฆะตะน ะฟั€ะธัั‚ั€ั–ะน ะ’ะธะดะฐะปะธั‚ะธ %1$s? - ะ”ั–ะฐะณะฝะพัั‚ะธะบะฐ + ะ ะพะทั€ะพะฑะฝะธะบ + ะ’ะพะดัะฝะธะน ะทะฝะฐะบ ั–ะท ะผั–ั‚ะบะพัŽ ะทะฑั–ั€ะบะธ + ะŸะพะบะฐะทัƒะฒะฐั‚ะธ ะฝะฐ ะตะบั€ะฐะฝั– ะผั–ั‚ะบัƒ ั‚ะตัั‚ะพะฒะพั— ะทะฑั–ั€ะบะธ ะฐะฑะพ ะทะฑั–ั€ะบะธ Lab. ะฃะฒั–ะผะบะฝะตะฝะพ ะทะฐ ะทะฐะผะพะฒั‡ัƒะฒะฐะฝะฝัะผ. ะ“ะพั‚ะพะฒะพ ะดะพ ะณั€ะธ ะฉะต ะฝะต ะณะพั‚ะพะฒะพ ะดะพ ะณั€ะธ ัะตั€ะตะดะพะฒะธั‰ะต %1$s @@ -3618,6 +3623,25 @@ ะŸะตั€ะตะผั–ัั‚ะธั‚ะธ ะฟั–ะทะฝั–ัˆะต ะะฐะปะฐัˆั‚ัƒะฒะฐะฝะฝั ะฒั–ะดะถะตั‚ะฐ ะ’ะธะปัƒั‡ะธั‚ะธ ะฒั–ะดะถะตั‚ + ะ’ะธะณะปัะด + ะะฐะฑั–ั€ ะทะฝะฐั‡ะบั–ะฒ + ะฏะบ ัƒ ัะธัั‚ะตะผั– + ะคะพะฝ ะบะพะปัŒะพั€ัƒ ะทะฐัั‚ะพััƒะฝะบัƒ + ะ ะพะทะผั–ั€ ะทะฝะฐั‡ะบั–ะฒ + ะœะฐะปั– + ะกะตั€ะตะดะฝั– + ะ’ะตะปะธะบั– + ะกั…ะพะฒะฐั‚ะธ ะฝะฐะทะฒะธ ะทะฐัั‚ะพััƒะฝะบั–ะฒ + ะ’ั–ะดัั‚ัƒะฟะธ + ะ’ัƒะทัŒะบั– + ะกะตั€ะตะดะฝั– + ะจะธั€ะพะบั– + ะ—ะผั–ะฝะธั‚ะธ ะทะฝะฐั‡ะพะบ + ะกะบะธะฝัƒั‚ะธ ะทะฝะฐั‡ะพะบ + ะŸะพัˆัƒะบ ะทะฝะฐั‡ะบั–ะฒ + ะ—ะฐะฒะฐะฝั‚ะฐะถะตะฝะฝั ะทะฝะฐั‡ะบั–ะฒโ€ฆ + ะ—ะฝะฐั‡ะบั–ะฒ ะฝะต ะทะฝะฐะนะดะตะฝะพ. + ะ’ะปะฐัะฝั– ะทะฝะฐั‡ะบะธ ะ”ะพะดะฐั‚ะธ ะดะพ ะฟะฐะฟะบะธ ะะพะฒะฐ ะฟะฐะฟะบะฐ ะ’ะธะปัƒั‡ะธั‚ะธ ะท ะฟะฐะฟะบะธ @@ -3736,4 +3760,66 @@ ะ‘ะฐะณั€ัะฝะธะน ัะฝั–ะณ + ะกะฐัƒะฝะดั‚ั€ะตะบะธ + ะœัƒะทะธะบะฐ + ะŸะฐั€ะฐะผะตั‚ั€ะธ ะฒั–ะดั‚ะฒะพั€ะตะฝะฝั + ะฃะปัŽะฑะปะตะฝะต + ะšะพะปะตะบั†ั–ั— + ะšะพะปะตะบั†ั–ะน ั‰ะต ะฝะตะผะฐั”. ะขะพั€ะบะฝั–ั‚ัŒัั ะทะฝะฐั‡ะบะฐ ะทะฐะบะปะฐะดะบะธ, ั‰ะพะฑ ัั‚ะฒะพั€ะธั‚ะธ. + ะ—ะฑะตั€ะตะถะตะฝะพ + ะกั‚ะฒะพั€ะธั‚ะธ ะบะพะปะตะบั†ั–ัŽ + ะฃะฟะพั€ัะดะบัƒะนั‚ะต ัะฒะพั— ะทะฑะตั€ะตะถะตะฝั– ั‚ั€ะตะบะธ + ะะพะฒะฐ + ะกั‚ะฒะพั€ะธั‚ะธ + ะะฐะทะฒะฐ ะบะพะปะตะบั†ั–ั— + ะ’ะฒะตะดั–ั‚ัŒ ะฝะฐะทะฒัƒ, ัะบัƒ ะฝะต ะฒะธะบะพั€ะธัั‚ะพะฒัƒั” ะถะพะดะฝะฐ ั–ะฝัˆะฐ ะบะพะปะตะบั†ั–ั + ะšะตั€ัƒะฒะฐั‚ะธ + ะŸะตั€ะตะนะผะตะฝัƒะฒะฐั‚ะธ + ะ”ะพะดะฐั‚ะธ ั‚ั€ะตะบะธ + ะ”ะพะดะฐั‚ะธ (%1$d) + ะ’ะธะปัƒั‡ะธั‚ะธ ั‚ั€ะตะบะธ + ะ’ะธะดะฐะปะธั‚ะธ ะบะพะปะตะบั†ั–ัŽ + ะ’ะธะดะฐะปะธั‚ะธ %1$s? + ะขั€ะตะบะธ ะทะฐะปะธัˆะฐัŽั‚ัŒัั ะฝะฐ ะฒะฐัˆะพะผัƒ ะฟั€ะธัั‚ั€ะพั—. ะ‘ัƒะดะต ะฒะธะดะฐะปะตะฝะพ ะปะธัˆะต ะบะพะปะตะบั†ั–ัŽ. + ะ’ะธะฑั€ะฐั‚ะธ + ะ’ะธะฑั€ะฐั‚ะธ ะฒัะต + ะกะบะฐััƒะฒะฐั‚ะธ ะฒะธะฑั–ั€ + ะ’ะธะฑั€ะฐะฝะพ: %1$d + ะ”ะพะดะฐั‚ะธ ะดะพ ะบะพะปะตะบั†ั–ั— + ะ”ะพะดะฐั‚ะธ ะดะพ ัƒะปัŽะฑะปะตะฝะพะณะพ + ะ’ะธะปัƒั‡ะธั‚ะธ ะท ะบะพะปะตะบั†ั–ั— + ะŸะพัˆัƒะบ ั‚ั€ะตะบั–ะฒ + ะŸะพั€ัะดะพะบ ะฒ ะฐะปัŒะฑะพะผั– + ะกะฟะพั‡ะฐั‚ะบัƒ ะฝะฐะนะดะพะฒัˆั– + ะกะฟะพั‡ะฐั‚ะบัƒ ะฝะฐะนะบะพั€ะพั‚ัˆั– + ะขั€ะตะบะธ + ะ’ะธัะพั‚ะฐ ั‚ะพะฝัƒ + ะกะบะธะฝัƒั‚ะธ + ะŸั€ะพะฟัƒัะบะฐั‚ะธ ั‚ะธัˆัƒ + ะขะฐะนะผะตั€ ัะฝัƒ + %1$d ั…ะฒ + ะšั–ะฝะตั†ัŒ ั‚ั€ะตะบัƒ + ะ—ะฐะปะธัˆะธะปะพััŒ %1$s + ะ•ะบะฒะฐะปะฐะนะทะตั€ + ะŸั–ะดัะธะปะตะฝะฝั ะฑะฐัั–ะฒ + ะ•ะบะฒะฐะปะฐะนะทะตั€ ะฝะตะดะพัั‚ัƒะฟะฝะธะน ะฝะฐ ั†ัŒะพะผัƒ ะฟั€ะธัั‚ั€ะพั— + ะ’ะผะธะบะฐั‚ะธ ะฒ ะณั€ั– + ะ’ั–ะดั‚ะฒะพั€ัŽะฒะฐั‚ะธ ัะฐัƒะฝะดั‚ั€ะตะบ, ะฟะพะบะธ ะทะฐะฟัƒั‰ะตะฝะพ ะณั€ัƒ + ะกะฐัƒะฝะดั‚ั€ะตะบะธ ั‰ะต ะฝะต ะฒัั‚ะฐะฝะพะฒะปะตะฝะพ. + ะŸะพัˆัƒะบ ัะฐัƒะฝะดั‚ั€ะตะบั–ะฒ + ะ”ะพะดะฐั‚ะธ ั‚ะตะบัƒ ัะฐัƒะฝะดั‚ั€ะตะบัƒ + ะฃ ั†ั–ะน ั‚ะตั†ั– ะฝะตะผะฐั” ะฐัƒะดั–ะพั„ะฐะนะปั–ะฒ + ะ—ะฐะณะฐะปัŒะฝะฐ ั‚ั€ะธะฒะฐะปั–ัั‚ัŒ + ะขั€ะตะบั–ะฒ: %1$d / %2$s + ะ”ะธัะบ %1$s + ะŸะตั€ะตะผั–ัˆะฐั‚ะธ + ะะฐะทะฐะด + ะ’ั–ะดั‚ะฒะพั€ะธั‚ะธ + ะŸะฐัƒะทะฐ + ะ”ะฐะปั– + ะŸะพะฒั‚ะพั€ ะฒะธะผะบะฝะตะฝะพ + ะŸะพะฒั‚ะพั€ัŽะฒะฐั‚ะธ ะฒัะต + ะŸะพะฒั‚ะพั€ัŽะฒะฐั‚ะธ ะพะดะธะฝ + ะ“ัƒั‡ะฝั–ัั‚ัŒ + ะฃ ั†ัŒะพะผัƒ ัะฐัƒะฝะดั‚ั€ะตะบัƒ ะฝะตะผะฐั” ะฐัƒะดั–ะพั„ะฐะนะปั–ะฒ diff --git a/app/src/main/res/values-vi/strings.xml b/app/src/main/res/values-vi/strings.xml index 537168797a..05c9403f13 100644 --- a/app/src/main/res/values-vi/strings.xml +++ b/app/src/main/res/values-vi/strings.xml @@ -28,6 +28,8 @@ Tแบกm dแปซng ngay Dแปซng phiรชn Tแบกo khung hรฌnh + Cร i ฤ‘แบทt cho trรฒ chฦกi nร y + Cร i ฤ‘แบทt mแบทc ฤ‘แป‹nh Chแปn chแบฟ ฤ‘แป™ tแบกo khung hรฌnh Tแบฏt DD-FG %1$dร— @@ -476,6 +478,7 @@ Bแบญt KhแปŸi ฤ‘แป™ng cรนng Steam KhแปŸi ฤ‘แป™ng khรดng cแบงn Steam + ฤแป™ phรขn giแบฃi trรฒ chฦกi Thiแบฟt lแบญp Thiแบฟt lแบญp %1$s Mแบทc ฤ‘แป‹nh @@ -2164,7 +2167,6 @@ Cแปญa hร ng game Steam Tรนy chแป‰nh - Cแปญa hร ng Mแปฉc tแป‘c ฤ‘แป™ tแบฃi Cรขn bแบฑng Nhanh @@ -2210,6 +2212,7 @@ Bแป‹ giรกn ฤ‘oแบกn Cร i ยท %1$s Lแบฅy miแป…n phรญ + ฤang thรชm vร o thฦฐ viแป‡nโ€ฆ Xem trรชn %1$s Mua ยท %1$s ฤรฃ cร i @@ -2538,7 +2541,9 @@ %1$s ยท cแบงn khแปŸi ฤ‘แป™ng lแบกi Thiแบฟt bแป‹ nร y Xรณa %1$s? - Chแบฉn ฤ‘oรกn + Nhร  phรกt triแปƒn + Hรฌnh mแป nhรฃn bแบฃn dแปฑng + Hiแปƒn thแป‹ nhรฃn bแบฃn dแปฑng thแปญ nghiแป‡m hoแบทc Lab trรชn mร n hรฌnh. ฤฦฐแปฃc bแบญt theo mแบทc ฤ‘แป‹nh. Sแบตn sร ng ฤ‘แปƒ chฦกi Chฦฐa sแบตn sร ng ฤ‘แปƒ chฦกi runtime %1$s @@ -3513,6 +3518,25 @@ Chuyแปƒn ra sau Cร i ฤ‘แบทt tiแป‡n รญch Xรณa tiแป‡n รญch + Giao diแป‡n + Gรณi biแปƒu tฦฐแปฃng + Theo hแป‡ thแป‘ng + Nแปn theo mร u แปฉng dแปฅng + Kรญch thฦฐแป›c biแปƒu tฦฐแปฃng + Nhแป + Vแปซa + Lแป›n + แบจn tรชn แปฉng dแปฅng + Khoแบฃng cรกch + Hแบนp + Vแปซa + Rแป™ng + ฤแป•i biแปƒu tฦฐแปฃng + ฤแบทt lแบกi biแปƒu tฦฐแปฃng + Tรฌm biแปƒu tฦฐแปฃng + ฤang tแบฃi biแปƒu tฦฐแปฃngโ€ฆ + Khรดng tรฌm thแบฅy biแปƒu tฦฐแปฃng. + Biแปƒu tฦฐแปฃng tรนy chแป‰nh Thรชm vร o thฦฐ mแปฅc Thฦฐ mแปฅc mแป›i Xรณa khแปi thฦฐ mแปฅc @@ -3628,4 +3652,66 @@ Tuyแบฟt ฤ‘แป thแบซm + Nhแบกc nแปn + Nhแบกc + Tรนy chแปn phรกt + Yรชu thรญch + Bแป™ sฦฐu tแบญp + Chฦฐa cรณ bแป™ sฦฐu tแบญp nร o. Chแบกm vร o biแปƒu tฦฐแปฃng dแบฅu trang ฤ‘แปƒ tแบกo. + ฤรฃ lฦฐu + Tแบกo bแป™ sฦฐu tแบญp + Sแบฏp xแบฟp cรกc bร i ฤ‘รฃ lฦฐu + Mแป›i + Tแบกo + Tรชn bแป™ sฦฐu tแบญp + Nhแบญp tรชn chฦฐa ฤ‘ฦฐแปฃc bแป™ sฦฐu tแบญp nร o khรกc sแปญ dแปฅng + Quแบฃn lรฝ + ฤแป•i tรชn + Thรชm bร i hรกt + Thรชm (%1$d) + Xรณa bร i hรกt + Xรณa bแป™ sฦฐu tแบญp + Xรณa %1$s? + Cรกc bร i hรกt vแบซn cรฒn trรชn thiแบฟt bแป‹ cแปงa bแบกn. Chแป‰ bแป™ sฦฐu tแบญp bแป‹ xรณa. + Chแปn + Chแปn tแบฅt cแบฃ + Bแป chแปn tแบฅt cแบฃ + ฤรฃ chแปn %1$d + Thรชm vร o bแป™ sฦฐu tแบญp + Thรชm vร o yรชu thรญch + Xรณa khแปi bแป™ sฦฐu tแบญp + Tรฌm bร i hรกt + Thแปฉ tแปฑ album + Dร i nhแบฅt trฦฐแป›c + Ngแบฏn nhแบฅt trฦฐแป›c + Bร i hรกt + Cao ฤ‘แป™ + ฤแบทt lแบกi + Bแป qua khoแบฃng lแบทng + Hแบนn giแป ngแปง + %1$d phรบt + Hแบฟt bร i + Cรฒn %1$s + Bแป™ cรขn bแบฑng รขm + Tฤƒng รขm trแบงm + Thiแบฟt bแป‹ nร y khรดng cรณ bแป™ cรขn bแบฑng รขm + Bแบญt trong game + Tiแบฟp tแปฅc phรกt nhแบกc nแปn khi game ฤ‘ang chแบกy + Chฦฐa cรณ nhแบกc nแปn nร o ฤ‘ฦฐแปฃc cร i ฤ‘แบทt. + Tรฌm nhแบกc nแปn + Thรชm thฦฐ mแปฅc nhแบกc nแปn + Khรดng cรณ tแป‡p รขm thanh trong thฦฐ mแปฅc ฤ‘รณ + Tแป•ng thแปi lฦฐแปฃng + %1$d bร i / %2$s + ฤฤฉa %1$s + Phรกt ngแบซu nhiรชn + Trฦฐแป›c + Phรกt + Tแบกm dแปซng + Tiแบฟp + Tแบฏt lแบทp lแบกi + Lแบทp lแบกi tแบฅt cแบฃ + Lแบทp lแบกi mแป™t bร i + ร‚m lฦฐแปฃng + Khรดng cรณ tแป‡p รขm thanh trong nhแบกc nแปn nร y diff --git a/app/src/main/res/values-zh-rCN/strings.xml b/app/src/main/res/values-zh-rCN/strings.xml index 8f0ab9c57b..d775759045 100644 --- a/app/src/main/res/values-zh-rCN/strings.xml +++ b/app/src/main/res/values-zh-rCN/strings.xml @@ -28,6 +28,8 @@ ็ซ‹ๅณๆš‚ๅœ ๅœๆญขไผš่ฏ ๅธง็”Ÿๆˆ + ๆญคๆธธๆˆ็š„่ฎพ็ฝฎ + ้ป˜่ฎค่ฎพ็ฝฎ ้€‰ๆ‹ฉๅธง็”Ÿๆˆๆจกๅผ ๅ…ณ้—ญ DD-FG %1$dร— @@ -476,6 +478,7 @@ ๅผ€ ้š Steam ๅฏๅŠจ ไธ้€š่ฟ‡ Steam ๅฏๅŠจ + ๆธธๆˆๅˆ†่พจ็އ ่ฎพ็ฝฎ %1$s ่ฎพ็ฝฎ ้ป˜่ฎค @@ -2245,7 +2248,6 @@ ๆธธๆˆๅ•†ๅบ— Steam ่‡ชๅฎšไน‰ - ๆธธๆˆๅ•†ๅบ— ไธ‹่ฝฝ้€Ÿๅบฆๆกฃไฝ ๅ‡่กก ๅฟซ้€Ÿ @@ -2291,6 +2293,7 @@ ๅทฒไธญๆ–ญ ๅฎ‰่ฃ… ยท %1$s ๅ…่ดน้ข†ๅ– + ๆญฃๅœจๆทปๅŠ ๅˆฐๆธธๆˆๅบ“โ€ฆ ๅœจ %1$s ไธŠๆŸฅ็œ‹ ่ดญไนฐ ยท %1$s ๅทฒๅฎ‰่ฃ… @@ -2551,7 +2554,9 @@ ๅˆ†ๅˆซ่ฎพ็ฝฎ่ฟ่กŒๆ—ถ้ฉฑๅŠจๅ’Œๆ˜พ็คบ้ฉฑๅŠจ ไฝฟ็”จ %1$s๏ผŸ ็งป้™ค %1$s๏ผŸ - ่ฏŠๆ–ญ + ๅผ€ๅ‘่€… + ๆž„ๅปบๆ ‡็ญพๆฐดๅฐ + ๅœจๅฑๅน•ไธŠๆ˜พ็คบๆต‹่ฏ•็‰ˆๆˆ– Lab ๆž„ๅปบๆ ‡็ญพใ€‚้ป˜่ฎคๅฏ็”จใ€‚ ๅฏไปฅๆธธ็Žฉไบ† ๆš‚ๆ—ถ่ฟ˜ไธ่ƒฝๆธธ็Žฉ ่ฟ่กŒๆ—ถ %1$s @@ -3517,6 +3522,25 @@ ๅŽ็งป ๅพฎไปถ่ฎพ็ฝฎ ็งป้™คๅพฎไปถ + ๅค–่ง‚ + ๅ›พๆ ‡ๅŒ… + ็ณป็ปŸ้ป˜่ฎค + ไฝฟ็”จๅบ”็”จ้ขœ่‰ฒไฝœไธบ่ƒŒๆ™ฏ + ๅ›พๆ ‡ๅคงๅฐ + ๅฐ + ไธญ + ๅคง + ้š่—ๅบ”็”จๅ็งฐ + ้—ด่ท + ็ดงๅ‡‘ + ๆญฃๅธธ + ๅฎฝๆพ + ๆ›ดๆขๅ›พๆ ‡ + ้‡็ฝฎๅ›พๆ ‡ + ๆœ็ดขๅ›พๆ ‡ + ๆญฃๅœจๅŠ ่ฝฝๅ›พๆ ‡โ€ฆ + ๆœชๆ‰พๅˆฐๅ›พๆ ‡ใ€‚ + ่‡ชๅฎšไน‰ๅ›พๆ ‡ ๆทปๅŠ ๅˆฐๆ–‡ไปถๅคน ๆ–ฐๅปบๆ–‡ไปถๅคน ไปŽๆ–‡ไปถๅคนไธญ็งป้™ค @@ -3632,4 +3656,66 @@ ็Œฉ็บขไน‹้›ช + ๅŽŸๅฃฐ้Ÿณไน + ้Ÿณไน + ๆ’ญๆ”พ้€‰้กน + ๆ”ถ่— + ๅˆ้›† + ่ฟ˜ๆฒกๆœ‰ๅˆ้›†ใ€‚็‚นๆŒ‰ไนฆ็ญพๅ›พๆ ‡ๅณๅฏๅˆ›ๅปบใ€‚ + ๅทฒไฟๅญ˜ + ๅˆ›ๅปบๅˆ้›† + ๆ•ด็†ไฝ ็š„ๆ”ถ่— + ๆ–ฐๅปบ + ๅˆ›ๅปบ + ๅˆ้›†ๅ็งฐ + ่ฏท่พ“ๅ…ฅๆœช่ขซๅ…ถไป–ๅˆ้›†ไฝฟ็”จ็š„ๅ็งฐ + ็ฎก็† + ้‡ๅ‘ฝๅ + ๆทปๅŠ ๆ›ฒ็›ฎ + ๆทปๅŠ ๏ผˆ%1$d๏ผ‰ + ็งป้™คๆ›ฒ็›ฎ + ๅˆ ้™คๅˆ้›† + ๅˆ ้™ค %1$s๏ผŸ + ๆ›ฒ็›ฎไปไฟ็•™ๅœจไฝ ็š„่ฎพๅค‡ไธŠ๏ผŒๅชไผšๅˆ ้™คๅˆ้›†ใ€‚ + ้€‰ๆ‹ฉ + ๅ…จ้€‰ + ๅ–ๆถˆๅ…จ้€‰ + ๅทฒ้€‰ๆ‹ฉ %1$d ้กน + ๆทปๅŠ ๅˆฐๅˆ้›† + ๆทปๅŠ ๅˆฐๆ”ถ่— + ไปŽๅˆ้›†ไธญ็งป้™ค + ๆœ็ดขๆ›ฒ็›ฎ + ไธ“่พ‘้กบๅบ + ๆœ€้•ฟไผ˜ๅ…ˆ + ๆœ€็Ÿญไผ˜ๅ…ˆ + ๆ›ฒ็›ฎ + ้Ÿณ่ฐƒ + ้‡็ฝฎ + ่ทณ่ฟ‡้™้Ÿณ + ็ก็œ ๅฎšๆ—ถ + %1$d ๅˆ†้’Ÿ + ๆ›ฒ็›ฎ็ป“ๆŸ + ๅ‰ฉไฝ™ %1$s + ๅ‡่กกๅ™จ + ไฝŽ้Ÿณๅขžๅผบ + ๆญค่ฎพๅค‡ไธๆ”ฏๆŒๅ‡่กกๅ™จ + ๅœจๆธธๆˆไธญๅฏ็”จ + ๆธธๆˆ่ฟ่กŒๆ—ถ็ปง็ปญๆ’ญๆ”พๅŽŸๅฃฐ้Ÿณไน + ๅฐšๆœชๅฎ‰่ฃ…ไปปไฝ•ๅŽŸๅฃฐ้Ÿณไนใ€‚ + ๆœ็ดขๅŽŸๅฃฐ้Ÿณไน + ๆทปๅŠ ๅŽŸๅฃฐ้Ÿณไนๆ–‡ไปถๅคน + ่ฏฅๆ–‡ไปถๅคนไธญๆฒกๆœ‰้Ÿณ้ข‘ๆ–‡ไปถ + ๆ€ปๆ—ถ้•ฟ + %1$d ้ฆ–ๆ›ฒ็›ฎ / %2$s + ็ฌฌ %1$s ๅผ  + ้šๆœบๆ’ญๆ”พ + ไธŠไธ€้ฆ– + ๆ’ญๆ”พ + ๆš‚ๅœ + ไธ‹ไธ€้ฆ– + ๅ…ณ้—ญ้‡ๅค + ๅ…จ้ƒจ้‡ๅค + ๅ•ๆ›ฒ้‡ๅค + ้Ÿณ้‡ + ๆญคๅŽŸๅฃฐ้Ÿณไนไธญๆฒกๆœ‰้Ÿณ้ข‘ๆ–‡ไปถ diff --git a/app/src/main/res/values-zh-rHK/strings.xml b/app/src/main/res/values-zh-rHK/strings.xml index b8d2bf0846..a7b17a7383 100644 --- a/app/src/main/res/values-zh-rHK/strings.xml +++ b/app/src/main/res/values-zh-rHK/strings.xml @@ -28,6 +28,8 @@ ็ซ‹ๅณๆšซๅœ ็ตๆŸๆœƒ่ฉฑ ๅน€็”Ÿๆˆ + ๆญค้Šๆˆฒ็š„่จญๅฎš + ้ ่จญ่จญๅฎš ้ธๆ“‡ๅน€็”Ÿๆˆๆจกๅผ ้—œ้–‰ DD-FG %1$dร— @@ -476,6 +478,7 @@ ้–‹ ้šจ Steam ๅ•Ÿๅ‹• ไธ็ถ“ Steam ๅ•Ÿๅ‹• + ้Šๆˆฒ่งฃๅƒๅบฆ ่จญๅฎš %1$s ่จญๅฎš ้ ่จญ @@ -2164,7 +2167,6 @@ ๅ•†ๅบ— Steam ่‡ช่จ‚ - ๅ•†ๅบ— ไธ‹่ผ‰้€Ÿๅบฆ็ญ‰็ดš ๅนณ่กก ๅฟซ้€Ÿ @@ -2210,6 +2212,7 @@ ๅทฒไธญๆ–ท ๅฎ‰่ฃ ยท %1$s ๅ…่ฒป้ ˜ๅ– + ๆญฃๅœจๅŠ ๅ…ฅ้Šๆˆฒๅบซโ€ฆ ๅœจ %1$s ๆŸฅ็œ‹ ่ณผ่ฒท ยท %1$s ๅทฒๅฎ‰่ฃ @@ -2538,7 +2541,9 @@ %1$s ยท ็ญ‰ๅพ…้‡ๆ–ฐๅ•Ÿๅ‹• ๆญค่ฃ็ฝฎ ็งป้™ค %1$s๏ผŸ - ่จบๆ–ท + ้–‹็™ผไบบๅ“ก + ๅปบ็ฝฎๆจ™็ฑคๆตฎๆฐดๅฐ + ๅœจ็•ซ้ขไธŠ้กฏ็คบๆธฌ่ฉฆ็‰ˆๆˆ– Lab ๅปบ็ฝฎๆจ™็ฑคใ€‚้ ่จญๅ•Ÿ็”จใ€‚ ๅฏไปฅ้–‹ๅง‹้Šๆˆฒ ๅฐšๆœชๅฏไปฅ้–‹ๅง‹้Šๆˆฒ ้‹่กŒ็’ฐๅขƒ %1$s @@ -3513,6 +3518,25 @@ ๅ‘ๅพŒ็งป ๅฐๅทฅๅ…ท่จญๅฎš ็งป้™คๅฐๅทฅๅ…ท + ๅค–่ง€ + ๅœ–็คบๅŒ… + ็ณป็ตฑ้ ่จญ + ไฝฟ็”จๆ‡‰็”จ็จ‹ๅผ้ก่‰ฒไฝœ็‚บ่ƒŒๆ™ฏ + ๅœ–็คบๅคงๅฐ + ๅฐ + ไธญ + ๅคง + ้šฑ่—ๆ‡‰็”จ็จ‹ๅผๅ็จฑ + ้–“่ท + ็ทŠๅฏ† + ๆญฃๅธธ + ๅฏฌ้ฌ† + ๆ›ดๆ”นๅœ–็คบ + ้‡่จญๅœ–็คบ + ๆœๅฐ‹ๅœ–็คบ + ๆญฃๅœจ่ผ‰ๅ…ฅๅœ–็คบโ€ฆ + ๆ‰พไธๅˆฐๅœ–็คบใ€‚ + ่‡ช่จ‚ๅœ–็คบ ๅŠ ๅ…ฅ่ณ‡ๆ–™ๅคพ ๆ–ฐ่ณ‡ๆ–™ๅคพ ๅพž่ณ‡ๆ–™ๅคพ็งป้™ค @@ -3631,4 +3655,66 @@ ็ท‹็ด…ไน‹้›ช + ๅŽŸ่ฒๅธถ + ้Ÿณๆจ‚ + ๆ’ญๆ”พ้ธ้ … + ๆœ€ๆ„› + ๅˆ้›† + ๆšซๆ™‚ๆœชๆœ‰ๅˆ้›†ใ€‚้ปžๆŒ‰ๆ›ธ็ฑคๅœ–็คบๅณๅฏๅปบ็ซ‹ใ€‚ + ๅทฒๅ„ฒๅญ˜ + ๅปบ็ซ‹ๅˆ้›† + ๆ•ด็†ไฝ ็š„ๆ”ถ่— + ๆ–ฐๅขž + ๅปบ็ซ‹ + ๅˆ้›†ๅ็จฑ + ่ซ‹่ผธๅ…ฅๆœช่ขซๅ…ถไป–ๅˆ้›†ไฝฟ็”จ็š„ๅ็จฑ + ็ฎก็† + ้‡ๆ–ฐๅ‘ฝๅ + ๆ–ฐๅขžๆ›ฒ็›ฎ + ๆ–ฐๅขž๏ผˆ%1$d๏ผ‰ + ็งป้™คๆ›ฒ็›ฎ + ๅˆช้™คๅˆ้›† + ๅˆช้™ค %1$s๏ผŸ + ๆ›ฒ็›ฎไปๆœƒไฟ็•™ๅœจไฝ ็š„่ฃ็ฝฎไธŠ๏ผŒๅชๆœƒๅˆช้™คๅˆ้›†ใ€‚ + ้ธๅ– + ๅ…จ้ธ + ๅ–ๆถˆๅ…จ้ธ + ๅทฒ้ธๅ– %1$d ้ … + ๅŠ ๅ…ฅๅˆ้›† + ๅŠ ๅ…ฅๆœ€ๆ„› + ๅพžๅˆ้›†ไธญ็งป้™ค + ๆœๅฐ‹ๆ›ฒ็›ฎ + ๅฐˆ่ผฏ้ †ๅบ + ๆœ€้•ทๅ„ชๅ…ˆ + ๆœ€็Ÿญๅ„ชๅ…ˆ + ๆ›ฒ็›ฎ + ้Ÿณ่ชฟ + ้‡่จญ + ็•ฅ้Ž้œ้Ÿณ + ็ก็œ ่จˆๆ™‚ๅ™จ + %1$d ๅˆ†้˜ + ๆ›ฒ็›ฎ็ตๆŸ + ๅ‰ฉ้ค˜ %1$s + ็ญ‰ๅŒ–ๅ™จ + ้‡ไฝŽ้Ÿณๅขžๅผท + ๆญค่ฃ็ฝฎไธๆ”ฏๆด็ญ‰ๅŒ–ๅ™จ + ๅœจ้Šๆˆฒไธญๅ•Ÿ็”จ + ้Šๆˆฒ้‹่กŒๆ™‚็นผ็บŒๆ’ญๆ”พๅŽŸ่ฒๅธถ + ๅฐšๆœชๅฎ‰่ฃไปปไฝ•ๅŽŸ่ฒๅธถใ€‚ + ๆœๅฐ‹ๅŽŸ่ฒๅธถ + ๆ–ฐๅขžๅŽŸ่ฒๅธถ่ณ‡ๆ–™ๅคพ + ่ฉฒ่ณ‡ๆ–™ๅคพไธญๆฒ’ๆœ‰้Ÿณ่จŠๆช”ๆกˆ + ็ธฝ้•ทๅบฆ + %1$d ้ฆ–ๆ›ฒ็›ฎ / %2$s + ็ฌฌ %1$s ๅผต + ้šจๆฉŸๆ’ญๆ”พ + ไธŠไธ€้ฆ– + ๆ’ญๆ”พ + ๆšซๅœ + ไธ‹ไธ€้ฆ– + ้—œ้–‰้‡่ค‡ + ๅ…จ้ƒจ้‡่ค‡ + ๅ–ฎๆ›ฒ้‡่ค‡ + ้Ÿณ้‡ + ๆญคๅŽŸ่ฒๅธถไธญๆฒ’ๆœ‰้Ÿณ่จŠๆช”ๆกˆ diff --git a/app/src/main/res/values-zh-rTW/strings.xml b/app/src/main/res/values-zh-rTW/strings.xml index 8b883d4a89..a73fbfecb1 100644 --- a/app/src/main/res/values-zh-rTW/strings.xml +++ b/app/src/main/res/values-zh-rTW/strings.xml @@ -28,6 +28,8 @@ ็ซ‹ๅณๆšซๅœ ็ตๆŸๆญคๅทฅไฝœ้šŽๆฎต ๅฝฑๆ ผ็”Ÿๆˆ + ๆญค้Šๆˆฒ็š„่จญๅฎš + ้ ่จญ่จญๅฎš ่ซ‹้ธๆ“‡ไฝ ่ฆไฝฟ็”จ็š„ๅฝฑๆ ผ็”Ÿๆˆๆจกๅผ ้—œ้–‰ DD-FG %1$dร— @@ -476,6 +478,7 @@ ้–‹ ้šจ Steam ๅ•Ÿๅ‹• ไธ็ถ“ Steam ๅ•Ÿๅ‹• + ้Šๆˆฒ่งฃๆžๅบฆ ่จญๅฎš %1$s ่จญๅฎš ้ ่จญ @@ -2164,7 +2167,6 @@ ้Šๆˆฒๅ•†ๅบ— Steam ่‡ช่จ‚ - ้Šๆˆฒๅ•†ๅบ— ไธ‹่ผ‰้€Ÿๅบฆ็ญ‰็ดš ๅนณ่กก ๅฟซ้€Ÿ @@ -2210,6 +2212,7 @@ ๅทฒไธญๆ–ท ๅฎ‰่ฃ ยท %1$s ๅ…่ฒปๅ–ๅพ— + ๆญฃๅœจๅŠ ๅ…ฅๆ”ถ่—ๅบซโ€ฆ ๅœจ %1$s ๆชข่ฆ– ่ณผ่ฒท ยท %1$s ๅทฒๅฎ‰่ฃ @@ -2538,7 +2541,9 @@ %1$s ยท ็ญ‰ๅพ…้‡ๆ–ฐๅ•Ÿๅ‹• ๆญค่ฃ็ฝฎ ่ฆ็งป้™ค %1$s ๅ—Ž๏ผŸ - ่จบๆ–ท + ้–‹็™ผไบบๅ“ก + ็ต„ๅปบๆจ™็ฑคๆตฎๆฐดๅฐ + ๅœจ็•ซ้ขไธŠ้กฏ็คบๆธฌ่ฉฆ็‰ˆๆˆ– Lab ็ต„ๅปบๆจ™็ฑคใ€‚้ ่จญๅ•Ÿ็”จใ€‚ ๅทฒๅฏ้–‹ๅง‹้Šๆˆฒ ๅฐšๆœชๆบ–ๅ‚™ๅฅฝ้–‹ๅง‹้Šๆˆฒ ๅŸท่กŒ็’ฐๅขƒ %1$s @@ -3513,6 +3518,25 @@ ๅพ€ๅพŒ็งป ๅฐๅทฅๅ…ท่จญๅฎš ็งป้™คๅฐๅทฅๅ…ท + ๅค–่ง€ + ๅœ–็คบๅฅ—ไปถ + ็ณป็ตฑ้ ่จญ + ไฝฟ็”จๆ‡‰็”จ็จ‹ๅผ้ก่‰ฒไฝœ็‚บ่ƒŒๆ™ฏ + ๅœ–็คบๅคงๅฐ + ๅฐ + ไธญ + ๅคง + ้šฑ่—ๆ‡‰็”จ็จ‹ๅผๅ็จฑ + ้–“่ท + ็ทŠๅฏ† + ๆญฃๅธธ + ๅฏฌ้ฌ† + ่ฎŠๆ›ดๅœ–็คบ + ้‡่จญๅœ–็คบ + ๆœๅฐ‹ๅœ–็คบ + ๆญฃๅœจ่ผ‰ๅ…ฅๅœ–็คบโ€ฆ + ๆ‰พไธๅˆฐๅœ–็คบใ€‚ + ่‡ช่จ‚ๅœ–็คบ ๆ–ฐๅขž่‡ณ่ณ‡ๆ–™ๅคพ ๆ–ฐ่ณ‡ๆ–™ๅคพ ๅพž่ณ‡ๆ–™ๅคพ็งป้™ค @@ -3631,4 +3655,66 @@ ็ท‹็ด…ไน‹้›ช + ๅŽŸ่ฒๅธถ + ้Ÿณๆจ‚ + ๆ’ญๆ”พ้ธ้ … + ๆˆ‘็š„ๆœ€ๆ„› + ๅˆ้›† + ๅฐš็„กๅˆ้›†ใ€‚้ปž้ธๆ›ธ็ฑคๅœ–็คบๅณๅฏๅปบ็ซ‹ใ€‚ + ๅทฒๅ„ฒๅญ˜ + ๅปบ็ซ‹ๅˆ้›† + ๆ•ด็†ไฝ ็š„ๆ”ถ่— + ๆ–ฐๅขž + ๅปบ็ซ‹ + ๅˆ้›†ๅ็จฑ + ่ซ‹่ผธๅ…ฅๆœช่ขซๅ…ถไป–ๅˆ้›†ไฝฟ็”จ็š„ๅ็จฑ + ็ฎก็† + ้‡ๆ–ฐๅ‘ฝๅ + ๆ–ฐๅขžๆ›ฒ็›ฎ + ๆ–ฐๅขž๏ผˆ%1$d๏ผ‰ + ็งป้™คๆ›ฒ็›ฎ + ๅˆช้™คๅˆ้›† + ๅˆช้™ค %1$s๏ผŸ + ๆ›ฒ็›ฎไปๆœƒไฟ็•™ๅœจไฝ ็š„่ฃ็ฝฎไธŠ๏ผŒๅชๆœƒๅˆช้™คๅˆ้›†ใ€‚ + ้ธๅ– + ๅ…จ้ธ + ๅ–ๆถˆๅ…จ้ธ + ๅทฒ้ธๅ– %1$d ้ … + ๅŠ ๅ…ฅๅˆ้›† + ๅŠ ๅ…ฅๆˆ‘็š„ๆœ€ๆ„› + ๅพžๅˆ้›†ไธญ็งป้™ค + ๆœๅฐ‹ๆ›ฒ็›ฎ + ๅฐˆ่ผฏ้ †ๅบ + ๆœ€้•ทๅ„ชๅ…ˆ + ๆœ€็Ÿญๅ„ชๅ…ˆ + ๆ›ฒ็›ฎ + ้Ÿณ่ชฟ + ้‡่จญ + ็•ฅ้Ž้œ้Ÿณ + ็ก็œ ่จˆๆ™‚ๅ™จ + %1$d ๅˆ†้˜ + ๆ›ฒ็›ฎ็ตๆŸ + ๅ‰ฉ้ค˜ %1$s + ็ญ‰ๅŒ–ๅ™จ + ้‡ไฝŽ้Ÿณๅขžๅผท + ๆญค่ฃ็ฝฎไธๆ”ฏๆด็ญ‰ๅŒ–ๅ™จ + ๅœจ้Šๆˆฒไธญๅ•Ÿ็”จ + ้ŠๆˆฒๅŸท่กŒๆ™‚็นผ็บŒๆ’ญๆ”พๅŽŸ่ฒๅธถ + ๅฐšๆœชๅฎ‰่ฃไปปไฝ•ๅŽŸ่ฒๅธถใ€‚ + ๆœๅฐ‹ๅŽŸ่ฒๅธถ + ๆ–ฐๅขžๅŽŸ่ฒๅธถ่ณ‡ๆ–™ๅคพ + ่ฉฒ่ณ‡ๆ–™ๅคพไธญๆฒ’ๆœ‰้Ÿณ่จŠๆช”ๆกˆ + ็ธฝ้•ทๅบฆ + %1$d ้ฆ–ๆ›ฒ็›ฎ / %2$s + ็ฌฌ %1$s ๅผต + ้šจๆฉŸๆ’ญๆ”พ + ไธŠไธ€้ฆ– + ๆ’ญๆ”พ + ๆšซๅœ + ไธ‹ไธ€้ฆ– + ้—œ้–‰้‡่ค‡ + ๅ…จ้ƒจ้‡่ค‡ + ๅ–ฎๆ›ฒ้‡่ค‡ + ้Ÿณ้‡ + ๆญคๅŽŸ่ฒๅธถไธญๆฒ’ๆœ‰้Ÿณ่จŠๆช”ๆกˆ diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 22ce0eaa18..fc37281213 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -55,6 +55,8 @@ Suspend now Stop session Frame generation + Settings for this game + Default settings Select the frame generation mode Off DD-FG %1$dร— @@ -526,6 +528,7 @@ On Starts with Steam Starts without Steam + Game resolution Settings %1$s Settings Default @@ -919,6 +922,8 @@ Saved after each session Enhanced diagnostics for next session Captures detailed logs for one session. May reduce performance and use more storage. Turns itself off when the session starts; review logs before sharing. + Build label watermark + Show the test or Lab build label on screen. On by default. Share diagnostic bundles Session and device Graphics @@ -980,6 +985,8 @@ Use as Home screen DroidDeck can be the Home app DroidDeck is never offered as a Home app + Home button opens + The page shown when DroidDeck is the Home app and you press Home In Add Games, set DroidDeck to Include Orientation Launcher orientation @@ -1188,6 +1195,29 @@ Attach Remove Default + Reasoning effort + Go + Revise + Nothing changed yet + Go ahead with the plan. + Send now + Message + More + Close + Latest + Working + Context + %1$s of %2$s + This conversation ยท %1$s + Usage shows after the first reply + %1$d-hour limit + %1$d-minute limit + Weekly limit + %1$d%% ยท resets %2$s + + %1$d file + %1$d files + Plan first Plan Proposes a plan without changing anything @@ -1359,6 +1389,25 @@ Move later Widget settings Remove widget + Appearance + Icon pack + System default + App color background + Icon size + Small + Medium + Large + Hide app names + Spacing + Tight + Normal + Roomy + Change icon + Reset icon + Search icons + Loading iconsโ€ฆ + No icons found. + Custom icons Add to folder New folder Remove from folder @@ -1521,6 +1570,14 @@ Setup Updates Trinkets + More + Edit tabs + Tabs + Shown + In More + Hidden + Move %1$s up + Move %1$s down %1$d%% Resume %1$s Shows up as /root/ROMs in each session. Internal storage is at /root/Storage. @@ -2537,7 +2594,6 @@ Stores Steam Custom - Stores Download speed tier Balanced Fast @@ -2583,6 +2639,7 @@ Interrupted Install ยท %1$s Get for free + Adding to libraryโ€ฆ View on %1$s Buy ยท %1$s Installed @@ -2640,6 +2697,13 @@ Sort Sidebar labels Show names under the sidebar icons. Turn off for a slimmer sidebar. + Agent pet + DeeDee floats over the launcher and games and shows what the agent is doing. + Over other apps + Let DeeDee float over every app and open its chat there + Allow + DeeDee + Chat with DeeDee Display Larger cards Smaller cards @@ -2935,7 +2999,7 @@ %1$s ยท restart pending This device Remove %1$s? - Diagnostics + Developer Smart glasses Display and head-tracking settings are shared across DroidDeck menus, games and desktop sessions. Connect smart glasses to change their display and tracking settings. Your saved settings are kept when you disconnect. @@ -3338,6 +3402,7 @@ VC++ and DirectX installers games ask for Runs Linux x86 games Steam tool + Steam downloads this for games that ship anti-cheat, even when it is off. Removing it stalls their install at 0% DroidDeck runs games without this runtime x86 Proton, which DroidDeck cannot run Default for every game @@ -3966,4 +4031,68 @@ Scarlet Snow White surfaces with red accents. + Soundtracks + Music + Playback options + Favorites + Collections + No collections yet. Tap the bookmark icon to create one. + Saved + Create a collection + Organise your saves + New + Create + Collection name + Enter a name that no other collection uses + Manage + Rename + Add tracks + Add (%1$d) + Remove tracks + Delete collection + Delete %1$s? + The tracks stay on your device. Only the collection is removed. + Select + Select all + Deselect all + %1$d selected + Add to collection + Add to favorites + Remove from collection + Search tracks + Album order + Longest first + Shortest first + Tracks + Pitch + Reset + Skip silence + Sleep timer + %1$d min + End of track + %1$s left + Equalizer + Bass boost + The equalizer is not available on this device + Music while playing + Keep the soundtrack playing while a game runs + No soundtracks installed yet. + Search soundtracks + Add a soundtrack folder + No audio files found in that folder + Total length + %1$d Tracks / %2$s + Disc %1$s + Shuffle + Previous + Play + Pause + Next + Repeat off + Repeat all + Repeat one + Volume + No audio files found in this soundtrack + Launch unavailable + No web browser is available to open this link. diff --git a/app/src/main/resources/ea/graphql/GetGameProductOfferIds.gql b/app/src/main/resources/ea/graphql/GetGameProductOfferIds.gql new file mode 100644 index 0000000000..9c1c1dbd5c --- /dev/null +++ b/app/src/main/resources/ea/graphql/GetGameProductOfferIds.gql @@ -0,0 +1,15 @@ +query GetGameProductOfferIds($slug: String!, $locale: Locale!, $overrideCountryCode: String!) { + game(slug: $slug, locale: $locale) { + id + isFreeToPlay + slug + lowestPriceGameProduct(availabilities: [ACQUIRABLE], overrideCountryCode: $overrideCountryCode) { + id + isFree + name + originOfferId + __typename + } + __typename + } +} diff --git a/app/src/main/resources/ea/graphql/grantEntitlement.gql b/app/src/main/resources/ea/graphql/grantEntitlement.gql new file mode 100644 index 0000000000..9871d7231f --- /dev/null +++ b/app/src/main/resources/ea/graphql/grantEntitlement.gql @@ -0,0 +1,23 @@ +mutation grantEntitlement($input: GrantEntitlementInput!) { + grantEntitlement(input: $input) { + success + entitledOfferIds + entitlementType + errors { + ... on GrantEntitlementOfferDoesNotExistError { + __typename + } + ... on GrantEntitlementNotQualifiedError { + __typename + } + ... on GrantEntitlementNotFreeOrNoAppropriateSubscriptionError { + __typename + } + ... on GrantEntitlementUpstreamConflictError { + __typename + } + __typename + } + __typename + } +} diff --git a/app/src/main/resources/rockstar/legacy-cipher.bin b/app/src/main/resources/rockstar/legacy-cipher.bin new file mode 100644 index 0000000000..b70beb43ed Binary files /dev/null and b/app/src/main/resources/rockstar/legacy-cipher.bin differ diff --git a/app/src/test/java/com/droiddeck/launcher/HomeIconsTest.kt b/app/src/test/java/com/droiddeck/launcher/HomeIconsTest.kt new file mode 100644 index 0000000000..fc3ba72d75 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/HomeIconsTest.kt @@ -0,0 +1,26 @@ +package com.droiddeck.launcher + +import com.droiddeck.launcher.ui.iconMatches +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test + +class HomeIconsTest { + @Test fun aChoiceSurvivesEncoding() { + val choice = HomeIcons.Choice("com.pack", "chrome_alt") + assertEquals("com.app/.Main#10" to choice, HomeIcons.decode(HomeIcons.encode("com.app/.Main#10", choice))) + } + + @Test fun aDamagedEntryIsDropped() { + assertNull(HomeIcons.decode("com.app/.Main")) + assertNull(HomeIcons.decode("com.app/.Main\t\tchrome")) + } + + @Test fun iconsNamedLikeTheAppComeFirst() { + assertEquals(listOf("google_chrome", "alarm", "zoom"), iconMatches(listOf("alarm", "google_chrome", "zoom"), "Chrome", "")) + } + + @Test fun aSearchIgnoresCaseAndSeparators() { + assertEquals(listOf("google_chrome"), iconMatches(listOf("alarm", "google_chrome"), "Chrome", "Google Ch")) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/IconPackTest.kt b/app/src/test/java/com/droiddeck/launcher/IconPackTest.kt new file mode 100644 index 0000000000..0c03ac3b7e --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/IconPackTest.kt @@ -0,0 +1,127 @@ +package com.droiddeck.launcher + +import android.graphics.Color +import android.util.Xml +import androidx.core.graphics.createBitmap +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +import org.robolectric.annotation.GraphicsMode +import java.io.StringReader + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [33]) +@GraphicsMode(GraphicsMode.Mode.NATIVE) +class IconPackTest { + private fun filter(xml: String) = IconPack.parse(Xml.newPullParser().also { it.setInput(StringReader(xml)) }) + + private fun parse(xml: String) = filter(xml).icons + + private fun plate(xml: String) = filter(xml).plate + + private fun solid(color: Int) = createBitmap(10, 10).also { it.eraseColor(color) } + + @Test fun plateTagsAreReadFromTheFilter() { + val xml = """ + + + + + + """ + assertEquals(IconPack.Plate("back", "mask", "upon", 0.75f), plate(xml)) + } + + @Test fun aPackWithoutPlateImagesHasNoPlateEvenWithAScale() { + assertNull(plate("""""")) + } + + @Test fun anInvalidScaleLeavesTheIconFullSize() { + assertEquals(1f, plate("""""")?.scale) + } + + @Test fun theMaskCutsTheIconWhereItIsOpaqueAndTheBackShowsThrough() { + val mask = createBitmap(10, 10).also { it.setPixel(0, 0, Color.BLACK) } + val out = IconPack.compose(solid(Color.RED), solid(Color.BLUE), mask, null, 1f) + assertEquals(Color.BLUE, out.getPixel(0, 0)) + assertEquals(Color.RED, out.getPixel(5, 5)) + } + + @Test fun theScaleShrinksTheIconOntoTheBack() { + val out = IconPack.compose(solid(Color.RED), solid(Color.BLUE), null, null, 0.5f) + assertEquals(Color.BLUE, out.getPixel(1, 1)) + assertEquals(Color.RED, out.getPixel(5, 5)) + } + + @Test fun anAppColorRepaintsTheBackInsideItsShape() { + val back = createBitmap(10, 10).also { it.setPixel(5, 5, Color.WHITE) } + val out = IconPack.compose(createBitmap(10, 10), back, null, null, 1f, Color.GREEN) + assertEquals(Color.GREEN, out.getPixel(5, 5)) + assertEquals(Color.TRANSPARENT, out.getPixel(0, 0)) + } + + @Test fun theUponImageDrawsOverEverything() { + val out = IconPack.compose(solid(Color.RED), solid(Color.BLUE), null, solid(Color.GREEN), 1f) + assertEquals(Color.GREEN, out.getPixel(5, 5)) + } + + @Test fun drawableXmlNamesAreDistinctAndInOrder() { + val xml = """""" + assertEquals(listOf("b", "a"), IconPack.parseNames(Xml.newPullParser().also { it.setInput(StringReader(xml)) })) + } + + @Test fun aClassNameStartingWithADotIsExpandedWithThePackage() { + assertEquals("com.example.app/com.example.app.Main", IconPack.componentKey("ComponentInfo{com.example.app/.Main}")) + } + + @Test fun entriesWithoutAUsableComponentOrDrawableAreSkipped() { + val icons = parse( + """ + + + + + + """, + ) + assertTrue(icons.toString(), icons.isEmpty()) + } + + @Test fun theFirstEntryForAComponentWins() { + val icons = parse( + """ + + + """, + ) + assertEquals("first", icons["com.example/com.example.Main"]) + } + + @Test fun aCalendarTriesTodaysIconBeforeItsStaticOne() { + val filter = filter( + """ + + + + """, + ) + assertEquals(listOf("calendar_7", "cal"), filter.names("com.example/com.example.Cal", 7)) + assertEquals(listOf("main"), filter.names("com.example/com.example.Main", 7)) + } + + @Test fun tagsThatAreNotItemsAreIgnored() { + val icons = parse( + """ + + + + + """, + ) + assertEquals(mapOf("com.example/com.example.Main" to "main"), icons) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/agent/AgentGuestPathTest.kt b/app/src/test/java/com/droiddeck/launcher/agent/AgentGuestPathTest.kt new file mode 100644 index 0000000000..794a0e95f4 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/agent/AgentGuestPathTest.kt @@ -0,0 +1,18 @@ +package com.droiddeck.launcher.agent + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +class AgentGuestPathTest { + private val dirs = AgentHost.GUEST_PATH.split(':') + + @Test fun includesTheSystemBinariesDpkgNeedsAsRoot() { + assertTrue(dirs.containsAll(listOf("/usr/local/sbin", "/usr/sbin", "/sbin"))) + } + + @Test fun keepsUserBinariesFirstAndTheStandardDirs() { + assertEquals("/root/.local/bin", dirs.first()) + assertTrue(dirs.containsAll(listOf("/usr/local/bin", "/usr/bin", "/bin"))) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/agent/AgentHostTest.kt b/app/src/test/java/com/droiddeck/launcher/agent/AgentHostTest.kt index 23a176c201..11ecd7aea8 100644 --- a/app/src/test/java/com/droiddeck/launcher/agent/AgentHostTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/agent/AgentHostTest.kt @@ -74,7 +74,8 @@ class AgentHostTest { } @Test fun claudeShowsWholeEditsAndTodos() { - assertEquals("a.kt\n\n- old\n\n+ new", ClaudeCode.fullInput("Edit", org.json.JSONObject("""{"file_path":"a.kt","old_string":"old","new_string":"new"}"""))) + assertEquals("a.kt\n-old\n+new", ClaudeCode.fullInput("Edit", org.json.JSONObject("""{"file_path":"a.kt","old_string":"old","new_string":"new"}"""))) + assertEquals("b.kt\n+one\n+two", ClaudeCode.fullInput("Write", org.json.JSONObject("""{"file_path":"b.kt","content":"one\ntwo"}"""))) assertEquals("[x] read\n[~] fix\n[ ] test", ClaudeCode.fullInput("TodoWrite", org.json.JSONObject( """{"todos":[{"content":"read","status":"completed"},{"content":"fix","status":"in_progress"},{"content":"test","status":"pending"}]}"""))) } @@ -131,6 +132,27 @@ class AgentHostTest { assertEquals("ls", shellCommand("ls")) } + @Test fun claudeCodeDefaultsToNoAttributionAndKeepsTheUsersChoice() { + val root = Files.createTempDirectory("rootfs").toFile() + val settings = File(root, "root/.claude/settings.json") + ClaudeCode.prepare(root) + val written = org.json.JSONObject(settings.readText()) + assertEquals(false, written.getBoolean("includeCoAuthoredBy")) + assertEquals("", written.getJSONObject("attribution").getString("commit")) + assertEquals("", written.getJSONObject("attribution").getString("pr")) + + settings.writeText("""{"includeCoAuthoredBy":true,"model":"opus"}""") + ClaudeCode.prepare(root) + val kept = org.json.JSONObject(settings.readText()) + assertEquals(true, kept.getBoolean("includeCoAuthoredBy")) + assertEquals("opus", kept.getString("model")) + assertTrue(kept.has("attribution")) + + settings.writeText("not json") + ClaudeCode.prepare(root) + assertEquals("not json", settings.readText()) + } + @Test fun aTurnWithoutAnEndWasInterrupted() { assertTrue(AgentHost.interrupted(listOf(Entry.Asked("hi"), Entry.Used("1", "Bash", "dd-lab-build")))) assertEquals(false, AgentHost.interrupted(listOf(Entry.Asked("hi"), Entry.Finished(null)))) @@ -143,6 +165,7 @@ class AgentHostTest { val written = listOf( Entry.Asked("hi", listOf("/root/x.png")), Entry.Said("hello"), Entry.Thought("hm"), Entry.Used("t1", "Read", "/root/x", "{}"), Entry.Result("t1", "contents", false), Entry.Finished(null, usage = AgentHost.Usage(1, 0.5, 2, 3)), Entry.Finished("boom", stopped = true), + Entry.Finished(null, usage = AgentHost.Usage(1, 0.5, 2, 3, context = 40_000, window = 200_000), planned = true), ) written.forEach { AgentChats.append(file, it) } file.appendText("broken line\n") @@ -152,6 +175,7 @@ class AgentHostTest { assertEquals(listOf( Entry.Asked("hi", listOf("/root/x.png")), Entry.Said("hello"), Entry.Thought("hm"), Entry.Used("t1", "Read", "/root/x", "{}", "contents", false), Entry.Finished(null, usage = AgentHost.Usage(1, 0.5, 2, 3)), Entry.Finished("boom", stopped = true), + Entry.Finished(null, usage = AgentHost.Usage(1, 0.5, 2, 3, context = 40_000, window = 200_000), planned = true), ), loaded.entries) assertEquals(emptyList(), AgentChats.read(File(file.path + ".missing")).entries) } @@ -187,4 +211,46 @@ class AgentHostTest { assertTrue(p.running && !p.prepare) assertEquals(95, p.etaSeconds) } + + @Test fun anEditBecomesALineDiffWithItsNearbyLines() { + assertEquals(" a\n b\n-c\n+C\n+D\n e\n f", lineDiff("x\na\nb\nc\ne\nf\ny", "x\na\nb\nC\nD\ne\nf\ny")) + assertEquals("+only", lineDiff("", "only")) + assertEquals("-gone", lineDiff("gone", "")) + assertEquals("+one\n+two", lineDiff("", "one\ntwo\n")) + } + + @Test fun claudeRateLimitsAndContextWindowAreRead() { + val event = ClaudeCode.parse("""{"type":"rate_limit_event","rate_limit_info":{"status":"allowed_warning","unifiedWindows":{"five_hour":{"utilization":0.07,"resetsAt":1794435600},"seven_day":{"utilization":0.85,"resetsAt":1794592800}}},"session_id":"s"}""")!! + assertEquals(listOf(AgentHost.Limit(300, 7, 1794435600), AgentHost.Limit(10_080, 85, 1794592800)), event.limits) + val result = ClaudeCode.parse("""{"type":"result","subtype":"success","is_error":false,"result":"done","usage":{},"modelUsage":{"claude-haiku":{"costUSD":0.01,"contextWindow":200000},"claude-sonnet":{"costUSD":0.7,"contextWindow":1000000}}}""")!! + assertEquals(1_000_000L, result.window) + } + + @Test fun codexTokenCountsCarryContextAndLimits() { + val event = Codex.tokenCount("""{"timestamp":"t","type":"event_msg","payload":{"type":"token_count","info":{"total_token_usage":{"total_tokens":90000},"last_token_usage":{"total_tokens":41000},"model_context_window":272000},"rate_limits":{"primary":{"used_percent":12.5,"window_minutes":300,"resets_at":1794435600},"secondary":{"used_percent":40.0,"window_minutes":10080,"resets_at":1794592800}}}}""")!! + assertEquals(41_000L, event.context) + assertEquals(272_000L, event.window) + assertEquals(listOf(AgentHost.Limit(300, 12, 1794435600), AgentHost.Limit(10_080, 40, 1794592800)), event.limits) + assertNull(Codex.tokenCount("""{"type":"event_msg","payload":{"type":"agent_message"}}""")) + } + + @Test fun codexUsageComesFromTheThreadsSessionLog() { + val root = Files.createTempDirectory("rootfs").toFile() + val log = File(root, "root/.codex/sessions/2026/11/12/rollout-2026-11-12T10-00-00-thread1.jsonl").apply { parentFile!!.mkdirs() } + log.writeText( + """{"type":"event_msg","payload":{"type":"token_count","info":{"last_token_usage":{"total_tokens":15692},"model_context_window":258400},"rate_limits":{"primary":{"used_percent":86.0,"window_minutes":10080,"resets_at":1794716485},"secondary":null}}}""" + "\n" + + """{"type":"response_item","payload":{"type":"additional_tools","tools":[{"description":"reports token_count as it goes"}]}}""" + "\n", + ) + val event = Codex.usage(root, "thread1")!! + assertEquals(15_692L, event.context) + assertEquals(258_400L, event.window) + assertEquals(listOf(AgentHost.Limit(10_080, 86, 1794716485)), event.limits) + assertNull(Codex.usage(root, "other")) + } + + @Test fun limitsRoundTripThroughPrefs() { + val limits = listOf(AgentHost.Limit(300, 7, 1794435600), AgentHost.Limit(10_080, 85, 1794592800)) + assertEquals(limits, AgentHost.decodeLimits(AgentHost.encodeLimits(limits))) + assertEquals(emptyList(), AgentHost.decodeLimits("not json")) + } } diff --git a/app/src/test/java/com/droiddeck/launcher/agent/AgentSetupRootTest.kt b/app/src/test/java/com/droiddeck/launcher/agent/AgentSetupRootTest.kt new file mode 100644 index 0000000000..5e5c1656c2 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/agent/AgentSetupRootTest.kt @@ -0,0 +1,10 @@ +package com.droiddeck.launcher.agent + +import org.junit.Assert.assertEquals +import org.junit.Test + +class AgentSetupRootTest { + @Test fun onlyThePackageInstallRunsAsRoot() { + assertEquals(listOf(AgentSetup.Step.INSTALL), AgentSetup.Step.values().filter { AgentSetup.runsAsRoot(it) }) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/core/AddonPackTest.kt b/app/src/test/java/com/droiddeck/launcher/core/AddonPackTest.kt index 80c6ebd328..c367c63ecc 100644 --- a/app/src/test/java/com/droiddeck/launcher/core/AddonPackTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/core/AddonPackTest.kt @@ -58,6 +58,22 @@ class AddonPackTest { assertFalse(AddonPack("sample", "", 0L, listOf("tool"), reuseDeviceCopy = false).installed(context)) } + @Test fun labBuildReusesInstalledPackDespiteDifferentSourcePin() { + installed("b".repeat(64)) + val pack = AddonPack("sample", "a".repeat(64), 1L, listOf("tool"), labBuild = true) + + assertTrue(pack.installed(context)) + assertEquals("b".repeat(64), pack.dir(context).name) + } + + @Test fun labBuildWithoutCompleteInstalledPackKeepsSourcePin() { + installed("b".repeat(64), complete = false) + val pack = AddonPack("sample", "a".repeat(64), 1L, listOf("tool"), labBuild = true) + + assertFalse(pack.installed(context)) + assertEquals("a".repeat(64), pack.dir(context).name) + } + @Test fun localBuildInstallsTheBundledPackWithoutDownloading() { val archive = tarZst("tool" to "x") val pack = AddonPack("sample", Hashes.sha256(archive), archive.length(), listOf("tool"), bundle = { archive.inputStream() }) diff --git a/app/src/test/java/com/droiddeck/launcher/core/GameResolutionTest.kt b/app/src/test/java/com/droiddeck/launcher/core/GameResolutionTest.kt new file mode 100644 index 0000000000..5a76e0525e --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/core/GameResolutionTest.kt @@ -0,0 +1,60 @@ +package com.droiddeck.launcher.core + +import com.droiddeck.launcher.session.NoSteamLaunch +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test + +class GameResolutionTest { + @Test + fun choicesRoundTripThroughTheStoredValue() { + for (choice in listOf(GameResolution.Fixed(1280, 720), GameResolution.Scaled(1.5f), GameResolution.Scaled(2f))) { + assertEquals(choice, GameResolution.parse(GameResolution.format(choice))) + } + assertEquals("1280x720", GameResolution.format(GameResolution.Fixed(1280, 720))) + assertEquals("/1.5", GameResolution.format(GameResolution.Scaled(1.5f))) + } + + @Test + fun invalidValuesAreIgnored() { + for (value in listOf(null, "", "abc", "100x100", "1280", "1280x720x2", "/1", "/0.5", "/9")) { + assertNull(value, GameResolution.parse(value)) + } + } + + @Test + fun aScaleDividesTheOutputToEvenSides() { + assertEquals(1706 to 1066, GameResolution.resolve(GameResolution.Scaled(1.5f), 2560 to 1600)) + assertEquals(1280 to 800, GameResolution.resolve(GameResolution.Scaled(2f), 2560 to 1600)) + assertEquals(1280 to 720, GameResolution.resolve(GameResolution.Fixed(1280, 720), 2560 to 1600)) + } + + @Test + fun aspectRatiosAreNamed() { + assertEquals("16:9", GameResolution.aspectLabel(1920, 1080)) + assertEquals("16:10", GameResolution.aspectLabel(2560, 1600)) + assertEquals("4:3", GameResolution.aspectLabel(1024, 768)) + assertEquals("21:9", GameResolution.aspectLabel(2560, 1080)) + assertEquals("20:9", GameResolution.aspectLabel(2400, 1080)) + } + + @Test + fun presetsLargerThanThePanelAreLeftOut() { + val wide = GameResolution.aspects.first { it.label == "16:9" } + assertEquals(listOf(960 to 540, 1280 to 720, 1600 to 900, 1920 to 1080), + GameResolution.sizesFor(wide, 1920 to 1200).map { it.width to it.height }) + } + + @Test + fun theSessionFindsTheResolutionOfTheGameItStarts() { + val config = GameEnvironment.withGameResolution(GameEnvironment.Config(), "570", GameResolution.Fixed(1280, 800)) + val scope = NoSteamLaunch.scopeOf(NoSteamLaunch.PROTON_RUN, listOf("--app", "570")) + assertEquals("570", scope) + assertEquals(1280 to 800, NoSteamLaunch.resolution(config, scope, 2560 to 1600)) + assertNull(NoSteamLaunch.resolution(config, "440", 2560 to 1600)) + assertEquals("123", NoSteamLaunch.scopeOf(NoSteamLaunch.BATTLENET, listOf("launch", "WTCG")) { if (it == "WTCG") "123" else null }) + assertEquals(com.droiddeck.launcher.runtime.BattleNet.APP_ID.toString(), + NoSteamLaunch.scopeOf(NoSteamLaunch.BATTLENET, listOf("launch", "Pro"))) + assertNull(GameEnvironment.withGameResolution(config, "570", null).games["570"]) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/frontend/SoundtrackCollectionsTest.kt b/app/src/test/java/com/droiddeck/launcher/frontend/SoundtrackCollectionsTest.kt new file mode 100644 index 0000000000..6aa9bb1640 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/frontend/SoundtrackCollectionsTest.kt @@ -0,0 +1,43 @@ +package com.droiddeck.launcher.frontend + +import com.droiddeck.launcher.frontend.SoundtrackCollections.Collection +import com.droiddeck.launcher.frontend.SoundtrackCollections.TrackRef +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [33]) +class SoundtrackCollectionsTest { + private fun ref(path: String) = TrackRef(path, path, "", "", 0) + + @Test fun toggledAddsThenRemoves() { + val once = SoundtrackCollections.toggled(emptyList(), ref("a")) + assertEquals(listOf("a"), once.map { it.path }) + assertTrue(SoundtrackCollections.toggled(once, ref("a")).isEmpty()) + } + + @Test fun mergedSkipsDuplicatesAndKeepsOrder() { + val result = SoundtrackCollections.merged(listOf(ref("a"), ref("b")), listOf(ref("b"), ref("c"), ref("c"))) + assertEquals(listOf("a", "b", "c"), result.map { it.path }) + } + + @Test fun cleanNameTrimsAndCollapsesSpaces() = assertEquals("My mix", SoundtrackCollections.cleanName(" My mix ")) + + @Test fun nameTakenIgnoresCaseAndExcludedId() { + val list = listOf(Collection(2_000_000_001, "Chill", emptyList())) + assertTrue(SoundtrackCollections.nameTaken(list, "chill")) + assertFalse(SoundtrackCollections.nameTaken(list, "chill", except = 2_000_000_001)) + assertFalse(SoundtrackCollections.nameTaken(list, "Focus")) + } + + @Test fun nextIdStartsAboveFavoritesAndGrows() { + assertEquals(SoundtrackCollections.FAVORITES_ID + 1, SoundtrackCollections.nextId(emptyList())) + val list = listOf(Collection(2_000_000_005, "x", emptyList())) + assertEquals(2_000_000_006, SoundtrackCollections.nextId(list)) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/frontend/SoundtrackOrderTest.kt b/app/src/test/java/com/droiddeck/launcher/frontend/SoundtrackOrderTest.kt new file mode 100644 index 0000000000..167d2c96b9 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/frontend/SoundtrackOrderTest.kt @@ -0,0 +1,34 @@ +package com.droiddeck.launcher.frontend + +import java.io.File +import org.junit.Assert.assertEquals +import org.junit.Test + +class SoundtrackOrderTest { + private fun track(name: String, disc: Int, number: Int) = Soundtrack.Track(File("/music/$name"), name, disc, number, 1000L) + + @Test fun savedOrderIsAppliedAndRenumbered() { + val disc = mapOf(1 to listOf(track("a", 1, 1), track("b", 1, 2), track("c", 1, 3))) + val result = SoundtrackOrder.ordered(disc, listOf("/music/c", "/music/a", "/music/b")) + assertEquals(listOf("c", "a", "b"), result.getValue(1).map { it.title }) + assertEquals(listOf(1, 2, 3), result.getValue(1).map { it.number }) + } + + @Test fun unknownTracksKeepTheirOrderAfterKnownOnes() { + val disc = mapOf(1 to listOf(track("a", 1, 1), track("b", 1, 2), track("c", 1, 3))) + val result = SoundtrackOrder.ordered(disc, listOf("/music/c")) + assertEquals(listOf("c", "a", "b"), result.getValue(1).map { it.title }) + } + + @Test fun discsStayApart() { + val disc = mapOf(1 to listOf(track("a", 1, 1), track("b", 1, 2)), 2 to listOf(track("c", 2, 1), track("d", 2, 2))) + val result = SoundtrackOrder.ordered(disc, listOf("/music/d", "/music/b", "/music/a", "/music/c")) + assertEquals(listOf("b", "a"), result.getValue(1).map { it.title }) + assertEquals(listOf("d", "c"), result.getValue(2).map { it.title }) + } + + @Test fun emptyOrderChangesNothing() { + val disc = mapOf(1 to listOf(track("a", 1, 1), track("b", 1, 2))) + assertEquals(disc, SoundtrackOrder.ordered(disc, emptyList())) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/frontend/SoundtrackTest.kt b/app/src/test/java/com/droiddeck/launcher/frontend/SoundtrackTest.kt new file mode 100644 index 0000000000..ed96285429 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/frontend/SoundtrackTest.kt @@ -0,0 +1,151 @@ +package com.droiddeck.launcher.frontend + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test +import java.io.File + +class SoundtrackTest { + private fun raw( + folder: String, name: String, disc: Int? = null, track: Int? = null, title: String? = null, size: Long = 1000L, + ) = Soundtrack.Raw(File("/music/album/${if (folder.isEmpty()) "" else "$folder/"}$name"), folder, disc, track, title, null, 60_000L, size) + + @Test fun titlesDropArtistAlbumAndNumber() { + assertEquals("Once Upon a Time", Soundtrack.cleanTitle("toby fox - UNDERTALE Soundtrack - 01 Once Upon a Time.mp3")) + assertEquals("ANOTHER HIM", Soundtrack.cleanTitle("001 ANOTHER HIM.flac")) + assertEquals("Chapter 5 Logo", Soundtrack.cleanTitle("166 Chapter 5 Logo.mp3")) + assertEquals("Query-", Soundtrack.cleanTitle("094 Query-.mp3")) + assertEquals("Ruins", Soundtrack.cleanTitle("Ruins.ogg")) + } + + @Test fun flatAlbumIsOneDiscOrderedByNumber() { + val disc = Soundtrack.group( + listOf(raw("", "toby fox - X - 10 Ten.mp3"), raw("", "toby fox - X - 02 Two.mp3"), raw("", "toby fox - X - 01 One.mp3")), + ) + assertEquals(listOf(0), disc.keys.toList()) + assertEquals(listOf("One", "Two", "Ten"), disc.getValue(0).map { it.title }) + assertEquals(listOf(1, 2, 3), disc.getValue(0).map { it.number }) + } + + @Test fun subfoldersBecomeDiscs() { + val disc = Soundtrack.group( + listOf(raw("2", "041 B.mp3"), raw("1", "001 A.mp3"), raw("10", "200 C.mp3"), raw("1", "002 A2.mp3")), + ) + assertEquals(listOf(1, 2, 3), disc.keys.toList()) + assertEquals(listOf("A", "A2"), disc.getValue(1).map { it.title }) + assertEquals(listOf("B"), disc.getValue(2).map { it.title }) + assertEquals(listOf("C"), disc.getValue(3).map { it.title }) + } + + @Test fun losslessCopyReplacesLossyDuplicateAndKeepsItsFolder() { + val disc = Soundtrack.group( + listOf( + raw("", "001 ANOTHER HIM.flac", size = 4_130_000L), + raw("", "002 Beginning.flac", size = 4_870_000L), + raw("1", "001 ANOTHER HIM.mp3", size = 1_940_000L), + raw("1", "002 Beginning.mp3", size = 2_320_000L), + raw("2", "041 Faint Glow.mp3"), + ), + ) + assertEquals(listOf(1, 2), disc.keys.toList()) + assertEquals(listOf("flac", "flac"), disc.getValue(1).map { it.file.extension }) + assertEquals(listOf("ANOTHER HIM", "Beginning"), disc.getValue(1).map { it.title }) + assertEquals(listOf("Faint Glow"), disc.getValue(2).map { it.title }) + } + + @Test fun tagsDecideDiscsAndFileNamesDecideOrder() { + val disc = Soundtrack.group( + listOf( + raw("3+4", "088 Late.mp3", disc = 4, track = 1, title = "Old wooden rafters"), + raw("3+4", "001 Early.mp3", disc = 3, track = 2, title = "Second"), + raw("3+4", "002 Early.mp3", disc = 3, track = 1, title = "First"), + ), + ) + assertEquals(listOf(3, 4), disc.keys.toList()) + assertEquals(listOf("Second", "First"), disc.getValue(3).map { it.title }) + assertEquals("Old wooden rafters", disc.getValue(4).single().title) + } + + @Test fun sameTagsCollapseDuplicates() { + val disc = Soundtrack.group( + listOf( + raw("", "a.flac", disc = 1, track = 1, title = "Song", size = 5000L), + raw("1", "a.mp3", disc = 1, track = 1, title = "Song", size = 900L), + ), + ) + assertEquals(1, disc.getValue(1).size) + assertEquals("flac", disc.getValue(1).single().file.extension) + } + + @Test fun renamedPunctuationStillMatchesAcrossFormats() { + val disc = Soundtrack.group( + listOf( + raw("", "094 Query?.flac", size = 5000L), + raw("3+4", "094 Query-.mp3", size = 900L), + raw("3+4", "095 Quiz!.mp3", size = 900L), + ), + ) + assertEquals(2, disc.getValue(0).size + disc.filterKeys { it != 0 }.values.sumOf { it.size }) + assertEquals(listOf("flac", "mp3"), disc.values.flatten().map { it.file.extension }) + } + + @Test fun sameTitleWithDifferentNumbersStaysSeparate() { + val disc = Soundtrack.group(listOf(raw("", "01 Fanfare.mp3"), raw("", "07 Fanfare.mp3"))) + assertEquals(2, disc.values.flatten().size) + } + + @Test fun folderDiscsKeepTheirFolderNameAsLabel() { + val disc = Soundtrack.group( + listOf(raw("3+4", "088 A.mp3", track = 1), raw("3+4", "165 B.mp3", track = 78), raw("5", "166 C.mp3", track = 1), raw("Bonus", "300 D.mp3")), + ) + assertEquals(listOf("3+4", "5", "3"), disc.values.map { it.first().discLabel }.let { it.take(2) + disc.getValue(3).first().discLabel }) + assertEquals(listOf("A", "B"), disc.getValue(1).map { it.title }) + } + + @Test fun tagsFromTheDroppedDuplicateFillTheKeptOne() { + val disc = Soundtrack.group( + listOf( + raw("", "165 Concert for you.flac", size = 90_000L), + raw("3+4", "165 Concert for you.mp3", track = 78, title = "Concert for you", size = 98_000L), + raw("", "088 Flashback (Excerpt).flac", size = 4_800_000L), + raw("3+4", "088 Flashback (Excerpt).mp3", track = 1, title = "Flashback (Excerpt)", size = 1_280_000L), + ), + ) + val tracks = disc.values.flatten() + assertEquals(listOf("Flashback (Excerpt)", "Concert for you"), tracks.map { it.title }) + assertEquals(listOf("flac", "flac"), tracks.map { it.file.extension }) + } + + @Test fun emptyInputGivesNothing() { + assertTrue(Soundtrack.group(emptyList()).isEmpty()) + } + + @Test fun lengthFormatting() { + assertEquals("0:48", Soundtrack.formatLength(48_000L)) + assertEquals("1:20", Soundtrack.formatLength(80_000L)) + assertEquals("4:15:37", Soundtrack.formatLength((4 * 3600 + 15 * 60 + 37) * 1000L)) + } + + @Test fun shortcutLinksRoundTrip() { + assertEquals(391540, SoundtrackShortcuts.parse(SoundtrackShortcuts.uri(391540))) + assertEquals(-5, SoundtrackShortcuts.parse(SoundtrackShortcuts.uri(-5))) + assertNull(SoundtrackShortcuts.parse("droiddeck://game/12")) + assertNull(SoundtrackShortcuts.parse(null)) + } + + @Test fun addedSoundtracksNeverCollideWithSteamIds() { + assertTrue(AddedSoundtracks.idOf("/storage/emulated/0/Music/Album") < 0) + } + + @Test fun addedIdsStayStableWhenAnotherFolderIsRemoved() { + assertEquals("Aa".hashCode(), "BB".hashCode()) + val first = AddedSoundtracks.Entry("/m/Aa", "A") + val second = AddedSoundtracks.Entry("/m/BB", "B") + val assigned = AddedSoundtracks.assignIds(listOf(first, second)) + assertTrue(assigned[0].id != assigned[1].id) + assertTrue(assigned.all { it.id < 0 }) + val after = AddedSoundtracks.assignIds(assigned.drop(1)) + assertEquals(assigned[1].id, after[0].id) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/frontend/SoundtrackTracksTest.kt b/app/src/test/java/com/droiddeck/launcher/frontend/SoundtrackTracksTest.kt new file mode 100644 index 0000000000..c601653ca7 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/frontend/SoundtrackTracksTest.kt @@ -0,0 +1,29 @@ +package com.droiddeck.launcher.frontend + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class SoundtrackTracksTest { + private class T(val title: String, val ms: Long) + private val items = listOf(T("banana", 300), T("Apple", 100), T("cherry", 200)) + private fun sorted(s: SoundtrackTracks.Sort) = SoundtrackTracks.sort(items, s, { it.title }, { it.ms }).map { it.title } + + @Test fun defaultKeepsOrder() = assertEquals(listOf("banana", "Apple", "cherry"), sorted(SoundtrackTracks.Sort.DEFAULT)) + @Test fun titleAscIgnoresCase() = assertEquals(listOf("Apple", "banana", "cherry"), sorted(SoundtrackTracks.Sort.TITLE_ASC)) + @Test fun titleDesc() = assertEquals(listOf("cherry", "banana", "Apple"), sorted(SoundtrackTracks.Sort.TITLE_DESC)) + @Test fun longestFirst() = assertEquals(listOf("banana", "cherry", "Apple"), sorted(SoundtrackTracks.Sort.LONGEST)) + @Test fun shortestFirst() = assertEquals(listOf("Apple", "cherry", "banana"), sorted(SoundtrackTracks.Sort.SHORTEST)) + + @Test fun blankQueryMatchesEverything() = assertTrue(SoundtrackTracks.matches(" ", "anything")) + @Test fun wordsMayHitDifferentFields() = assertTrue(SoundtrackTracks.matches("main theme", "Main Menu", "Theme Composer")) + @Test fun everyWordMustMatch() = assertFalse(SoundtrackTracks.matches("main boss", "Main Menu", "Composer")) + @Test fun matchIsCaseInsensitive() = assertTrue(SoundtrackTracks.matches("MENU", "main menu")) + + @Test fun rankOrdersExactPrefixContains() { + assertEquals(0, SoundtrackTracks.rank("Menu", "menu")) + assertEquals(1, SoundtrackTracks.rank("men", "Menu Theme")) + assertEquals(2, SoundtrackTracks.rank("theme", "Menu Theme")) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/gpu/FrameGenTest.kt b/app/src/test/java/com/droiddeck/launcher/gpu/FrameGenTest.kt index f4c3b79ea0..5afd7f83a9 100644 --- a/app/src/test/java/com/droiddeck/launcher/gpu/FrameGenTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/gpu/FrameGenTest.kt @@ -2,6 +2,8 @@ package com.droiddeck.launcher.gpu import android.content.Context import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue import org.junit.Before import org.junit.Test import org.junit.runner.RunWith @@ -45,4 +47,22 @@ class FrameGenTest { .putString("engine", "winfg").putInt("multiplier", 2).commit() assertEquals(FrameGen.Mode(FrameGen.ENGINE_DDFG, 2), FrameGen.mode(context)) } + + @Test fun perGameOverrideIsIsolatedFromGlobalMode() { + val global = FrameGen.Mode(FrameGen.ENGINE_LSFG, target = 90) + val game = FrameGen.Mode(FrameGen.ENGINE_DDFG, 3) + + FrameGen.set(context, global) + FrameGen.setForGame(context, "12345", game) + + assertEquals(global, FrameGen.mode(context)) + assertEquals(game, FrameGen.mode(context, "12345")) + assertTrue(FrameGen.hasGameOverride(context, "12345")) + + FrameGen.clearGame(context, "12345") + + assertFalse(FrameGen.hasGameOverride(context, "12345")) + assertEquals(global, FrameGen.mode(context, "12345")) + } + } diff --git a/app/src/test/java/com/droiddeck/launcher/hud/CoreClockAverageTest.kt b/app/src/test/java/com/droiddeck/launcher/hud/CoreClockAverageTest.kt new file mode 100644 index 0000000000..80c1c7121c --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/hud/CoreClockAverageTest.kt @@ -0,0 +1,26 @@ +package com.droiddeck.launcher.hud + +import org.junit.Assert.assertEquals +import org.junit.Test + +class CoreClockAverageTest { + private val freqs = longArrayOf(902_400L, 1_459_200L, 2_803_200L) + + @Test fun aCoreShowsTheClockItRanAtThroughTheSample() { + val before = arrayOf(freqs, longArrayOf(100L, 50L, 10L)) + val after = arrayOf(freqs, longArrayOf(125L, 50L, 35L)) + assertEquals(1_852_800L, HudMetrics.averageKhz(before, after)) + } + + @Test fun theFirstSampleOrAChangedTableFallsBack() { + val after = arrayOf(freqs, longArrayOf(1L, 2L, 3L)) + assertEquals(-1L, HudMetrics.averageKhz(null, after)) + assertEquals(-1L, HudMetrics.averageKhz(arrayOf(longArrayOf(1L), longArrayOf(0L)), after)) + assertEquals(-1L, HudMetrics.averageKhz(after, after)) + } + + @Test fun theCpuClockIsTheFastestCore() { + assertEquals(2_803, HudMetrics.fastestCoreMhz(intArrayOf(902, 2_803, 1_459))) + assertEquals(null, HudMetrics.fastestCoreMhz(intArrayOf(0, 0))) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/hud/FrameStatsTest.kt b/app/src/test/java/com/droiddeck/launcher/hud/FrameStatsTest.kt index 724275fd35..20e83499e8 100644 --- a/app/src/test/java/com/droiddeck/launcher/hud/FrameStatsTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/hud/FrameStatsTest.kt @@ -81,6 +81,21 @@ class FrameStatsTest { assertEquals(0, stats.slowFrames(now, 60_000_000_000L)) } + @Test fun guestFrameTimesMoveByThePausedSessionsClockShift() { + val control = java.io.File.createTempFile("bl-clock", null) + try { + control.writeBytes(java.nio.ByteBuffer.allocate(8).order(java.nio.ByteOrder.LITTLE_ENDIAN).putLong(62_283_930_706L).array()) + val feed = GameFrameFeed(java.io.File("/nonexistent/droiddeck-hud/frames"), clockControl = control) + assertEquals(62_283_930_706L, feed.guestClockShift(1_000_000_000L, 1_000_000_000L)) + control.writeBytes(java.nio.ByteBuffer.allocate(8).order(java.nio.ByteOrder.LITTLE_ENDIAN).putLong(70_000_000_000L).array()) + assertEquals(62_283_930_706L, feed.guestClockShift(1_050_000_000L, 1_000_000_000L)) + assertEquals(70_000_000_000L, feed.guestClockShift(1_200_000_000L, 100_000_000L)) + assertEquals(0L, GameFrameFeed(java.io.File("/nonexistent/droiddeck-hud/frames")).guestClockShift(0L, 0L)) + } finally { + control.delete() + } + } + @Test fun compositorFramesDoNotCountAsLiveGamescopeFrames() { val feed = GameFrameFeed(java.io.File("/nonexistent/droiddeck-hud/frames")) var now = 1_000_000_000L diff --git a/app/src/test/java/com/droiddeck/launcher/input/JoyConPadTest.kt b/app/src/test/java/com/droiddeck/launcher/input/JoyConPadTest.kt index 0b8c930ed0..cff58d665e 100644 --- a/app/src/test/java/com/droiddeck/launcher/input/JoyConPadTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/input/JoyConPadTest.kt @@ -147,6 +147,75 @@ class JoyConPadTest { assertNull(RecordingWriter.pads[2]) } + @Test fun aControllerThatDisconnectsWhileItsKeyIsHandledIsIgnored() { + for (lookups in 0..4) { + val event = key(right, KeyEvent.KEYCODE_BUTTON_A, BTN_SOUTH) + PadBridgeRoutingTest.RegisteredKeyEvent.lookupsLeft = lookups + try { + val handled = bridge.onKeyEvent(event) + if (lookups == 0) assertFalse(handled) + if (lookups >= 2) assertTrue(handled) + } finally { PadBridgeRoutingTest.RegisteredKeyEvent.lookupsLeft = -1 } + } + assertTrue(press(right, KeyEvent.KEYCODE_BUTTON_A, BTN_SOUTH)) + } + + @Test fun aControllerThatDisconnectsAfterTheFirstLookupStillDeliversItsEvents() { + val device = controller(0x045e, 0x0b13, MotionEvent.AXIS_X, MotionEvent.AXIS_Y) + val down = key(device, KeyEvent.KEYCODE_BUTTON_A, BTN_SOUTH) + val up = key(device, KeyEvent.KEYCODE_BUTTON_A, BTN_SOUTH, KeyEvent.ACTION_UP) + val move = motion(device, MotionEvent.AXIS_X to 0.5f, MotionEvent.AXIS_Y to -0.25f) + try { + PadBridgeRoutingTest.RegisteredKeyEvent.lookupsLeft = 1 + assertTrue(bridge.onKeyEvent(down)) + assertEquals(0, PadBridgeRoutingTest.RegisteredKeyEvent.lookupsLeft) + assertTrue(pad(0).isDown(PadState.A)) + PadBridgeRoutingTest.RegisteredKeyEvent.lookupsLeft = 1 + assertTrue(bridge.onKeyEvent(up)) + assertFalse(pad(0).isDown(PadState.A)) + PadBridgeRoutingTest.RegisteredMotionEvent.lookupsLeft = 1 + assertTrue(bridge.onMotionEvent(move)) + assertEquals(0, PadBridgeRoutingTest.RegisteredMotionEvent.lookupsLeft) + assertEquals(0.5f, pad(0).leftX) + assertEquals(-0.25f, pad(0).leftY) + } finally { + PadBridgeRoutingTest.RegisteredKeyEvent.lookupsLeft = -1 + PadBridgeRoutingTest.RegisteredMotionEvent.lookupsLeft = -1 + } + } + + @Test fun nonControllerInputStaysUnhandledWithOneLookup() { + val keyboard = InputDeviceBuilder.newBuilder().setId(nextId++).setName("Keyboard").setDescriptor("keyboard") + .setExternal(true).setSources(InputDevice.SOURCE_KEYBOARD) + .setKeyboardType(InputDevice.KEYBOARD_TYPE_ALPHABETIC) + .setKeyCharacterMap(KeyCharacterMap.load(KeyCharacterMap.VIRTUAL_KEYBOARD)).build().also(::register) + val typed = KeyEvent(0L, 0L, KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_A, 0, 0, keyboard.id, 30, 0, InputDevice.SOURCE_KEYBOARD) + val touch = MotionEvent.obtain(0L, 0L, MotionEvent.ACTION_MOVE, 1, arrayOf(MotionEvent.PointerProperties().apply { id = 0 }), + arrayOf(MotionEvent.PointerCoords().apply { x = 10f; y = 20f }), 0, 0, 1f, 1f, keyboard.id, 0, InputDevice.SOURCE_TOUCHSCREEN, 0) + try { + PadBridgeRoutingTest.RegisteredKeyEvent.lookupsLeft = 1 + assertFalse(bridge.onKeyEvent(typed)) + PadBridgeRoutingTest.RegisteredMotionEvent.lookupsLeft = 1 + assertFalse(bridge.onMotionEvent(touch)) + } finally { + PadBridgeRoutingTest.RegisteredKeyEvent.lookupsLeft = -1 + PadBridgeRoutingTest.RegisteredMotionEvent.lookupsLeft = -1 + } + assertNull(RecordingWriter.pads[0]) + } + + @Test fun wiredMotionKeepsItsAxesWhenDeviceDisappears() { + val device = controller(0x20d6, 0x2063, MotionEvent.AXIS_RX, MotionEvent.AXIS_RY, MotionEvent.AXIS_Z, MotionEvent.AXIS_RZ) + val event = motion(device, MotionEvent.AXIS_RX to 0.75f, MotionEvent.AXIS_RY to -0.5f, + MotionEvent.AXIS_Z to -1f, MotionEvent.AXIS_RZ to 1f) + PadBridgeRoutingTest.RegisteredMotionEvent.lookupsLeft = 2 + try { assertTrue(bridge.onMotionEvent(event)) } finally { PadBridgeRoutingTest.RegisteredMotionEvent.lookupsLeft = -1 } + assertEquals(0.75f, pad(0).rightX) + assertEquals(-0.5f, pad(0).rightY) + assertEquals(0f, pad(0).leftTrigger) + assertEquals(1f, pad(0).rightTrigger) + } + @Test fun joyConsHeldForVrAreLeftAlone() { bridge.setExcluded { it == left.id } assertFalse(bridge.onKeyEvent(key(left, KeyEvent.KEYCODE_BUTTON_L1, BTN_TL))) diff --git a/app/src/test/java/com/droiddeck/launcher/input/PadBridgeRoutingTest.kt b/app/src/test/java/com/droiddeck/launcher/input/PadBridgeRoutingTest.kt index a76da590a3..ea66f32136 100644 --- a/app/src/test/java/com/droiddeck/launcher/input/PadBridgeRoutingTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/input/PadBridgeRoutingTest.kt @@ -191,12 +191,24 @@ class PadBridgeRoutingTest { @Implements(KeyEvent::class) class RegisteredKeyEvent : ShadowKeyEvent() { @RealObject private lateinit var event: KeyEvent - @Implementation override fun getDevice(): InputDevice? = Shadow.directlyOn(event as InputEvent, InputEvent::class.java, "getDevice") + @Implementation override fun getDevice(): InputDevice? { + if (lookupsLeft == 0) return null + if (lookupsLeft > 0) lookupsLeft-- + return Shadow.directlyOn(event as InputEvent, InputEvent::class.java, "getDevice") + } + + companion object { @JvmField var lookupsLeft = -1 } } @Implements(MotionEvent::class) class RegisteredMotionEvent : ShadowMotionEvent() { @RealObject private lateinit var event: MotionEvent - @Implementation override fun getDevice(): InputDevice? = Shadow.directlyOn(event as InputEvent, InputEvent::class.java, "getDevice") + @Implementation override fun getDevice(): InputDevice? { + if (lookupsLeft == 0) return null + if (lookupsLeft > 0) lookupsLeft-- + return Shadow.directlyOn(event as InputEvent, InputEvent::class.java, "getDevice") + } + + companion object { @JvmField var lookupsLeft = -1 } } } diff --git a/app/src/test/java/com/droiddeck/launcher/input/PadPartialAxesTest.kt b/app/src/test/java/com/droiddeck/launcher/input/PadPartialAxesTest.kt index 2a2bade1c4..ae46c9d5e3 100644 --- a/app/src/test/java/com/droiddeck/launcher/input/PadPartialAxesTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/input/PadPartialAxesTest.kt @@ -126,11 +126,11 @@ class PadPartialAxesTest { @Test fun wiredXboxTriggerKeysDoNotOverrideTheirAxes() { val device = device(MotionEvent.AXIS_RX, MotionEvent.AXIS_RY, MotionEvent.AXIS_Z, MotionEvent.AXIS_RZ, wired = true) - motion(device, MotionEvent.AXIS_Z to 0f, MotionEvent.AXIS_RZ to -1f) + motion(device, MotionEvent.AXIS_Z to 0f, MotionEvent.AXIS_RZ to -0.6f) key(device, KeyEvent.KEYCODE_BUTTON_L2) key(device, KeyEvent.KEYCODE_BUTTON_R2) assertEquals(0.5f, pad().leftTrigger) - assertEquals(0f, pad().rightTrigger) + assertEquals(0.2f, pad().rightTrigger, 0.0001f) } @Test fun digitalTriggerKeysStillPressAndRelease() { @@ -148,11 +148,46 @@ class PadPartialAxesTest { } @Test fun keyTriggerDecision() { - assertEquals(1f, PadBridge.keyTrigger(0f, true, 0, false)) - assertEquals(0f, PadBridge.keyTrigger(1f, false, 0, false)) - assertEquals(0.25f, PadBridge.keyTrigger(0.25f, true, 1, false)) - assertEquals(0.25f, PadBridge.keyTrigger(0.25f, true, 0, true)) - assertEquals(0.25f, PadBridge.keyTrigger(0.25f, false, 0, true)) + val held = BooleanArray(2) + assertEquals(1f, PadBridge.keyTrigger(0f, true, 0, false, held, 0)) + assertEquals(0f, PadBridge.keyTrigger(1f, false, 0, false, held, 0)) + assertEquals(0.25f, PadBridge.keyTrigger(0.25f, true, 1, false, held, 0)) + assertEquals(0.25f, PadBridge.keyTrigger(0.25f, true, 0, true, held, 0)) + assertEquals(0.25f, PadBridge.keyTrigger(0.25f, false, 0, true, held, 0)) + assertEquals(1f, PadBridge.keyTrigger(0f, true, 0, true, held, 1)) + assertEquals(1f, PadBridge.axisTrigger(0f, held, 1)) + assertEquals(0f, PadBridge.keyTrigger(1f, false, 0, true, held, 1)) + assertEquals(0f, PadBridge.axisTrigger(0f, held, 1)) + } + + @Test fun silentTriggerAxesLetTheirKeysPress() { + val device = device(MotionEvent.AXIS_LTRIGGER, MotionEvent.AXIS_RTRIGGER) + motion(device) + key(device, KeyEvent.KEYCODE_BUTTON_L2) + key(device, KeyEvent.KEYCODE_BUTTON_R2) + assertEquals(1f, pad().leftTrigger) + assertEquals(1f, pad().rightTrigger) + motion(device, MotionEvent.AXIS_X to 0.8f) + key(device, KeyEvent.KEYCODE_BUTTON_L2, repeat = 1) + assertEquals(1f, pad().leftTrigger) + assertEquals(1f, pad().rightTrigger) + key(device, KeyEvent.KEYCODE_BUTTON_L2, KeyEvent.ACTION_UP) + assertEquals(0f, pad().leftTrigger) + assertEquals(1f, pad().rightTrigger) + key(device, KeyEvent.KEYCODE_BUTTON_R2, KeyEvent.ACTION_UP) + assertEquals(0f, pad().rightTrigger) + } + + @Test fun aLiveAxisTakesOverFromItsKey() { + val device = device(MotionEvent.AXIS_LTRIGGER) + key(device, KeyEvent.KEYCODE_BUTTON_L2) + assertEquals(1f, pad().leftTrigger) + motion(device, MotionEvent.AXIS_LTRIGGER to 0.4f) + assertEquals(0.4f, pad().leftTrigger) + motion(device, MotionEvent.AXIS_LTRIGGER to 0f) + assertEquals(0f, pad().leftTrigger) + key(device, KeyEvent.KEYCODE_BUTTON_L2, KeyEvent.ACTION_UP) + assertEquals(0f, pad().leftTrigger) } private fun pad(): PadState = requireNotNull(JoyConPadTest.RecordingWriter.pads[0]) diff --git a/app/src/test/java/com/droiddeck/launcher/runtime/BattleNetTest.kt b/app/src/test/java/com/droiddeck/launcher/runtime/BattleNetTest.kt index 1af73baef4..f74528c725 100644 --- a/app/src/test/java/com/droiddeck/launcher/runtime/BattleNetTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/runtime/BattleNetTest.kt @@ -259,6 +259,29 @@ class BattleNetTest { BattleNet.hostFolder(context, "Z:/root/Games/Stores/Battle.net/Hearthstone/")) } + @Test fun aMappedWineDriveResolvesThroughItsLink() { + val devices = File(BattleNet.prefix(context), "pfx/dosdevices").apply { mkdirs() } + java.nio.file.Files.createSymbolicLink(File(devices, "d:").toPath(), java.nio.file.Paths.get("/root/Games/Card")) + java.nio.file.Files.createSymbolicLink(File(devices, "e:").toPath(), java.nio.file.Paths.get("../drive_c")) + assertEquals(File(LinuxRuntime.rootDir(context), "root/Games/Card/Battle.net/Hearthstone"), + BattleNet.hostFolder(context, "D:\\Battle.net\\Hearthstone")) + assertEquals(File(BattleNet.prefix(context), "pfx/drive_c/Games/X"), BattleNet.hostFolder(context, "E:\\Games\\X")) + assertNull(BattleNet.hostFolder(context, "F:\\Games\\X")) + assertNull(BattleNet.hostFolder(context, "D:\\..\\etc")) + } + + @Test fun aDriveLinkTheNativeUserlandMadeRelativeStillResolvesInTheGuest() { + val root = LinuxRuntime.rootDir(context) + val devices = File(BattleNet.prefix(context), "pfx/dosdevices").apply { mkdirs() } + java.nio.file.Files.createSymbolicLink(File(devices, "d:").toPath(), java.nio.file.Paths.get("/root/Games/Card")) + java.nio.file.Files.createSymbolicLink(File(devices, "g:").toPath(), java.nio.file.Paths.get("../../../../../../../../../../..")) + NativeGuest.relinkAbsoluteSymlinks(context, root) + assertFalse(java.nio.file.Files.readSymbolicLink(File(devices, "d:").toPath()).isAbsolute) + assertEquals(File(root, "root/Games/Card/Battle.net/Hearthstone"), + BattleNet.hostFolder(context, "D:\\Battle.net\\Hearthstone")) + assertNull(BattleNet.hostFolder(context, "G:\\etc\\passwd")) + } + @Test fun wowForeverIsListedBesideRetailInTheSharedWorldOfWarcraftFolder() { val pfx = File(BattleNet.prefix(context), "pfx").apply { mkdirs() } @@ -351,6 +374,20 @@ class BattleNetTest { } + @Test fun aScannedGamesShortcutReusesTheKeptRankingInsteadOfWalkingItsFolder() { + val added = com.droiddeck.launcher.frontend.AddedGames + val folder = File(BattleNet.prefix(context), "pfx/drive_c/Program Files (x86)/Kept Game").apply { mkdirs() } + File(folder, "Game.exe").writeBytes(byteArrayOf(0x4d, 0x5a)) + val kept = File(folder, "Other.exe").apply { writeBytes(byteArrayOf(0x4d, 0x5a)) } + com.droiddeck.launcher.frontend.AddedGamesCache(File(context.filesDir, com.droiddeck.launcher.frontend.AddedGamesCache.FILE)).apply { + keepRank(folder, com.droiddeck.launcher.frontend.GameExePicker.Ranking(listOf(kept), listOf(10), false)) + save() + } + added.scan(context) + assertEquals(kept, BattleNet.shortcut(context, BattleNet.Game("fenris", "Kept Game", "Fen", folder))!!.exe) + assertEquals("Game.exe", added.candidates(folder).first().name) + } + @Test fun aGamesShortcutHasBattleNetLaunchItInItsPrefix() { val folder = File(BattleNet.prefix(context), "pfx/drive_c/Program Files (x86)/Diablo IV").apply { mkdirs() } File(folder, "Diablo IV Launcher.exe").writeBytes(byteArrayOf(0x4d, 0x5a)) diff --git a/app/src/test/java/com/droiddeck/launcher/runtime/LinuxRuntimeRootPrefixTest.kt b/app/src/test/java/com/droiddeck/launcher/runtime/LinuxRuntimeRootPrefixTest.kt new file mode 100644 index 0000000000..e956781db9 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/runtime/LinuxRuntimeRootPrefixTest.kt @@ -0,0 +1,54 @@ +package com.droiddeck.launcher.runtime + +import android.app.Application +import android.system.Os +import android.system.StructUtsname +import androidx.test.core.app.ApplicationProvider +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +import org.robolectric.annotation.Implementation +import org.robolectric.annotation.Implements +import java.io.File + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [33], manifest = Config.NONE, application = Application::class, shadows = [LinuxRuntimeRootPrefixTest.Uname::class]) +class LinuxRuntimeRootPrefixTest { + private val context: Application = ApplicationProvider.getApplicationContext() + private val root = File(context.filesDir, "rootfs") + private val guest = listOf("/usr/bin/dpkg", "--configure", "-a") + + @Test fun fakeRootEmulatesHardLinksForPackageManagers() { + val cmd = LinuxRuntime.commandWithBinds(context, root, emptyList(), guest, true) + assertTrue("-0" in cmd) + assertTrue("--link2symlink" in cmd) + assertFalse("-i" in cmd) + assertEquals(guest, cmd.takeLast(guest.size)) + } + + @Test fun rootSpawnerAndFakeRootCommandsShareOnePrefix() { + assertEquals(LinuxRuntime.rootPrefix(context, root, "/root"), + LinuxRuntime.commandWithBinds(context, root, emptyList(), emptyList(), true)) + } + + @Test fun userCommandsKeepTheAppUidAndRealLinks() { + val cmd = LinuxRuntime.commandWithBinds(context, root, emptyList(), guest) + val uid = android.os.Process.myUid() + assertFalse("-0" in cmd) + assertFalse("--link2symlink" in cmd) + assertEquals("$uid:$uid", cmd[cmd.indexOf("-i") + 1]) + assertEquals(LinuxRuntime.prootPrefix(context, root, "/root"), cmd.dropLast(guest.size)) + } + + @Implements(Os::class) + class Uname { + companion object { + @JvmStatic @Implementation + fun uname() = StructUtsname("Linux", "localhost", "6.1.0", "#1 SMP", "aarch64") + } + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/session/BuildWatermarkSettingTest.kt b/app/src/test/java/com/droiddeck/launcher/session/BuildWatermarkSettingTest.kt new file mode 100644 index 0000000000..f495d9e0bb --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/session/BuildWatermarkSettingTest.kt @@ -0,0 +1,99 @@ +package com.droiddeck.launcher.session + +import android.app.Activity +import android.app.Application +import android.content.Context +import android.content.Intent +import android.os.Looper +import android.view.View +import com.droiddeck.launcher.ui.BuildWatermark +import org.junit.After +import org.junit.Assert.* +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.Robolectric +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.Shadows.shadowOf +import org.robolectric.annotation.ConscryptMode +import org.robolectric.annotation.GraphicsMode +import org.robolectric.annotation.Config +import java.io.File + +@RunWith(RobolectricTestRunner::class) +@ConscryptMode(ConscryptMode.Mode.OFF) +@GraphicsMode(GraphicsMode.Mode.LEGACY) +@Config(sdk = [34], manifest = Config.NONE, application = Application::class) +class BuildWatermarkSettingTest { + private val context get() = RuntimeEnvironment.getApplication() + private val originalLineProvider = BuildWatermark.lineProvider + + @Before fun clear() { + BuildWatermark.lineProvider = { + BuildWatermark.lines(pr = 1234, ci = true, commit = "abcdef0123", title = "Test build", branch = "") + } + listOf("build-watermark", "build-watermark.new", "build-watermark.bak", "build-watermark.lock").forEach { + File(context.filesDir, it).delete() + } + context.getSharedPreferences("session", Context.MODE_PRIVATE).edit().clear().commit() + } + + @After fun cleanUp() { + try { + clear() + } finally { + BuildWatermark.lineProvider = originalLineProvider + } + } + + @Test fun defaultsOnAndPreservesLegacyChoice() { + assertTrue(SessionPrefs.buildWatermarkEnabled(context)) + context.getSharedPreferences("session", Context.MODE_PRIVATE).edit().putBoolean("buildWatermark", false).commit() + assertFalse(SessionPrefs.buildWatermarkEnabled(context)) + } + + @Test fun sharedFileOverridesCachedPreferencesAndNotifiesOtherProcesses() { + context.getSharedPreferences("session", Context.MODE_PRIVATE).edit().putBoolean("buildWatermark", false).commit() + SessionPrefs.setBuildWatermarkEnabled(context, true) + assertTrue(SessionPrefs.buildWatermarkEnabled(context)) + val change = shadowOf(context).broadcastIntents.last { it.action == BuildWatermarkSetting.CHANGED } + assertEquals(context.packageName, change.`package`) + File(context.filesDir, "build-watermark").writeText("off") + assertFalse(SessionPrefs.buildWatermarkEnabled(context)) + } + + @Test fun lockOpenFailureFallsBackToPreferences() { + val lock = File(context.filesDir, "build-watermark.lock") + assertTrue(lock.mkdir()) + assertTrue(SessionPrefs.buildWatermarkEnabled(context)) + context.getSharedPreferences("session", Context.MODE_PRIVATE).edit().putBoolean("buildWatermark", false).commit() + assertFalse(SessionPrefs.buildWatermarkEnabled(context)) + assertThrows(java.io.IOException::class.java) { SessionPrefs.setBuildWatermarkEnabled(context, true) } + } + + @Test fun settingReadFailureFallsBackToPreferences() { + assertTrue(File(context.filesDir, "build-watermark").mkdir()) + context.getSharedPreferences("session", Context.MODE_PRIVATE).edit().putBoolean("buildWatermark", false).commit() + assertFalse(SessionPrefs.buildWatermarkEnabled(context)) + } + + @Test fun remoteChangeRefreshesExistingAndRecreatedActivities() { + BuildWatermark.install(context) + val activity = Robolectric.buildActivity(Activity::class.java).setup() + try { + assertNotNull(activity.get().window.decorView.findViewWithTag("build-watermark")) + File(context.filesDir, "build-watermark").writeText("off") + context.sendBroadcast(Intent(BuildWatermarkSetting.CHANGED).setPackage(context.packageName)) + shadowOf(Looper.getMainLooper()).idle() + assertNull(activity.get().window.decorView.findViewWithTag("build-watermark")) + activity.recreate() + assertNull(activity.get().window.decorView.findViewWithTag("build-watermark")) + SessionPrefs.setBuildWatermarkEnabled(context, true) + shadowOf(Looper.getMainLooper()).idle() + assertNotNull(activity.get().window.decorView.findViewWithTag("build-watermark")) + } finally { + activity.pause().stop().destroy() + } + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/session/SelectedGameProfileTest.kt b/app/src/test/java/com/droiddeck/launcher/session/SelectedGameProfileTest.kt index 7955fde23b..d02d76d3db 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/SelectedGameProfileTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/SelectedGameProfileTest.kt @@ -2,6 +2,7 @@ package com.droiddeck.launcher.session import com.droiddeck.launcher.core.GameEnvironment import com.droiddeck.launcher.frontend.Library +import com.droiddeck.launcher.gpu.FrameGen import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse import org.junit.Assert.assertNull @@ -116,6 +117,17 @@ class SelectedGameProfileTest { assertEquals(ProfileValue("PERFORMANCE_TSO", true), resolve(environment = inherited)!!.fexPreset) } + @Test fun frameGenOverrideMakesProfileCustom() { + val profile = resolve( + frameGenMode = FrameGen.Mode.OFF, + frameGenInherited = false, + ) + + assertEquals(FrameGen.Mode.OFF, profile!!.frameGen) + assertFalse(profile.frameGenInherited) + assertTrue(profile.hasOverrides) + } + private fun resolve( selectedAppId: Long = 3180310, games: List = listOf(game), @@ -123,6 +135,8 @@ class SelectedGameProfileTest { gameChoice: ProtonDefault.GameChoice? = null, gameComponents: Map = emptyMap(), gameWindowsComponents: List = emptyList(), + frameGenMode: FrameGen.Mode = FrameGen.Mode.OFF, + frameGenInherited: Boolean = true, ) = SelectedGameProfile.resolve( selectedAppId = selectedAppId, games = games, @@ -134,6 +148,8 @@ class SelectedGameProfileTest { gameProtonId = "p1", gameComponents = gameComponents, gameWindowsComponents = gameWindowsComponents, + frameGenMode = frameGenMode, + frameGenInherited = frameGenInherited, ) private fun component(label: String) = diff --git a/app/src/test/java/com/droiddeck/launcher/session/SessionSuspendControllerTest.kt b/app/src/test/java/com/droiddeck/launcher/session/SessionSuspendControllerTest.kt index 230eb1f12e..44aa6c73cd 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/SessionSuspendControllerTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/SessionSuspendControllerTest.kt @@ -273,9 +273,12 @@ class SessionSuspendControllerTest { val fixture = fixture(17) fixture.clock.writeBytes(shift(5_000_000L)) fixture.controller.freeze { assertTrue(it) } + fixture.clock.delete() + fixture.clock.writeBytes(shift(5_000_000L)) fixture.now += 90_000L fixture.controller.resume { assertTrue(it) } val expected = 5_000_000L + 90_000L * 1_000_000L + assertEquals(5_000_000L, fixture.clockAtMapping) assertEquals(expected, fixture.clockAtContinue) assertEquals(expected, shift(fixture.clock)) fixture.controller.resume { assertTrue(it) } @@ -478,6 +481,7 @@ class SessionSuspendControllerTest { val control = File(tmp, ".bl-zram") val clock = File(tmp, ".bl-clock") var clockAtContinue: Long? = null + var clockAtMapping: Long? = null val pagedOut = mutableListOf>() val pagedIn = mutableListOf>() var availableKb = 8_000_000L @@ -496,6 +500,7 @@ class SessionSuspendControllerTest { proc, ::signal, ::threadSignal, ::sleep, { now }, executor, zramControl = control, clockControl = clock, + mapClockControl = { clockAtMapping = ByteBuffer.wrap(it.readBytes()).order(ByteOrder.LITTLE_ENDIAN).long }, nowNanos = { now * 1_000_000L }, pagedOut = { processes, unacknowledged, resident, swap, _, _ -> pagedOut += Triple(processes, resident, swap) diff --git a/app/src/test/java/com/droiddeck/launcher/session/SteamLibrariesTest.kt b/app/src/test/java/com/droiddeck/launcher/session/SteamLibrariesTest.kt index 5a3fdb26c8..5317e5ca33 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/SteamLibrariesTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/SteamLibrariesTest.kt @@ -65,6 +65,26 @@ class SteamLibrariesTest { assertTrue(SteamLibraries.add(app, nested.path) is SteamLibraries.AddResult.Refused) } + @Test fun aGamesFolderIsOfferedWholeUnlessItIsAlreadyALibrary() { + val games = "/storage/card/GameNative" + assertTrue(SteamLibraries.offered(emptyList(), listOf(games), games)) + assertFalse(SteamLibraries.offered(emptyList(), listOf(games), "$games/Steam")) + assertFalse(SteamLibraries.offered(emptyList(), listOf(games), "/storage/card")) + assertFalse(SteamLibraries.offered(listOf(games), listOf(games), games)) + assertTrue(SteamLibraries.offered(listOf("/storage/card/Other"), listOf(games), "/storage/card/New")) + } + + @Test fun aGamesFolderRemainsDiscoverableBesideChosenGameStorage() { + val card = tmp.newFolder("card") + val games = File(card, "GameNative").path + val selected = File(card, "Selected").apply { mkdirs() } + SessionPrefs.setGameStorage(app, selected.path, "Selected") + val effective = GameStorage.effective(app)!! + assertTrue(SteamLibraries.offered(listOf(effective.path), listOf(games), games)) + SessionPrefs.setGameStorage(app, card.path, "Card") + assertFalse(SteamLibraries.offered(listOf(GameStorage.effective(app)!!.path), listOf(games), games)) + } + private fun library(dir: File): File = dir.apply { File(this, "steamapps").mkdirs(); File(this, "steamapps/appmanifest_220.acf").writeText("x") } @Test fun pickingTheFolderAboveALibraryAddsTheLibraryInside() { @@ -124,6 +144,14 @@ class SteamLibrariesTest { assertEquals("${lib.guest}/steamapps/common/Game", AddedGames.guestPath(app, scanned.folder)) } + @Test fun rawAndStorageMountViewsOverlapButDistinctFoldersDoNot() { + val raw = SteamLibraries.canonical(File("/mnt/media_rw/ABCD-1234/Games")) + val storage = SteamLibraries.canonical(File("/storage/ABCD-1234/Games")) + assertEquals(storage, raw) + assertTrue(SteamLibraries.overlaps(raw, SteamLibraries.canonical(File("/storage/ABCD-1234/Games/Steam")))) + assertFalse(SteamLibraries.overlaps(raw, SteamLibraries.canonical(File("/storage/ABCD-1234/Other")))) + } + @Test fun unreadableOrInvalidEntriesAreDropped() { assertTrue(SteamLibraries.parse("{oops").isEmpty()) assertEquals(listOf("2"), SteamLibraries.parse("""[{"id":"../x","path":"/a"},{"id":"2","path":"/b","label":""}]""").map { it.id }) diff --git a/app/src/test/java/com/droiddeck/launcher/storage/SteamStorageTest.kt b/app/src/test/java/com/droiddeck/launcher/storage/SteamStorageTest.kt index 0cfbf2e054..a3b6a8fa24 100644 --- a/app/src/test/java/com/droiddeck/launcher/storage/SteamStorageTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/storage/SteamStorageTest.kt @@ -50,6 +50,8 @@ class SteamStorageTest { assertEquals(SteamStorage.Kind.X86_PROTON, SteamStorage.kind(manifest(1493710, "Proton - Experimental"))) assertEquals(SteamStorage.Kind.X86_PROTON, SteamStorage.kind(manifest(2805730, "Proton 9.0"))) assertEquals(SteamStorage.Kind.REQUIRED, SteamStorage.kind(manifest(228980, "Steamworks Shared"))) + assertEquals(SteamStorage.Kind.REQUIRED, SteamStorage.kind(manifest(1826330, "Proton EasyAntiCheat Runtime"))) + assertEquals(SteamStorage.Kind.REQUIRED, SteamStorage.kind(manifest(1161040, "Proton BattlEye Runtime"))) assertTrue(SteamStorage.isTool(manifest(2805730, "Proton 9.0"))) assertFalse(SteamStorage.isTool(manifest(204360, "CastleCrashers"))) } diff --git a/app/src/test/java/com/droiddeck/launcher/stores/StoreAccountsCipherTest.kt b/app/src/test/java/com/droiddeck/launcher/stores/StoreAccountsCipherTest.kt index cd14c66602..9924c2b50a 100644 --- a/app/src/test/java/com/droiddeck/launcher/stores/StoreAccountsCipherTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/stores/StoreAccountsCipherTest.kt @@ -132,6 +132,17 @@ class StoreAccountsCipherTest { assertEquals("test@example.test", StoreAccounts.signedInAs(app, Store.XBOX)) } + @Test fun rockstarNeverFallsBackToPlaintextWhenKeystoreFails() { + StoreAccounts.keys = broken + org.junit.Assert.assertThrows(IllegalStateException::class.java) { + StoreAccounts.write(app, Store.ROCKSTAR, JSONObject().put("access_token", "synthetic-secret")) + } + assertFalse(file(Store.ROCKSTAR).exists()) + StoreAccounts.keys = fake + StoreAccounts.write(app, Store.ROCKSTAR, creds) + assertTrue(CredentialCipher.isEnvelope(JSONObject(file(Store.ROCKSTAR).readText()))) + } + @Test fun xboxShowsTheGamertagElseAMaskedEmail() { StoreAccounts.write(app, Store.XBOX, JSONObject().put("username", "player@example.test")) assertEquals("pโ€ขโ€ขโ€ข@example.test", StoreAccounts.displayName(app, Store.XBOX)) diff --git a/app/src/test/java/com/droiddeck/launcher/stores/StoreSizesTest.kt b/app/src/test/java/com/droiddeck/launcher/stores/StoreSizesTest.kt new file mode 100644 index 0000000000..2a306aeff8 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/stores/StoreSizesTest.kt @@ -0,0 +1,96 @@ +package com.droiddeck.launcher.stores + +import java.util.concurrent.CompletableFuture +import java.util.concurrent.ConcurrentHashMap +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotSame +import org.junit.Assert.assertSame +import org.junit.Assert.assertTrue +import org.junit.Test + +class StoreSizesTest { + private val ea = CatalogItem(Store.EA, "Origin.OFR.50.0001", "Game", imageUrl = null, owned = true) + + @After fun clear() { + StoreSizes.known.clear() + } + + @Test fun anUnresolvedSizeIsUnknown() { + assertEquals(0L, StoreSizes.size(ea)) + } + + @Test fun aResolvedSizeReplacesTheCatalogValue() { + StoreSizes.known[ea.key] = 4_200_000_000L + assertEquals(4_200_000_000L, StoreSizes.size(ea)) + } + + @Test fun aResolvedSizeOnlyAppliesToItsOwnGame() { + StoreSizes.known[ea.key] = 4_200_000_000L + assertEquals(0L, StoreSizes.size(ea.copy(id = "Origin.OFR.50.0002"))) + assertEquals(7L, StoreSizes.size(ea.copy(id = "Origin.OFR.50.0002", sizeBytes = 7L))) + } + + @Test fun anEaSizeDoesNotReplaceAnotherStoresCatalogSize() { + StoreSizes.known[ea.key] = 4_200_000_000L + val epic = ea.copy(store = Store.EPIC, id = "Epic.Game", sizeBytes = 7L) + assertEquals(7L, StoreSizes.size(epic)) + } + + @Test fun aFailedLookupIsRetriedOnTheNextRequest() { + val requests = ConcurrentHashMap>() + val failed = StoreSizes.shared(requests, ea.key) { CompletableFuture.completedFuture(null) } + assertEquals(null, failed.get()) + val retried = StoreSizes.shared(requests, ea.key) { CompletableFuture.completedFuture(9L) } + assertNotSame(failed, retried) + assertEquals(9L, retried.get()) + } + + @Test fun aResolvedLookupIsSharedAndKept() { + val requests = ConcurrentHashMap>() + val first = StoreSizes.shared(requests, ea.key) { CompletableFuture.completedFuture(5L) } + val second = StoreSizes.shared(requests, ea.key) { CompletableFuture.completedFuture(6L) } + assertSame(first, second) + assertEquals(5L, second.get()) + } + + @Test fun anInFlightLookupIsSharedBetweenRequests() { + val requests = ConcurrentHashMap>() + val pending = CompletableFuture() + val first = StoreSizes.shared(requests, ea.key) { pending } + val second = StoreSizes.shared(requests, ea.key) { CompletableFuture.completedFuture(1L) } + assertSame(first, second) + pending.complete(null) + assertEquals(null, second.get()) + assertEquals(0, requests.size) + } + + @Test fun aContinuationThatRequestsAgainAfterAFailureStartsANewLookup() { + val requests = ConcurrentHashMap>() + val pending = CompletableFuture() + val first = StoreSizes.shared(requests, ea.key) { pending } + val retried = CompletableFuture() + first.thenAccept { bytes -> + if (bytes == null) retried.complete(StoreSizes.shared(requests, ea.key) { CompletableFuture.completedFuture(9L) }.get()) + } + pending.complete(null) + assertEquals(9L, retried.get()) + } + + @Test fun concurrentCallersShareOneLookup() { + val requests = ConcurrentHashMap>() + val pending = CompletableFuture() + var starts = 0 + val callers = (1..3).map { StoreSizes.shared(requests, ea.key) { starts++; pending } } + pending.complete(3L) + assertEquals(1, starts) + callers.forEach { assertEquals(3L, it.get()) } + } + + @Test fun synchronousStartFailureCompletesAndAllowsRetry() { + val requests = ConcurrentHashMap>() + val failed = StoreSizes.shared(requests, ea.key) { throw IllegalStateException("boom") } + assertTrue(failed.isCompletedExceptionally) + assertEquals(4L, StoreSizes.shared(requests, ea.key) { CompletableFuture.completedFuture(4L) }.get()) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/stores/ea/EaTest.kt b/app/src/test/java/com/droiddeck/launcher/stores/ea/EaTest.kt index a52485035e..b9deb11a11 100644 --- a/app/src/test/java/com/droiddeck/launcher/stores/ea/EaTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/stores/ea/EaTest.kt @@ -1,5 +1,6 @@ package com.droiddeck.launcher.stores.ea +import com.droiddeck.launcher.stores.CatalogItem import com.droiddeck.launcher.stores.Store import com.droiddeck.launcher.stores.StoreGameSidecar import com.droiddeck.launcher.stores.StoreLaunch @@ -40,6 +41,43 @@ class EaTest { assertNull(EaCrypto.challengeSeed("9", answer)) } + @Test fun onlyTokenRejectionsAreRetried() { + val rejected = EaReply(409, "".toByteArray(), emptyMap()) + val notEntitled = EaReply(409, "".toByteArray(), emptyMap()) + var authCalls = 0 + val success = EaReply(200, ByteArray(0), emptyMap()) + val result = EaOoa.retryTokenRejected { + authCalls++ + if (authCalls == 1) rejected else success + } + assertEquals(2, authCalls) + assertEquals(200, result.status) + + var entitlementCalls = 0 + val refused = EaOoa.retryTokenRejected { + entitlementCalls++ + notEntitled + } + assertEquals(1, entitlementCalls) + assertEquals(409, refused.status) + + val otherAuthFailure = EaReply(409, "".toByteArray(), emptyMap()) + var otherAuthCalls = 0 + val otherRefused = EaOoa.retryTokenRejected { + otherAuthCalls++ + otherAuthFailure + } + assertEquals(1, otherAuthCalls) + assertEquals(409, otherRefused.status) + + var failedCalls = 0 + EaOoa.retryTokenRejected { + failedCalls++ + rejected + } + assertEquals(4, failedCalls) + } + @Test fun licenceRoundTripsThroughTheFileFormat() { val xml = "kh" + "12349tokgsn" @@ -188,6 +226,61 @@ class EaTest { assertEquals(listOf("1", "3"), picked.map { it.first.offerId }) } + @Test fun anOwnedProductWithoutAnActiveGameDownloadIsLeftOut() { + fun row(id: String, type: String, tag: String = type, status: String = "ACTIVE") = + JSONObject().put("productId", id).put("entitlementType", type).put("entitlementTag", tag).put("status", status) + val rows = listOf( + row("DR:106479900", "DEFAULT", "VALIDATED_ONLINE_ACCESS"), + row("DR:231813200", "ORIGIN_DOWNLOAD", status = "DISABLED"), + row("Origin.OFR.50.0003426", "ONLINE_ACCESS"), + row("Origin.OFR.50.0003426", "ORIGIN_DOWNLOAD"), + row("Origin.OFR.50.0005237", "ORIGIN_DOWNLOAD"), + ) + assertEquals(setOf("DR:106479900", "DR:231813200"), EaLibrary.withoutGameDownload(rows).keys) + assertTrue(EaLibrary.withoutGameDownload(emptyList()).isEmpty()) + } + + @Test fun theStorePageNamesEachGameWithItsPrice() { + val game = { slug: String, title: String, date: String, price: String, sale: String, off: Int, free: Boolean -> + """{"slug":"$slug","title":"$title +","isFreeToPlay":$free,"franchiseSlug":"f","tier":"Tier1","releaseDate":"$date", + "packArt":{"ar16X9":"https://img/$slug-wide","ar2X3":"https://img/$slug-tall"},"genres":[{"name":"RPG"}], + "price":{"displayTotal":"$price","displayTotalWithDiscount":"$sale","discountPercentage":$off,"currency":"USD"}}""" + } + val html = """" + val (items, total) = EaStore.parsePage(html, "USD") + assertEquals("", EaStore.parsePage(html, "EUR").first.first().finalPrice) + assertEquals(40, total) + val ultima = items.first() + assertEquals("Ultima VII", ultima.title) + assertEquals("$2.49", ultima.finalPrice) + assertEquals("$4.99", ultima.originalPrice) + assertEquals(50, ultima.discountPercent) + assertEquals("https://www.ea.com/games/f/ultima-7", ultima.storeUrl) + assertTrue(items[1].isFree) + val shelves = EaStore.shelves(items, java.time.Instant.parse("2026-11-12T00:00:00Z")) + assertEquals(listOf("Ultima VII", "REDSEC"), shelves.whatsNew.map { it.title }) + assertEquals(listOf("Ultima VII"), shelves.deals.map { it.title }) + assertEquals(listOf("REDSEC"), shelves.free.map { it.title }) + val owned = CatalogItem(Store.EA, "Origin.OFR.1", "Ultimaโ„ข VII", null, owned = true, extra = mapOf("slug" to "other")) + val marked = com.droiddeck.launcher.stores.StoreFront.markOwned(shelves, listOf(owned), EaStore::sameGame) + assertEquals("Origin.OFR.1", marked.deals.single().id) + assertEquals("https://img/ultima-7-wide", marked.deals.single().imageUrl) + val bf = CatalogItem(Store.EA, "Origin.OFR.50.0005511", "Battlefieldโ„ข", null, owned = true, extra = mapOf("slug" to "glacier", "productName" to "Battlefieldโ„ข 6")) + assertTrue(EaStore.sameGame(CatalogItem(Store.EA, "ea-store:battlefield-6", "Battlefieldโ„ข 6", null, extra = mapOf("slug" to "battlefield-6")), bf)) + assertFalse(EaStore.sameGame(CatalogItem(Store.EA, "ea-store:bf-2042", "Battlefieldโ„ข 2042", null), bf)) + } + + @Test fun titlesMatchAcrossMarksAndAccentsButNeverWhenEmpty() { + assertEquals("pokemon", com.droiddeck.launcher.stores.StoreFront.titleKey("Pokรฉmonโ„ข")) + assertEquals("ใƒ•ใ‚กใ‚คใƒŠใƒซ 7", com.droiddeck.launcher.stores.StoreFront.titleKey("ใƒ•ใ‚กใ‚คใƒŠใƒซยฎ 7")) + val shelf = CatalogItem(Store.EA, "ea-store:a", "โ„ข", null) + assertFalse(EaStore.sameGame(shelf, CatalogItem(Store.EA, "Origin.OFR.2", "ยฎ", null, owned = true))) + } + @Test fun ownedPageParses() { val page = JSONObject( """{"me":{"ownedGameProducts":{"next":"100","items":[{"originOfferId":"Origin.OFR.50.0001","product":{"id":"x","name":"N","downloadable":true,"gameSlug":"titanfall-2", diff --git a/app/src/test/java/com/droiddeck/launcher/stores/gog/GogMaintenanceTest.kt b/app/src/test/java/com/droiddeck/launcher/stores/gog/GogMaintenanceTest.kt index 06c88bfd11..c98c1da30e 100644 --- a/app/src/test/java/com/droiddeck/launcher/stores/gog/GogMaintenanceTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/stores/gog/GogMaintenanceTest.kt @@ -302,10 +302,17 @@ class GogMaintenanceTest { File(folder, "Game.bin").writeText("original") assertThrows(IllegalArgumentException::class.java) { GogFiles.validate(JSONArray("""[{"path":"game.bin"}]"""), folder) } assertThrows(IllegalArgumentException::class.java) { GogFiles.validate(JSONArray("""[{"path":".droiddeck-store.json"}]"""), folder) } + val data = File(folder, "Data").apply { mkdirs() } + val installed = JSONArray() + for (i in 0 until 2000) { File(data, "Part$i.bin").writeText(""); installed.put(JSONObject().put("path", "Data/Part$i.bin")) } + GogFiles.validate(installed, folder) + assertThrows(IllegalArgumentException::class.java) { GogFiles.validate(JSONArray("""[{"path":"Data/Part0.bin"},{"path":"Data/part1.bin"}]"""), folder) } val outside = temporary.newFolder() try { Files.createSymbolicLink(File(folder, "link").toPath(), outside.toPath()) } catch (_: java.nio.file.FileSystemException) { return } assertThrows(IllegalArgumentException::class.java) { GogFiles.inside(folder, "link/game.exe") } + assertThrows(IllegalArgumentException::class.java) { GogFiles.validate(JSONArray("""[{"path":"Data/Part0.bin"},{"path":"link/game.exe"}]"""), folder) } + assertThrows(IllegalArgumentException::class.java) { GogFiles.validate(JSONArray("""[{"path":"a/./file"}]"""), folder) } } @Test fun resumedInstallSpaceCountsOnlyFilesStillMissing() { diff --git a/app/src/test/java/com/droiddeck/launcher/stores/rockstar/RockstarLaunchCipherTest.kt b/app/src/test/java/com/droiddeck/launcher/stores/rockstar/RockstarLaunchCipherTest.kt new file mode 100644 index 0000000000..39031e7c47 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/stores/rockstar/RockstarLaunchCipherTest.kt @@ -0,0 +1,35 @@ +package com.droiddeck.launcher.stores.rockstar + +import org.junit.Assert.assertArrayEquals +import org.junit.Assert.assertThrows +import org.junit.Test + +class RockstarLaunchCipherTest { + private fun bytes(hex: String) = ByteArray(hex.length / 2) { hex.substring(it * 2, it * 2 + 2).toInt(16).toByte() } + + @Test + fun decodesSyntheticCbcVectorsWithBothKeySchedules() { + val outer = bytes("f49a68fe243848826077b14d60b2f43c00000000000000000000000000000000") + val inner = bytes("864b81362b7d5bb23cd69b9bdb1980c500000000000000000000000000000000") + assertArrayEquals("launch-test-0000".toByteArray(), RockstarLaunchCipher.decrypt(outer, bytes("b804c12ac4af4d8962636fa63c00dda6"), false)) + assertArrayEquals("launch-test-0000".toByteArray(), RockstarLaunchCipher.decrypt(inner, bytes("50a6ad87e83fcde3593f86ae889cdaef"), true)) + } + + @Test + fun rejectsBadPaddingAndInvalidCipherSizes() { + val cipher = bytes("f49a68fe243848826077b14d60b2f43c00000000000000000000000000000000") + cipher[15] = (cipher[15].toInt() xor 1).toByte() + assertThrows(IllegalArgumentException::class.java) { RockstarLaunchCipher.decrypt(cipher, ByteArray(16), false) } + for (size in listOf(0, 15, 65552)) { + assertThrows(IllegalArgumentException::class.java) { RockstarLaunchCipher.decrypt(ByteArray(size), ByteArray(16), false) } + } + assertThrows(IllegalArgumentException::class.java) { RockstarLaunchCipher.decode("A".repeat(90001), "") } + } + + @Test + fun rejectsExternalDocumentTypesBeforeXmlParsing() { + assertThrows(IllegalArgumentException::class.java) { + RockstarRos.parse("") + } + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/stores/rockstar/RockstarMetadataTest.kt b/app/src/test/java/com/droiddeck/launcher/stores/rockstar/RockstarMetadataTest.kt new file mode 100644 index 0000000000..cb07f0914e --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/stores/rockstar/RockstarMetadataTest.kt @@ -0,0 +1,78 @@ +package com.droiddeck.launcher.stores.rockstar + +import org.junit.Assert.* +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +import java.nio.ByteBuffer +import java.nio.ByteOrder +import javax.crypto.Cipher +import javax.crypto.spec.IvParameterSpec +import javax.crypto.spec.SecretKeySpec + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [33], application = android.app.Application::class) +class RockstarMetadataTest { + @Test fun findsRootMetadataAfterManyOtherFiles() { + val root = java.nio.file.Files.createTempDirectory("rockstar-many-files").toFile() + try { + repeat(300) { java.io.File(root, "asset-$it.dat").writeText("asset") } + java.io.File(root, "title.rgl").writeBytes(container("""{"titleId":"game","rosTitleId":123,"principalFileName":"Game.exe"}""")) + assertEquals("game", RockstarMetadata.find(root)?.id) + java.io.File(root, "title.rgl").delete() + java.io.File(root, "Title.RGL").writeBytes(container("""{"titleId":"game","rosTitleId":123,"principalFileName":"Game.exe"}""")) + assertEquals("game", RockstarMetadata.find(root)?.id) + } finally { + root.deleteRecursively() + } + } + + private fun container(json: String): ByteArray { + val iv = ByteArray(16) { it.toByte() } + val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding") + cipher.init(Cipher.ENCRYPT_MODE, SecretKeySpec(ByteArray(32), "AES"), IvParameterSpec(iv)) + val payload = iv + cipher.doFinal(json.toByteArray()) + val header = ByteBuffer.allocate(80).order(ByteOrder.LITTLE_ENDIAN) + header.put(byteArrayOf(82, 71, 76, 77)).putInt(1).putInt(payload.size) + return header.array() + payload + } + + @Test fun decodesInstalledTitleWithoutAnAppIdAllowlist() { + val title = RockstarMetadata.decode(container("""{"titleId":"new_title","rosTitleId":123,"principalFileName":"Game/Binaries/Win64/Game.exe"}"""))!! + assertEquals("new_title", title.id) + assertEquals(123, title.rosId) + assertEquals("Game/Binaries/Win64/Game.exe", title.exe) + } + + @Test fun rejectsBrokenContainersAndEscapingExecutables() { + val valid = container("""{"titleId":"game","rosTitleId":123,"principalFileName":"Game.exe"}""") + assertNull(RockstarMetadata.decode(valid.copyOf(90))) + assertNull(RockstarMetadata.decode(valid.copyOf().also { it[4] = 2 })) + assertNull(RockstarMetadata.decode(valid + byteArrayOf(0))) + assertNull(RockstarMetadata.decode(container("""{"titleId":"game","rosTitleId":1.5,"principalFileName":"Game.exe"}"""))) + for (exe in listOf("../outside.exe", "C:/outside.exe", "/outside.exe")) { + assertNull(RockstarMetadata.decode(container("""{"titleId":"game","rosTitleId":123,"principalFileName":"$exe"}"""))) + } + } + + @Test fun doesNotFollowMetadataSymlinksOutsideTheGame() { + val root = java.nio.file.Files.createTempDirectory("rockstar-metadata").toFile() + val outside = java.io.File.createTempFile("rockstar-external", ".rgl") + try { + outside.writeBytes(container("""{"titleId":"game","rosTitleId":123,"principalFileName":"Game.exe"}""")) + val link = java.io.File(root, "title.rgl").toPath() + try { java.nio.file.Files.createSymbolicLink(link, outside.toPath()) } + catch (e: java.nio.file.FileSystemException) { org.junit.Assume.assumeNoException(e) } + assertNull(RockstarMetadata.find(root)) + java.nio.file.Files.delete(link) + java.io.File(root, "nested").mkdir() + outside.copyTo(java.io.File(root, "nested/title.rgl")) + assertEquals("game", RockstarMetadata.find(root)?.id) + assertEquals("nested/Game.exe", RockstarMetadata.find(root)?.exe) + } finally { + root.deleteRecursively() + outside.delete() + } + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/stores/rockstar/RockstarTest.kt b/app/src/test/java/com/droiddeck/launcher/stores/rockstar/RockstarTest.kt new file mode 100644 index 0000000000..755bd7320c --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/stores/rockstar/RockstarTest.kt @@ -0,0 +1,365 @@ +package com.droiddeck.launcher.stores.rockstar + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [33], application = android.app.Application::class) +class RockstarTest { + @Test fun sdkTicketExportsOnlyTheShortLivedServerResponse() { + val root = RockstarRos.parse("""1opaque-game-ticket456session-keysession-ticketexample.invalidservice-refresh-secretrefresh-secret123Playerplayer@example.invalidnested-refresh-secret""") + val sdk = RockstarRos.parse(RockstarAuth.sdkTicket(root)) + assertEquals("opaque-game-ticket", RockstarRos.text(sdk, "Ticket")) + assertEquals("session-key", RockstarRos.text(sdk, "SessionKey")) + assertEquals("123", RockstarRos.text(sdk, "RockstarId")) + assertEquals("456", RockstarRos.text(sdk, "PlayerAccountId")) + assertEquals("1", RockstarRos.first(sdk, "Services")?.getAttribute("Count")) + assertEquals("example.invalid", RockstarRos.text(sdk, "Host")) + assertNull(RockstarRos.first(sdk, "ScAuthToken")) + assertFalse(RockstarAuth.sdkTicket(root).contains("refresh-secret")) + } + + @Test fun sdkTitleStateRequiresAnOwnedPackageInsteadOfCatalogVisibility() { + val visible = RockstarApp("1", "future_title", "123", emptyList()) + val featured = RockstarAccountApps(listOf(visible), listOf(RockstarPackage("future_title", true))) + assertFalse(RockstarLibrary.owns(featured, 123, "future_title")) + val owned = RockstarAccountApps(listOf(visible), listOf(RockstarPackage("future_title", false))) + assertTrue(RockstarLibrary.owns(owned, 123, "future_title")) + assertFalse(RockstarLibrary.owns(owned, 124, "other_title")) + } + + @Test fun directLaunchPreservesArgumentsThroughTheWindowsBatchInterpreter() { + org.junit.Assume.assumeTrue(java.io.File.separatorChar == '\\') + val root = java.nio.file.Files.createTempDirectory("rockstar-batch").toFile() + try { + java.io.File(System.getenv("SystemRoot"), "System32/cscript.exe").copyTo(java.io.File(root, "Game.exe")) + java.io.File(root, "probe.vbs").writeText(""" + Set output = CreateObject("Scripting.FileSystemObject").CreateTextFile("args.txt", True) + For Each arg In WScript.Arguments + output.WriteLine(arg) + Next + output.Close + """.trimIndent()) + val args = listOf("", "&literal", "one argument", "%PATH%", "!PATH!", "^&|<>()") + val game = com.droiddeck.launcher.stores.StoreGameSidecar(com.droiddeck.launcher.stores.Store.ROCKSTAR, + "future_title", "Game", "Game.exe", args = listOf("//nologo", "probe.vbs") + args) + com.droiddeck.launcher.stores.StoreLaunch.writeLauncher(root, game) + val process = ProcessBuilder("cmd.exe", "/d", "/c", java.io.File(root, com.droiddeck.launcher.stores.StoreLaunch.LAUNCHER).path) + .directory(root).redirectErrorStream(true).start() + assertTrue(process.waitFor(10, java.util.concurrent.TimeUnit.SECONDS)) + assertEquals(process.inputStream.bufferedReader().readText(), 0, process.exitValue()) + assertEquals(args, java.io.File(root, "args.txt").readLines()) + } finally { + root.deleteRecursively() + } + } + + @Test fun launcherAdoptionDoesNotFollowSymbolicLinks() { + val folder = java.nio.file.Files.createTempDirectory("rockstar-launch-link").toFile() + val outside = java.io.File.createTempFile("rockstar-keep", ".txt").apply { writeText("keep") } + val link = java.io.File(folder, com.droiddeck.launcher.stores.StoreLaunch.LAUNCHER) + try { + try { + java.nio.file.Files.createSymbolicLink(link.toPath(), outside.toPath()) + } catch (e: java.nio.file.FileSystemException) { + org.junit.Assume.assumeNoException(e) + } + java.io.File(folder, "gta3.exe").writeText("game") + val game = com.droiddeck.launcher.stores.StoreGameSidecar(com.droiddeck.launcher.stores.Store.ROCKSTAR, "gta3", "GTA III", "gta3.exe", launcher = com.droiddeck.launcher.stores.StoreLaunch.LAUNCHER) + assertNull(com.droiddeck.launcher.stores.StoreLaunch.adopt(folder, game).launcher) + assertNull(com.droiddeck.launcher.stores.StoreLaunch.writeLauncher(folder, game).launcher) + assertEquals("keep", outside.readText()) + assertTrue(java.nio.file.Files.isSymbolicLink(link.toPath())) + } finally { + java.nio.file.Files.deleteIfExists(link.toPath()) + folder.deleteRecursively() + outside.delete() + } + } + + @Test fun resumeHashingStopsWhenCancelled() { + val file = java.io.File.createTempFile("rockstar-hash", ".bin") + try { + val bytes = ByteArray(1024 * 1024) + file.writeBytes(bytes) + val hash = java.security.MessageDigest.getInstance("SHA-256").digest(bytes).joinToString("") { "%02x".format(it) } + val chunk = RockstarChunk("1", "1", hash, 0, bytes.size.toLong()) + var checks = 0 + assertFalse(RockstarManifest.verified(file, chunk) { ++checks >= 3 }) + assertEquals(3, checks) + assertTrue(RockstarManifest.verified(file, chunk)) + } finally { + file.delete() + } + } + + @Test fun otherRockstarGamesRegisterAndLaunchTheirInstalledExecutable() { + val app = org.robolectric.RuntimeEnvironment.getApplication() + com.droiddeck.launcher.session.SessionPrefs.setGameStorage(app, com.droiddeck.launcher.session.SessionPrefs.GAME_STORAGE_OFF, "") + val folder = java.io.File(com.droiddeck.launcher.stores.StoreInstallRoot.storeDir(com.droiddeck.launcher.stores.StoreInstallRoot.installRoot(app), com.droiddeck.launcher.stores.Store.ROCKSTAR), "RDR2").apply { mkdirs() } + try { + val game = com.droiddeck.launcher.stores.StoreGameSidecar(com.droiddeck.launcher.stores.Store.ROCKSTAR, "rdr2", "RDR2", "RDR2.exe") + java.io.File(folder, game.exe).writeText("installed game") + val script = java.io.File(folder, com.droiddeck.launcher.stores.StoreLaunch.LAUNCHER) + script.writeText("old launcher") + val finished = com.droiddeck.launcher.stores.StoreLaunch.writeLauncher(folder, game) + finished.write(folder) + assertFalse(RockstarLaunch.usesClassicLauncher(game.id)) + assertEquals(com.droiddeck.launcher.stores.StoreLaunch.LAUNCHER, finished.launcher) + assertTrue(script.readText().contains("\"%~dp0RDR2.exe\"")) + assertTrue(script.readText().contains("if not exist \"C:\\Program Files\\Rockstar Games\\Launcher\\launch.json\" goto direct")) + assertTrue(java.io.File(folder, game.exe).isFile) + } finally { + folder.deleteRecursively() + } + } + + @Test fun otherRockstarGamesCanRegisterShortcuts() { + org.junit.Assume.assumeTrue(java.io.File.separatorChar == '/') + val app = org.robolectric.RuntimeEnvironment.getApplication() + com.droiddeck.launcher.session.SessionPrefs.setGameStorage(app, com.droiddeck.launcher.session.SessionPrefs.GAME_STORAGE_OFF, "") + val folder = java.io.File(com.droiddeck.launcher.stores.StoreInstallRoot.storeDir(com.droiddeck.launcher.stores.StoreInstallRoot.installRoot(app), com.droiddeck.launcher.stores.Store.ROCKSTAR), "RDR2").apply { mkdirs() } + try { + java.io.File(folder, "RDR2.exe").writeText("installed game") + com.droiddeck.launcher.stores.StoreGameSidecar(com.droiddeck.launcher.stores.Store.ROCKSTAR, "rdr2", "RDR2", "RDR2.exe").write(folder) + val game = com.droiddeck.launcher.frontend.AddedGames.single(app, folder.path) + assertTrue(game != null) + assertTrue(game!!.guestExe.endsWith("/" + com.droiddeck.launcher.stores.StoreLaunch.LAUNCHER)) + } finally { + folder.deleteRecursively() + } + } + + @Test fun existingRockstarLaunchScriptsAreRefreshed() { + val folder = java.nio.file.Files.createTempDirectory("rockstar-launch").toFile() + try { + java.io.File(folder, "gta3.exe").writeBytes(byteArrayOf(1)) + val game = com.droiddeck.launcher.stores.StoreGameSidecar(com.droiddeck.launcher.stores.Store.ROCKSTAR, "gta3", "GTA III", "gta3.exe", launcher = com.droiddeck.launcher.stores.StoreLaunch.LAUNCHER) + val script = java.io.File(folder, com.droiddeck.launcher.stores.StoreLaunch.LAUNCHER) + script.writeText("old launch script") + com.droiddeck.launcher.stores.StoreLaunch.adopt(folder, game) + assertTrue(script.readText().contains("Rockstar Games\\Launcher\\Launcher.exe")) + assertFalse(script.readText().contains("old launch script")) + } finally { + folder.deleteRecursively() + } + } + + @Test + @Config(sdk = [28]) + fun classicLaunchDefaultsAreSetBeforeWineAndKeepExplicitSettings() { + val app = org.robolectric.RuntimeEnvironment.getApplication() + val explicit = com.droiddeck.launcher.core.GameEnvironment.Config(games = mapOf( + "100" to mapOf("FEX_X87REDUCEDPRECISION" to "1"), + "104" to mapOf("PROTON_USE_WINED3D" to "0"), + )) + com.droiddeck.launcher.session.GameEnvironmentStore.save(app, explicit) + RockstarLaunch.applyDefaults(app, "gta3", 100) + RockstarLaunch.applyDefaults(app, "gta3", 101) + RockstarLaunch.applyDefaults(app, "gtasa", 102) + RockstarLaunch.applyDefaults(app, "gtavc", 103) + RockstarLaunch.applyDefaults(app, "gtasa", 104) + val config = com.droiddeck.launcher.session.GameEnvironmentStore.read(app) + assertEquals("1", config.games["100"]?.get("FEX_X87REDUCEDPRECISION")) + assertEquals("0", config.games["101"]?.get("FEX_X87REDUCEDPRECISION")) + assertEquals(mapOf("PROTON_USE_WINED3D" to "1"), config.games["102"]) + assertEquals("0", config.games["104"]?.get("PROTON_USE_WINED3D")) + assertFalse(config.games.containsKey("103")) + } + + @Test fun classicTitlesUseTheirObservedPipeNames() { + assertEquals(mapOf("gta3" to "GTA3_Pipe", "gtavc" to "GTA-VC_Pipe", "gtasa" to "GTA_SA_Pipe", "gta4" to "GTAIV_Pipe", "lanoire" to "LANOIRE_Pipe"), RockstarLaunch.pipes) + for (id in RockstarLaunch.pipes.keys) assertTrue(RockstarLaunch.usesClassicLauncher(id)) + } + + @Test fun signingOutClearsOwnedShelfCards() { + val store = com.droiddeck.launcher.stores.Store.ROCKSTAR + com.droiddeck.launcher.stores.StoresState.library[store] = emptyList() + com.droiddeck.launcher.stores.StoresState.shelves[store] = com.droiddeck.launcher.stores.StoreShelves() + RockstarLibrary.reset() + org.robolectric.shadows.ShadowLooper.idleMainLooper() + assertFalse(com.droiddeck.launcher.stores.StoresState.library.containsKey(store)) + assertFalse(com.droiddeck.launcher.stores.StoresState.shelves.containsKey(store)) + } + + @Test fun resumedChunksMustStillMatchTheirFiles() { + val folder = java.nio.file.Files.createTempDirectory("rockstar-resume").toFile() + try { + val file = java.io.File(folder, "game.bin") + val bytes = "verified chunk".toByteArray() + val hash = java.security.MessageDigest.getInstance("SHA-256").digest(bytes).joinToString("") { "%02x".format(it) } + val chunk = RockstarChunk("1", "2", hash, 2, bytes.size.toLong()) + assertFalse(RockstarManifest.verified(file, chunk)) + file.writeBytes(byteArrayOf(0, 0) + bytes) + assertTrue(RockstarManifest.verified(file, chunk)) + java.io.RandomAccessFile(file, "rw").use { it.setLength(4) } + assertFalse(RockstarManifest.verified(file, chunk)) + file.writeBytes(ByteArray(bytes.size + 2)) + assertFalse(RockstarManifest.verified(file, chunk)) + } finally { + folder.deleteRecursively() + } + } + + @Test fun manifestWritesRejectSymbolicLinks() { + val folder = java.nio.file.Files.createTempDirectory("rockstar-path").toFile() + val outside = java.nio.file.Files.createTempDirectory("rockstar-outside").toFile() + try { + val link = java.io.File(folder, "linked") + try { + java.nio.file.Files.createSymbolicLink(link.toPath(), outside.toPath()) + } catch (e: java.nio.file.FileSystemException) { + org.junit.Assume.assumeNoException(e) + } + assertTrue(runCatching { RockstarManifest.inside(folder, "linked/game.bin") }.isFailure) + assertEquals(java.io.File(folder.canonicalFile, "normal/game.bin"), RockstarManifest.inside(folder, "normal/game.bin")) + java.nio.file.Files.deleteIfExists(link.toPath()) + } finally { + folder.deleteRecursively() + outside.deleteRecursively() + } + } + + @Test + fun rockstarLaunchScriptsContainNoCredentials() { + val sidecar = com.droiddeck.launcher.stores.StoreGameSidecar( + com.droiddeck.launcher.stores.Store.ROCKSTAR, "gtavc", "Vice City", "gta-vc.exe", + ) + val text = com.droiddeck.launcher.stores.StoreLaunch.launcherText(sidecar) + assertTrue(text.contains("\"C:\\Program Files\\Rockstar Games\\Launcher\\Launcher.exe\"")) + assertTrue(text.contains("exit /b %errorlevel%")) + assertTrue(text.contains("goto direct")) + assertTrue(text.contains("\"%~dp0gta-vc.exe\"")) + assertFalse(text.contains("ticket", true)) + assertFalse(text.contains("rem ", true)) + } + + private val apps = """ +1 + + BRANCHACCESS token="L" + + + + + BRANCHACCESS token="S" + + + BRANCHACCESS token="B" + BRANCHACCESS token="D" + + + + {"title":"gta4","isFeatured":false,"packageType":"title"} + {"title":"rdr2","isFeatured":false,"packageType":"title"} + {"title":"gtatrilogy","isFeatured":true,"packageType":"bundle"} + {"title":"gta5","isFeatured":false,"packageType":"title"} +""" + + private fun account(xml: String = apps) = RockstarRos.parse(xml).let { RockstarAccountApps(RockstarApps.parse(it), RockstarApps.packages(it)) } + + private val manifest = """ +1 + + + Launcher.exe + + FF + + + ThirdParty\Steam\steam_api64.dll + + ee + + false""" + + @Test fun branchesNeedARealBuild() { + val parsed = account().apps + val gta4 = parsed.first { it.name == "gta4" } + assertEquals("31", RockstarApps.branch(gta4)!!.id) + assertNull(RockstarApps.branch(parsed.first { it.name == "rdr2_sp_steam" })) + assertNull(RockstarApps.branch(parsed.first { it.name == "gta5" })) + } + + @Test fun ownedTitlesAreTheAccountsOwnPackagesNotTheFeaturedOnes() { + assertEquals(listOf("gta4", "rdr2", "gta5"), RockstarLibrary.owned(account()).map { it.id }) + } + + @Test fun libraryListsOnlyOwnedTitlesRockstarDelivers() { + val games = RockstarLibrary.games(account()) + assertEquals(listOf("gta4"), games.map { it.id }) + assertEquals("gta4", games[0].extra["app"]) + assertTrue(games.all { it.owned }) + } + + @Test fun anOwnedTrilogyBundleIsAllThreeDefinitiveEditions() { + val owned = RockstarLibrary.owned(account(apps.replace("\"isFeatured\":true,\"packageType\":\"bundle\"", "\"isFeatured\":false,\"packageType\":\"bundle\""))) + assertTrue(owned.map { it.id }.containsAll(listOf("gta3unreal", "gtavcunreal", "gtasaunreal"))) + } + + @Test fun manifestFilesCarryTheirChunksAndWindowsPathsBecomeRelative() { + val build = RockstarManifest.parse(RockstarRos.parse(manifest)) + assertEquals("1311", build.buildId) + assertFalse(build.preload) + assertEquals(34L, build.bytes) + val exe = build.files[0] + assertEquals(listOf("46859", "46860"), exe.chunks.map { it.chunkId }) + assertEquals("ab", exe.chunks[0].sha256) + assertEquals("ff", exe.sha256) + assertEquals("ThirdParty/Steam/steam_api64.dll", build.files[1].path) + } + + @Test fun pathsThatLeaveTheInstallAreRefused() { + assertNull(RockstarManifest.safePath("..\\..\\Windows\\x.dll")) + assertNull(RockstarManifest.safePath("C:\\x.dll")) + assertEquals("a/b.rpf", RockstarManifest.safePath("\\a\\.\\b.rpf")) + } + + @Test fun urlBatchesStayWithinTheirByteAndCountLimits() { + val chunks = (1..5).map { RockstarChunk("1", "$it", "", 0, if (it == 3) 100 else 10) } + val batches = RockstarManifest.batches(chunks, maxBytes = 30, maxCount = 2) + assertEquals(listOf(listOf("1", "2"), listOf("3"), listOf("4", "5")), batches.map { b -> b.map { it.chunkId } }) + } + + @Test fun rosErrorsNameTheirCode() { + val root = RockstarRos.parse("0") + assertEquals("AuthenticationFailed", RockstarRos.first(root, "Error")!!.getAttribute("Code")) + } + + @Test fun ticketAnswerGivesTheAccountAndExpiry() { + val root = RockstarRos.parse("""1TK + S86399 + 42player""") + val t = RockstarAuth.parseTicket(root, now = 1000L)!! + assertEquals("T", t.ticket) + assertEquals("42", t.rockstarId) + assertEquals("player", t.nickname) + assertEquals(1000L + 86_399_000L, t.expiresAt) + } + + @Test fun gatewayStateIsWrittenAsThePageWritesIt() { + val fp = RockstarAuth.fingerprintOf("DROIDDECK-DUO", "0a0b0c0d", "0011223344556677") + assertEquals("{\"fp\": {\"device_name\":\"DROIDDECK-DUO\",\"machine_name\":\"DROIDDECK-DUO\",\"os_version\":\"10.0.19045\",\"volume_serial\":\"0a0b0c0d\",\"cpu_info\":\"0011223344556677\"}}", + RockstarAuth.state(fp)) + } + + @Test fun bridgeAnswersTheLauncherQueriesAndHandsBackTheCode() { + val js = RockstarAuth.bridgeScript(RockstarAuth.fingerprintOf("D", "1", "2"), "launcher") + for (m in listOf("GetWindowConfig", "GetDeviceId", "GetVersionInfo", "GetProfileList", "OnStartAuth", "CallAuthResult", "rgscQueryCancel", "/signin/user-form?cid=launcher")) + assertTrue(m, m in js) + assertTrue(RockstarAuth.isCodeUrl(RockstarAuth.CODE_URL + "?code=abc")) + assertEquals("a+b/c", RockstarAuth.codeFrom(RockstarAuth.CODE_URL + "?code=a%2Bb%2Fc")) + } + + @Test fun subAppsResolveToTheirGame() { + assertEquals("rdr2", RockstarTitles.byId("rdr2_sp_rgl")!!.id) + assertEquals("gtasaunreal", RockstarTitles.byId("gtatrilogy")!!.id) + assertNull(RockstarTitles.byId("launcher")) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/stores/ubisoft/UbisoftTest.kt b/app/src/test/java/com/droiddeck/launcher/stores/ubisoft/UbisoftTest.kt index 58e361db81..aecf4ca779 100644 --- a/app/src/test/java/com/droiddeck/launcher/stores/ubisoft/UbisoftTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/stores/ubisoft/UbisoftTest.kt @@ -1,5 +1,6 @@ package com.droiddeck.launcher.stores.ubisoft +import com.droiddeck.launcher.stores.CatalogItem import com.droiddeck.launcher.stores.Store import com.droiddeck.launcher.stores.StoreGameSidecar import com.droiddeck.launcher.stores.StoreLaunch @@ -20,18 +21,58 @@ class UbisoftTest { private val steamConfig = "version: 2.0\r\nroot:\r\n name: Assassin's Creed Syndicate\r\n start_game:\r\n steam:\r\n steam_app_id: 368500\r\n" + " third_party_platform:\r\n name: Steam\r\n override_uplayid: 1875\r\n" - @Test fun aProductUbisoftDeliversThroughSteamNamesItsSteamApp() { - assertEquals("368500", UbisoftLibrary.steamApp(steamConfig)) - assertNull(UbisoftLibrary.steamApp("root:\n start_game:\n online:\n executables:\n - path:\n relative: bin/game.exe\n")) + private fun listed(space: String, name: String) = CatalogItem(Store.UBISOFT, space, name, null, owned = true, extra = mapOf("spaceId" to space)) + + private val owned = JSONObject().put("games", JSONArray() + .put(JSONObject().put("productId", 1957).put("spaceId", "space-s").put("productType", 0).put("owned", true).put("configuration", steamConfig)) + .put(JSONObject().put("productId", 109).put("spaceId", "space-sc").put("productType", 0).put("owned", true).put("manifest", "AB").put("configuration", "root: {}")) + .put(JSONObject().put("productId", 1961).put("spaceId", "space-addon").put("productType", 1).put("owned", true).put("manifest", "CD").put("configuration", steamConfig)) + .put(JSONObject().put("productId", 720).put("spaceId", "space-plus").put("productType", 0).put("owned", false).put("manifest", "EF").put("configuration", "root: {}")) + .put(JSONObject().put("productId", 3539).put("spaceId", "space-o").put("productType", 0).put("owned", true).put("configuration", "root: {}"))) + + @Test fun onlyGamesConnectDeliversAreInTheLibrary() { + val profile = listOf(listed("space-sc", "Splinter Cell"), listed("space-s", "Syndicate"), listed("space-plus", "Ubisoft+ Game"), listed("space-gone", "Free Weekend"), listed("space-o", "Origins")) + val games = UbisoftLibrary.assemble(profile, owned) + assertEquals(listOf("space-o", "space-sc"), games.map { it.id }) + assertEquals(listOf("3539", "109"), games.map { it.extra["productId"] }) + assertEquals(null, games.first().extra["manifest"]) + assertEquals("Steam", UbisoftLibrary.thirdParty(steamConfig)) } - @Test fun steamOwnedGamesAreKeyedByTheirSpace() { - val owned = JSONObject().put("games", JSONArray() - .put(JSONObject().put("productId", 1957).put("spaceId", "space-s").put("productType", 0).put("owned", true).put("configuration", steamConfig)) - .put(JSONObject().put("productId", 109).put("spaceId", "space-sc").put("productType", 0).put("owned", true).put("manifest", "AB").put("configuration", "root: {}")) - .put(JSONObject().put("productId", 1961).put("spaceId", "space-addon").put("productType", 1).put("owned", true).put("configuration", steamConfig))) - assertEquals(mapOf("space-s" to "368500"), UbisoftLibrary.steamBySpace(owned)) - assertEquals(setOf("space-sc"), UbisoftLibrary.ownedBySpace(owned).keys) + @Test fun withoutAnOwnershipAnswerTheProfileListStays() { + val profile = listOf(listed("space-sc", "Splinter Cell"), listed("space-gone", "Free Weekend")) + assertEquals(listOf("space-gone", "space-sc"), UbisoftLibrary.assemble(profile, JSONObject().put("error", "demux closed")).map { it.id }) + assertEquals(listOf("space-gone", "space-sc"), UbisoftLibrary.assemble(profile, null).map { it.id }) + } + + @Test fun theStoreSearchNamesEachGameWithItsPrice() { + fun hit(id: String, title: String, price: Double, base: Double, off: String, date: String, free: String = "") = JSONObject() + .put("objectID", id).put("title", title).put("price", JSONObject().put("USD", price)).put("default_price", JSONObject().put("USD", base)) + .put("promotion_percentage", off).put("release_date", date).put("Free_offer", free).put("link", "https://store.ubisoft.com/us/$id.html") + .put("image_link", "https://img/$id.jpg?sw=300").put("productLauncherIDString", id.takeLast(3)).put("Rating", "esrb-m") + val answer = JSONObject().put("hits", JSONArray() + .put(hit("p-109", "Far Cryยฎ 6", 15.0, 60.0, "75", "2021-10-07T00:00:00.000Z")) + .put(hit("p-110", "Far Cryยฎ 6 - Gold Edition", 30.0, 100.0, "70", "2021-10-07T00:00:00.000Z")) + .put(hit("p-111", "Some Demo", 0.0, 0.0, "", "2021-10-07T00:00:00.000Z", free = "demo")) + .put(hit("p-112", "Next Year", 70.0, 70.0, "", "2030-01-01T00:00:00.000Z"))) + val items = UbisoftStore.parse(answer, "USD", java.time.Instant.parse("2026-11-12T00:00:00Z")) + assertEquals(listOf("Far Cryยฎ 6"), items.map { it.title }) + val game = items.single() + assertEquals("$15.00", game.finalPrice) + assertEquals("$60.00", game.originalPrice) + assertEquals(75, game.discountPercent) + assertEquals("https://img/p-109.jpg", game.imageUrl) + assertTrue(game.mature) + val owned = CatalogItem(Store.UBISOFT, "space-fc6", "Far Cry 6", null, owned = true, extra = mapOf("productId" to "5266")) + val ezio = CatalogItem(Store.UBISOFT, "ubisoft-store:x", "Assassin's Creedยฎ The Ezio Collection", null) + assertTrue(UbisoftStore.sameGame(game, owned)) + assertTrue(!UbisoftStore.sameGame(ezio, CatalogItem(Store.UBISOFT, "space-ac", "Assassin's Creedโ„ข", null, owned = true))) + } + + @Test fun theBaseEditionStandsForItsGameWhicheverComesFirst() { + fun hit(id: String, title: String) = JSONObject().put("objectID", id).put("title", title).put("price", JSONObject().put("USD", 10.0)) + val answer = JSONObject().put("hits", JSONArray().put(hit("gold", "Far Cryยฎ 6 - Gold Edition")).put(hit("base", "Far Cryยฎ 6"))) + assertEquals(listOf("ubisoft-store:base"), UbisoftStore.parse(answer, "USD").map { it.id }) } @Test fun theEntitlementNamesTheGamesApplication() { diff --git a/app/src/test/java/com/droiddeck/launcher/ui/AgentChangesTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/AgentChangesTest.kt new file mode 100644 index 0000000000..38eddd563b --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/ui/AgentChangesTest.kt @@ -0,0 +1,41 @@ +package com.droiddeck.launcher.ui + +import com.droiddeck.launcher.agent.AgentHost.Entry +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test + +class AgentChangesTest { + @Test fun aTurnAddsUpTheEditsItMade() { + val entries = listOf( + Entry.Asked("before"), Entry.Used("e0", "Edit", "old.kt", "old.kt\n-a\n+b"), Entry.Finished(null), + Entry.Asked("fix it"), + Entry.Used("e1", "Edit", "a.kt", "src/a.kt\n x\n-y\n+z\n+w"), + Entry.Used("e2", "Write", "b.kt", "src/b.kt\n+one"), + Entry.Used("e3", "Edit", "a.kt", "src/a.kt\n-q", failed = true), + Entry.Used("e4", "Edit", "a.kt", "src/a.kt\n-r"), + Entry.Used("b1", "Bash", "ls", "ls"), + Entry.Finished(null), + ) + assertEquals(Changes(files = 2, added = 3, removed = 2), turnChanges(entries, entries.lastIndex)) + assertEquals(Changes(1, 1, 1), turnChanges(entries, 2)) + } + + @Test fun onlyEditsCarryingADiffCount() { + assertNull(diffOf(Entry.Used("c", "Edit", "a.kt, b.kt", "a.kt\nb.kt"))) + assertNull(diffOf(Entry.Used("b", "Bash", "ls", "ls\n+x"))) + assertEquals(2, diffOf(Entry.Used("e", "Edit", "a.kt", "a.kt\n\n- old\n\n+ new"))?.lines?.size) + assertNull(turnChanges(listOf(Entry.Asked("hi"), Entry.Said("hello"), Entry.Finished(null)), 2)) + } + + @Test fun aSavedPlanIsNotAChange() { + val entries = listOf(Entry.Asked("plan it"), Entry.Used("w", "Write", "plan.md", "/root/.claude/plans/plan.md\n+step"), Entry.Finished(null)) + assertNull(turnChanges(entries, 2)) + } + + @Test fun bigCountsReadAsMillions() { + assertEquals("1M", tokens(1_000_000)) + assertEquals("1.5M", tokens(1_500_000)) + assertEquals("23k", tokens(23_400)) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/ui/AgentMarkdownTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/AgentMarkdownTest.kt index c7ad34d894..171fe16f9f 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/AgentMarkdownTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/AgentMarkdownTest.kt @@ -1,27 +1,176 @@ package com.droiddeck.launcher.ui -import androidx.compose.ui.graphics.Color -import org.junit.Assert.assertEquals +import android.content.Intent +import android.content.ClipboardManager +import android.text.Selection +import android.text.Spannable +import io.noties.markwon.ext.tables.TableRowSpan +import android.graphics.Color +import android.text.Spanned +import android.text.style.ClickableSpan +import android.widget.TextView +import org.junit.Assert.* import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.Shadows.shadowOf +import org.robolectric.annotation.ConscryptMode +import org.robolectric.annotation.Config +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28], manifest = Config.NONE) +@ConscryptMode(ConscryptMode.Mode.OFF) class AgentMarkdownTest { - @Test fun blocksSplitHeadingsBulletsAndCode() { - val blocks = markdownBlocks("## Done\n\n- one\n* two\n```kotlin\nval a = 1\n\nval b = 2\n```\nplain") - assertEquals( - listOf( - MdBlock.Line("Done", heading = true), - MdBlock.Line("โ€ข one", bullet = true), - MdBlock.Line("โ€ข two", bullet = true), - MdBlock.Code("val a = 1\n\nval b = 2"), - MdBlock.Line("plain"), - ), - blocks, - ) + private val context get() = RuntimeEnvironment.getApplication() + private val renderer get() = agentMarkdownRenderer(context, Color.BLUE, Color.DKGRAY) + private fun Spanned.links() = getSpans(0, length, ClickableSpan::class.java).toList() + + @Test fun namedPullRequestLinksKeepTheirLabelsAndOpenAnExternalBrowser() { + val text = renderer.toMarkdown("Created [**PR #2540**](https://github.com/Droid-Deck/DroidDeck/pull/2540).") + assertEquals("Created PR #2540.", text.toString()) + val link = text.links().single() + assertEquals("PR #2540", text.subSequence(text.getSpanStart(link), text.getSpanEnd(link)).toString()) + link.onClick(TextView(context)) + val intent = shadowOf(context).nextStartedActivity + assertEquals(Intent.ACTION_VIEW, intent.action) + assertEquals("https://github.com/Droid-Deck/DroidDeck/pull/2540", intent.dataString) + val browser = requireNotNull(intent.selector) + assertEquals(Intent.ACTION_MAIN, browser.action) + assertTrue(browser.hasCategory(Intent.CATEGORY_APP_BROWSER)) + assertTrue(intent.flags and Intent.FLAG_ACTIVITY_NEW_TASK != 0) } - @Test fun inlineMarkersAreDroppedAndUnclosedOnesKept() { - val text = inlineMarkdown("a **b** `c` d ** e ` f", Color.Red, Color.Black) - assertEquals("a b c d ** e ` f", text.text) - assertEquals(2, text.spanStyles.size) + @Test fun bareUrlsAndAutolinksAreClickableWithoutTrailingPunctuation() { + val text = renderer.toMarkdown("Visit https://github.com/Droid-Deck/DroidDeck/pull/2540. Also .") + assertEquals(2, text.links().size) + val labels = text.links().map { text.subSequence(text.getSpanStart(it), text.getSpanEnd(it)).toString() } + assertTrue(labels.contains("https://github.com/Droid-Deck/DroidDeck/pull/2540")) + assertTrue(labels.contains("https://example.org/help")) + } + + @Test fun referenceLinksAndEscapedParenthesesAreParsed() { + val text = renderer.toMarkdown("[Docs][guide] and [details](https://example.org/a\\(b\\)).\n\n[guide]: https://example.org/docs") + assertEquals("Docs and details.", text.toString().trimEnd()) + assertEquals(2, text.links().size) + } + + @Test fun codeStaysLiteralAndDoesNotBecomeClickable() { + val text = renderer.toMarkdown("`[PR](https://example.org)`\n\n~~~kotlin\nval url = \"https://example.org\"\n~~~") + assertTrue(text.toString().contains("[PR](https://example.org)")) + assertTrue(text.toString().contains("val url = \"https://example.org\"")) + assertTrue(text.links().isEmpty()) + } + + @Test fun commonMarkdownBlocksAndNestedFormattingRenderWithoutMarkers() { + val text = renderer.toMarkdown("# Heading\n\n> A **bold and *italic*** quote\n\n1. First\n - Nested\n2. Second\n\n~~Removed~~\n\n- [x] Done\n- [ ] Pending") + val result = text.toString() + for (word in listOf("Heading", "A bold and italic quote", "First", "Nested", "Second", "Removed", "Done", "Pending")) { + assertTrue(result, result.contains(word)) + } + for (marker in listOf("# Heading", "**", "~~", "[x]", "[ ]")) assertFalse(result, result.contains(marker)) + } + + @Test fun tablesAreParsedWithLinksInsideCells() { + val root = renderer.parse("| Result | Link |\n| --- | --- |\n| Ready | [PR](https://github.com/owner/repo/pull/1) |") + assertEquals("TableBlock", root.firstChild.javaClass.simpleName) + var links = 0 + root.accept(object : org.commonmark.node.AbstractVisitor() { + override fun visit(link: org.commonmark.node.Link) { + links++ + assertEquals("https://github.com/owner/repo/pull/1", link.destination) + } + }) + assertEquals(1, links) + renderer.render(root) + } + + @Test fun colorChangesPreserveSelectionAndRefreshLinkSpans() { + val source = "Read [the PR](https://github.com/owner/repo/pull/1)" + val view = TextView(context).apply { setTextIsSelectable(true) } + val original = renderer + setAgentMarkdown(view, original, original.toMarkdown(source)) + Selection.setSelection(view.text as Spannable, 5, 11) + val updated = agentMarkdownRenderer(context, Color.RED, Color.LTGRAY) + val rendered = updated.toMarkdown(source) + setAgentMarkdown(view, updated, rendered) + assertEquals(5, view.selectionStart) + assertEquals(11, view.selectionEnd) + assertSame(rendered, view.tag) + val paint = android.text.TextPaint() + (view.text as Spanned).links().single().updateDrawState(paint) + assertEquals(Color.RED, paint.color) + } + + @Test fun reversedSelectionsAndCursorsSurviveColorChangesButNotContentChanges() { + val view = TextView(context).apply { setTextIsSelectable(true) } + val original = renderer + val updated = agentMarkdownRenderer(context, Color.RED, Color.LTGRAY) + setAgentMarkdown(view, original, original.toMarkdown("A long reply")) + for ((start, end) in listOf(8 to 2, 4 to 4)) { + Selection.setSelection(view.text as Spannable, start, end) + setAgentMarkdown(view, updated, updated.toMarkdown("A long reply")) + assertEquals(start, view.selectionStart) + assertEquals(end, view.selectionEnd) + } + setAgentMarkdown(view, updated, updated.toMarkdown("New")) + assertFalse(view.selectionStart == 4 && view.selectionEnd == 4) + } + + @Test fun tableCellsRemainInNativeCopyAndAccessibilityTextOnAndroid28() { + val source = "Before\n\n| Result | Link |\n| --- | --- |\n| **Ready** | [PR](https://github.com/owner/repo/pull/1) |\n| Pending | `code` |\n\nAfter" + val markwon = renderer + val rendered = markwon.toMarkdown(source) + val view = TextView(context).apply { setTextIsSelectable(true) } + setAgentMarkdown(view, markwon, rendered) + val expected = "Result | Link\nReady | PR\nPending | code" + assertTrue(rendered.toString(), rendered.toString().contains(expected)) + assertTrue(view.createAccessibilityNodeInfo().text.toString().contains(expected)) + Selection.setSelection(view.text as Spannable, 0, view.text.length) + assertTrue(view.onTextContextMenuItem(android.R.id.copy)) + val copied = context.getSystemService(ClipboardManager::class.java).primaryClip!!.getItemAt(0).text.toString() + assertEquals(rendered.toString(), copied) + val rows = rendered.getSpans(0, rendered.length, TableRowSpan::class.java) + assertEquals(3, rows.size) + assertTrue(rows.all { rendered.getSpanEnd(it) > rendered.getSpanStart(it) }) + } + + @Test fun tableLinksStillOpenTheBrowserAfterExposingCellText() { + val markwon = renderer + val rendered = markwon.toMarkdown("| Result | Link |\n| --- | --- |\n| Ready | [PR](https://github.com/owner/repo/pull/1) |") + val view = TextView(context).apply { setTextIsSelectable(true) } + setAgentMarkdown(view, markwon, rendered) + view.measure(android.view.View.MeasureSpec.makeMeasureSpec(900, android.view.View.MeasureSpec.EXACTLY), + android.view.View.MeasureSpec.makeMeasureSpec(2000, android.view.View.MeasureSpec.AT_MOST)) + view.layout(0, 0, 900, view.measuredHeight) + val canvas = android.graphics.Canvas(android.graphics.Bitmap.createBitmap(900, 2000, android.graphics.Bitmap.Config.ARGB_8888)) + view.draw(canvas) + val row = rendered.getSpans(0, rendered.length, TableRowSpan::class.java).maxBy { rendered.getSpanStart(it) } + val cell = requireNotNull(row.findLayoutForHorizontalOffset(row.cellWidth() + 1)) + (cell.text as Spanned).links().single().onClick(view) + assertEquals("https://github.com/owner/repo/pull/1", shadowOf(context).nextStartedActivity.dataString) + } + + @Test fun multipleTablesAndEmptyCellsKeepTheirOwnTextAndRowSpans() { + val rendered = renderer.toMarkdown("| One | Two |\n| --- | --- |\n| | X |\n\nBetween\n\n| Three | Four |\n| --- | --- |\n| Y | |") + val text = rendered.toString() + assertTrue(text, text.contains("One | Two\n | X")) + assertTrue(text, text.contains("Three | Four\nY | ")) + assertTrue(text, text.contains("Between")) + assertEquals(4, rendered.getSpans(0, rendered.length, TableRowSpan::class.java).size) + } + + @Test fun unfinishedStreamingMarkdownDoesNotLoseTextOrCrash() { + val source = "Read [the PR](https://github.com/owner/repo/pull/1)\n\n```kotlin\nval x = 1" + for (end in 1..source.length) renderer.toMarkdown(source.take(end)) + assertTrue(renderer.toMarkdown(source).toString().contains("val x = 1")) + } + + @Test fun browserIntentsOnlyAcceptAbsoluteWebLinks() { + for (link in listOf("javascript:alert(1)", "file:///etc/passwd", "intent://open", "content://private", "/local/file", "https:")) { + assertNull(link, agentBrowserIntent(link)) + } + assertNotNull(agentBrowserIntent("http://example.org")) + assertNotNull(agentBrowserIntent("https://github.com/owner/repo/pull/1?diff=split#discussion")) } } diff --git a/app/src/test/java/com/droiddeck/launcher/ui/AppScaleTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/AppScaleTest.kt index 56a6db50b5..e3e741b65a 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/AppScaleTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/AppScaleTest.kt @@ -87,4 +87,12 @@ class AppScaleTest { assertEquals(540, base.screenHeightDp) assertEquals(320, base.densityDpi) } + + @Test fun homePageDefaultsToSteamAndIgnoresAnUnknownStoredPage() { + assertEquals(AppUiPrefs.HOME_PAGE_STEAM, AppUiPrefs.homePage(context)) + AppUiPrefs.setHomePage(context, AppUiPrefs.HOME_PAGE_APPS) + assertEquals(AppUiPrefs.HOME_PAGE_APPS, AppUiPrefs.homePage(context)) + context.getSharedPreferences("app-ui", Context.MODE_PRIVATE).edit().putString("home-page", "gone").commit() + assertEquals(AppUiPrefs.HOME_PAGE_STEAM, AppUiPrefs.homePage(context)) + } } diff --git a/app/src/test/java/com/droiddeck/launcher/ui/AppsGridTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/AppsGridTest.kt new file mode 100644 index 0000000000..6f09411ac1 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/ui/AppsGridTest.kt @@ -0,0 +1,21 @@ +package com.droiddeck.launcher.ui + +import android.content.Context +import androidx.test.core.app.ApplicationProvider +import org.junit.Assert.assertEquals +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [33]) +class AppsGridTest { + @Test fun anUnknownStoredGridValueFallsBackToTheDefault() { + val context: Context = ApplicationProvider.getApplicationContext() + context.getSharedPreferences("home_launcher", Context.MODE_PRIVATE).edit().putInt("grid_icon", 999).putInt("grid_spacing", 7).commit() + AppsGrid.load(context) + assertEquals(AppsGrid.MEDIUM, AppsGrid.iconDp) + assertEquals(AppsGrid.NORMAL, AppsGrid.spacing) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/ui/DragTargetTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/DragTargetTest.kt new file mode 100644 index 0000000000..3a35e77f23 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/ui/DragTargetTest.kt @@ -0,0 +1,20 @@ +package com.droiddeck.launcher.ui + +import org.junit.Assert.assertEquals +import org.junit.Test + +class DragTargetTest { + @Test fun smallMovesStayInPlace() = assertEquals(5, dragTarget(20f, 100f, 5, 0, 9)) + + @Test fun halfRowMovesToNextSlot() { + assertEquals(6, dragTarget(60f, 100f, 5, 0, 9)) + assertEquals(4, dragTarget(-60f, 100f, 5, 0, 9)) + } + + @Test fun longMovesSkipSeveralRows() = assertEquals(8, dragTarget(310f, 100f, 5, 0, 9)) + + @Test fun staysInsideTheDisc() { + assertEquals(9, dragTarget(900f, 100f, 5, 0, 9)) + assertEquals(2, dragTarget(-900f, 100f, 5, 2, 9)) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/ui/EdgeFlingTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/EdgeFlingTest.kt new file mode 100644 index 0000000000..5a0e298541 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/ui/EdgeFlingTest.kt @@ -0,0 +1,27 @@ +package com.droiddeck.launcher.ui + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class EdgeFlingTest { + private val density = 2f + + @Test fun aQuickFlickGoesTheWayItWasThrownFromAnywhere() { + assertFalse(EdgeFling.toRight(centerX = 1800f, span = 1920f, vx = -1500f, density = density)) + assertTrue(EdgeFling.toRight(centerX = 100f, span = 1920f, vx = 1500f, density = density)) + } + + @Test fun aSlowReleaseGoesWhereItWouldCoast() { + assertTrue(EdgeFling.toRight(centerX = 1000f, span = 1920f, vx = 0f, density = density)) + assertFalse(EdgeFling.toRight(centerX = 900f, span = 1920f, vx = 0f, density = density)) + assertFalse(EdgeFling.toRight(centerX = 1100f, span = 1920f, vx = -1100f, density = density)) + } + + @Test fun theHeightCarriesOnWithTheThrowAndStaysOnScreen() { + assertEquals(436f, EdgeFling.restY(400f, 200f, 0f, 1000f), 0.01f) + assertEquals(1000f, EdgeFling.restY(900f, 5000f, 0f, 1000f), 0.01f) + assertEquals(24f, EdgeFling.restY(100f, -5000f, 24f, 1000f), 0.01f) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/ui/NavTabsTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/NavTabsTest.kt new file mode 100644 index 0000000000..41f8333147 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/ui/NavTabsTest.kt @@ -0,0 +1,178 @@ +package com.droiddeck.launcher.ui + +import android.content.Context +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.height +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.ui.Modifier +import androidx.compose.ui.test.assertIsDisplayed +import androidx.compose.ui.test.hasTestTag +import androidx.compose.ui.test.hasText +import androidx.compose.ui.test.onNodeWithTag +import androidx.compose.ui.test.performClick +import androidx.compose.ui.unit.dp +import androidx.test.core.app.ApplicationProvider +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [34], qualifiers = "w1200dp-h752dp-land", application = android.app.Application::class) +class NavTabsTest { + @get:Rule val compose = createRobolectricComposeRule() + private val ctx: Context = ApplicationProvider.getApplicationContext() + + @Before @After fun reset() { + ctx.getSharedPreferences("session", Context.MODE_PRIVATE).edit().clear().commit() + NavTabs.load(ctx) + com.droiddeck.launcher.agent.AgentTab.load(ctx) + } + + @Test fun musicStartsInMore() { + assertEquals(listOf("steam", "games", "stores", "desktop", "components", "setup", "updates", NavTabs.MORE), navigationKeys(state())) + assertEquals(listOf("soundtracks"), NavTabs.more(state())) + assertEquals(setOf("soundtracks", "agent"), NavTabs.shelved) + assertTrue(com.droiddeck.launcher.agent.AgentTab.shown) + } + + @Test fun showingMusicOnceKeepsItShownAfterReload() { + NavTabs.setPlace(ctx, "soundtracks", TabPlace.BAR) + NavTabs.load(ctx) + assertEquals(listOf("steam", "games", "soundtracks", "stores", "desktop", "components", "setup", "updates"), navigationKeys(state())) + } + + @Test fun shelvedTabsLeaveTheBarAndAddMoreAtTheEnd() { + NavTabs.setPlace(ctx, "stores", TabPlace.MORE) + NavTabs.setPlace(ctx, "components", TabPlace.MORE) + val s = state() + assertEquals(listOf("soundtracks", "stores", "components"), NavTabs.more(s)) + assertEquals(NavTabs.MORE, navigationKeys(s).last()) + assertFalse("stores" in navigationKeys(s)) + } + + @Test fun hiddenTabsAreNowhereAndSetupCannotBeHidden() { + NavTabs.setPlace(ctx, "updates", TabPlace.HIDDEN) + NavTabs.setPlace(ctx, "setup", TabPlace.HIDDEN) + val s = state() + assertFalse("updates" in navigationKeys(s)) + assertFalse("updates" in NavTabs.more(s)) + assertTrue("setup" in navigationKeys(s)) + } + + @Test fun disabledStoresFeatureReadsAsHidden() { + assertEquals(TabPlace.HIDDEN, NavTabs.place(state(storesOn = false), "stores")) + } + + @Test fun movingSwapsWithTheNextVisibleTabAndPersists() { + NavTabs.setPlace(ctx, "soundtracks", TabPlace.BAR) + NavTabs.move(ctx, state(), "stores", -1) + assertEquals(listOf("steam", "games", "stores", "soundtracks"), navigationKeys(state()).take(4)) + NavTabs.load(ctx) + assertEquals(listOf("steam", "games", "stores", "soundtracks"), navigationKeys(state()).take(4)) + } + + @Test fun tabsMissingFromASavedOrderSlotInAfterTheirDefaultNeighbour() { + assertEquals(listOf("updates", "steam", "games", "soundtracks", "stores", "desktop", "agent", "components", "android-apps", "setup"), + NavTabs.arrange(listOf("updates", "steam"))) + assertEquals(listOf("games", "soundtracks", "steam", "setup", "stores", "desktop", "agent", "components", "android-apps", "updates"), + NavTabs.arrange(listOf("games", "steam", "setup", "stores", "desktop", "components", "android-apps", "updates", "bogus"))) + } + + @Test fun moreCarriesTheDownloadCountAndBadgesOfShelvedTabs() { + NavTabs.setPlace(ctx, "stores", TabPlace.MORE) + NavTabs.setPlace(ctx, "setup", TabPlace.MORE) + val s = state(downloads = 3, setupReady = false) + assertEquals(3, railCount(s, NavTabs.MORE)) + assertTrue(railBadge(s, NavTabs.MORE)) + NavTabs.setPlace(ctx, "stores", TabPlace.BAR) + assertEquals(0, railCount(s, NavTabs.MORE)) + assertEquals(3, railCount(s, "stores")) + } + + @Test fun sideRailShowsTheDownloadCountOnMoreWhenStoresIsShelved() { + NavTabs.setPlace(ctx, "stores", TabPlace.MORE) + val s = state(downloads = 2) + compose.setContent { + DroidDeckTheme { + CompositionLocalProvider(LocalFrontFocus provides FrontFocus()) { + Box(Modifier.height(752.dp)) { SideRail(s, "steam", {}, {}, actions(), Modifier) } + } + } + } + compose.onNodeWithTag("rail-stores").assertDoesNotExist() + compose.onNode(hasTestTag("rail-more")).assertIsDisplayed() + compose.onNode(hasText("2") and hasParentTag("rail-more"), useUnmergedTree = true).assertIsDisplayed() + } + + @Test fun morePageListsShelvedTabsWithTheirCount() { + NavTabs.setPlace(ctx, "stores", TabPlace.MORE) + NavTabs.setPlace(ctx, "components", TabPlace.MORE) + val s = state(downloads = 4) + compose.setContent { + DroidDeckTheme { + CompositionLocalProvider(LocalFrontFocus provides FrontFocus()) { + FocusGlideHost { Box(Modifier.fillMaxSize()) { MorePage(s, actions(), {}, Modifier.fillMaxSize()) } } + } + } + } + compose.onNodeWithTag("more-stores").assertIsDisplayed() + compose.onNodeWithTag("more-components").assertIsDisplayed() + compose.onNode(hasText("4") and hasParentTag("more-stores"), useUnmergedTree = true).assertIsDisplayed() + } + + @Test fun backFromAShelvedTabReturnsToMore() { + NavTabs.setPlace(ctx, "desktop", TabPlace.MORE) + var back: androidx.activity.OnBackPressedDispatcher? = null + compose.mainClock.autoAdvance = false + compose.setContent { + back = androidx.activity.compose.LocalOnBackPressedDispatcherOwner.current?.onBackPressedDispatcher + DroidDeckTheme { FrontEndScreen(state(), actions(), page = null) } + } + compose.mainClock.advanceTimeBy(2_000) + compose.onNodeWithTag("rail-more").performClick() + compose.mainClock.advanceTimeBy(2_000) + compose.onNodeWithTag("more-desktop").performClick() + compose.mainClock.advanceTimeBy(2_000) + compose.onNodeWithTag("more-desktop").assertDoesNotExist() + compose.runOnIdle { back!!.onBackPressed() } + compose.mainClock.advanceTimeBy(2_000) + compose.onNodeWithTag("more-desktop").assertIsDisplayed() + } + + @Test fun startupWithSteamHiddenNeverLandsOnABareComponentsSelection() { + NavTabs.setPlace(ctx, "steam", TabPlace.HIDDEN) + repeat(NavTabs.ALL.size) { NavTabs.move(ctx, state(), "components", -1) } + assertEquals("components", navigationKeys(state()).first()) + compose.mainClock.autoAdvance = false + compose.setContent { DroidDeckTheme { FrontEndScreen(state(), actions(), page = null) } } + compose.mainClock.advanceTimeBy(2_000) + compose.onNode(hasText(ctx.getString(com.droiddeck.launcher.R.string.content_page_gone))).assertDoesNotExist() + compose.onNode(hasTestTag("rail-games") and androidx.compose.ui.test.isSelected()).assertExists() + } + + private fun hasParentTag(tag: String) = androidx.compose.ui.test.hasAnyAncestor(hasTestTag(tag)) + + private fun state(storesOn: Boolean = true, downloads: Int = 0, setupReady: Boolean = true) = FrontEndState( + installed = "r9", ready = setupReady, available = null, busy = false, stage = "", percent = -1, + desktopInstalled = true, offlineAccount = null, offline = false, frameGenLabel = "", romsDir = null, logsEnabled = false, + steamGames = emptyList(), emulators = emptyList(), running = null, + gameStoresEnabled = storesOn, storeDownloadsActive = downloads, + ) + + private fun actions() = FrontEndActions( + onPlay = {}, onPlayDesktopUi = {}, onSteamGame = {}, onDesktop = {}, onEmulator = {}, onRom = {}, onResume = {}, + onSteamSettings = {}, onDesktopSettings = {}, onInstallPackage = {}, onRemovePackage = {}, + onRuntime = {}, onFrameGenPick = {}, onImportLossless = {}, onProtons = {}, onComponents = {}, + onPerformance = {}, onRoms = {}, onFiles = {}, onLogs = {}, onOffline = {}, + onWirelessAdbPair = { _, _, _, _ -> }, onWirelessAdbApply = { _, _, _, _ -> }, + onSetPhantomProcessLimit = { _, _ -> }, onRemoveDesktop = {}, + ) +} diff --git a/app/src/test/java/com/droiddeck/launcher/ui/PortraitLayoutTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/PortraitLayoutTest.kt index e1210893f0..25ba697759 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/PortraitLayoutTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/PortraitLayoutTest.kt @@ -93,6 +93,21 @@ class PortraitLayoutTest { compose.onNodeWithContentDescription("Resume Steam").assertIsDisplayed() } + @Test fun bottomBarFollowsSidebarLabelsSetting() { + val context = org.robolectric.RuntimeEnvironment.getApplication() + RailLabels.set(context, false) + compose.setContent { + DroidDeckTheme { BottomBar(state, "steam", {}, {}, actions, Modifier.size(480.dp, 64.dp)) } + } + compose.mainClock.advanceTimeBy(1_000) + compose.onNodeWithText("Library").assertDoesNotExist() + compose.onNodeWithContentDescription("Library").assertIsDisplayed() + compose.runOnIdle { RailLabels.set(context, true) } + androidx.compose.runtime.snapshots.Snapshot.sendApplyNotifications() + compose.mainClock.advanceTimeBy(1_000) + compose.onNodeWithText("Library").assertIsDisplayed() + } + @Test fun compactHeaderKeepsAllActionsReachable() { compose.setContent { DroidDeckTheme { diff --git a/docs/agent-control.md b/docs/agent-control.md index 7a1fed1d0e..4ac8706706 100644 --- a/docs/agent-control.md +++ b/docs/agent-control.md @@ -28,7 +28,7 @@ Player controls and observations work over authorized ADB on any build: `state`, `resume`, `wait`, `launch`, `quit`, `focus`, `input`, `ui`, `logs`, `screenshot`, `record`, `pacing`, `thermal`, `displays`, `wake`, `glasses` (except `glasses raw`), and `access`. -**Setup > Diagnostics > Debugging tools** is off by default in every build, including debug builds. +**Setup > Developer > Debugging tools** is off by default in every build, including debug builds. It enables `run`, `guest`, `cdp`, all `env` operations, `override`, `prefs`, and `glasses raw`. The toggle switches directly without a confirmation dialog. The bridge refuses to change it through `ui` or preference writes. The existing preference key, `setting-agent-commands` test tag, JSON command diff --git a/docs/development/game-environment.md b/docs/development/game-environment.md index 79206aa03a..766a565a55 100644 --- a/docs/development/game-environment.md +++ b/docs/development/game-environment.md @@ -104,7 +104,7 @@ Run the batch/reference and work-budget regressions with ## Game debug logs -Under **Setup > Diagnostics**, enable **Session logs** and **Game debug logs** +Under **Setup > Developer**, enable **Session logs** and **Game debug logs** before reproducing a Windows game problem. Game debug logs is off by default and is available when Session logs is enabled. It applies to the next game launch through DroidDeck's Valve or third-party Proton wrapper, including added games and store shortcuts. @@ -142,7 +142,7 @@ that diagnostics were skipped instead of writing uncollected files elsewhere. ## Enhanced diagnostics -Use **Setup > Diagnostics > Enhanced diagnostics for next session** when normal +Use **Setup > Developer > Enhanced diagnostics for next session** when normal session logs are not enough. The setting is one-shot: DroidDeck creates and retains the next session's log directory, records the diagnostic profile, then turns the setting off. It also enables the existing game diagnostic environment diff --git a/docs/development/low-memory.md b/docs/development/low-memory.md index 4b8e9b459e..81055ff0b1 100644 --- a/docs/development/low-memory.md +++ b/docs/development/low-memory.md @@ -9,8 +9,10 @@ Every five seconds the monitor reads `MemAvailable`, swap headroom and memory PS headroom means less than one fifth of total RAM (bounded to 512โ€“1536 MiB), or at least 1% `some avg10` memory stall with less than one third of RAM available. Pressure requests target only the launcher processes already recognized by the monitor, never the game. They require -at least 128 MiB launcher RSS and enough free swap to cover its entire RSS while leaving -one fifth of swap (at least 256 MiB) free. The regular automatic client request uses the +at least 128 MiB launcher RSS and enough free swap to cover its anonymous RSS while leaving +one fifth of swap (at least 256 MiB) free. File-backed resident pages do not consume this +budget: the page-out helper targets private anonymous mappings. If `RssAnon` is absent from a +process's status, its full RSS is used instead. The regular automatic client request uses the same swap guard. An explicit session RAM cap retains its existing behavior. Pressure requests are at least 30 seconds apart. Reclaiming less than 16 MiB doubles the @@ -41,27 +43,32 @@ reduced aggregate launcher RSS only from 263 to 255 MiB and backed off. Thus lau does not resolve this load failure, and this run did not exhaust swap. The unevictable/shmem growth needs allocation attribution before treating it as a driver or GPU-memory diagnosis. -## Low-RAM devices: compressing idle game memory +## Pressure reclaim: compressing idle game memory -On devices with at most 13 GiB `MemTotal` (every 12 GB phone and handheld and below), the -monitor also compresses the game session itself when memory runs out. The trigger is absolute -headroom, not a percentage: Android's `lmkd` killed a session on a 7.5 GiB device with +The monitor also compresses the game session itself when observed pressure approaches the +system kill boundary. There is no RAM-size gate. The trigger is absolute real headroom, not a +percentage: Android's `lmkd` killed a session on a 7.5 GiB device with 490 MiB still available, so a 95% used threshold (about 400 MiB left on 8 GB) is already past the kill. A world load added 1 GiB of GPU memory in about ten seconds, and compressing 1.4 GiB took 2.6 seconds, so the request has to leave room for both. -The session request runs when available memory falls below a quarter of RAM (bounded to -768โ€“2560 MiB, 1.85 GiB on an 8 GB device), or below one and a half times that with at least 1% -`some avg10` memory stall. One request pages out every session process that loaded -`libblsession.so`: the game, Wine and its services, plus the launcher processes unless their -compression is turned off, under a single wait. It runs before the launcher-only check, which -can wait up to 12 seconds for acknowledgements. While a game runs and available memory is under -twice that level, memory is read every second instead of every five. Requests are at least 30 seconds apart and need the same swap reserve as launcher -requests. When the session has read back more than half of what the previous request compressed, -that memory is in use: the request is skipped and the wait doubles, up to five minutes. A -request whose memory stayed compressed resets it to 30 seconds. Below half the headroom the -wait is ignored and only the 30-second spacing applies. The state resets when the game exits. Devices above 13 GiB keep the -launcher-only behaviour. +The session request runs when real headroom falls below a quarter of RAM (bounded to +768โ€“2560 MiB), or below one and a half times that with at least 1% `some` or `full avg10` +memory stall. Real headroom subtracts positive growth in KGSL allocation, `Unevictable`, and +`Shmem` from `MemAvailable`; a rapid fall also qualifies near twice the headroom. The monitor +may first request page-out of idle Steam and hidden launchers, subject to the Performance +setting and client reclaim limits. When both qualify, both requests are sent before waiting +for either to complete, so a slow launcher acknowledgement does not delay the game request. Until the client +request finishes, its anonymous RSS remains reserved from the session's swap budget. Completion +and backoff are measured against the processes that received each request, even if a later scan +finds different processes. The session request targets processes that loaded +`libblsession.so`: the game, Wine and its services, and excludes Steam and hidden launchers. +Requests are at least 30 seconds apart and need the same +swap reserve as launcher requests. When the session has read back more than half of what the +previous request compressed, that memory is in use: the request is skipped and the wait doubles, +up to five minutes. A request whose memory stayed compressed resets it to 30 seconds. Below half +the headroom the wait is ignored and only the 30-second spacing applies. The state resets when +the game exits. Measured on a Retroid Pocket Duo (7.5 GiB, kernel 6.6, 6 GiB lzo-rle zram plus a 4 GiB swap file) entering the world in World of Warcraft: Forever, one run each: @@ -91,7 +98,8 @@ A second run on that build showed the trigger arriving too late: character selec there. During the load, available memory crossed the headroom 9 seconds after Enter World, but the launcher check ran first and waited 12 seconds for acknowledgements; the game request started at 21 seconds, moved about 200 MiB, and `lmkd` ended the session at 30 seconds. The quarter-of-RAM -level and the game-first single request address both. +level starts reclaim earlier. Sending both requests before waiting removes the launcher +acknowledgement delay; it does not guarantee that reclaim can keep up with every loading peak. Without root an app cannot write its memory cgroup's `memory.reclaim` (owned by `system`), `process_madvise` on another process returns `EPERM`, `PAGEMAP_SCAN` is absent before Linux 6.7, diff --git a/docs/development/proot-performance.md b/docs/development/proot-performance.md index bcf3424c1e..634b7bc63a 100644 --- a/docs/development/proot-performance.md +++ b/docs/development/proot-performance.md @@ -204,7 +204,7 @@ call can be answered in-process with the 0014 design. | syscalls | why proot traps them | can it bypass proot? | |---|---|---| | `openat`/`open`/`creat`, `newfstatat`/`stat`/`lstat`, `statx`, `faccessat`/`access`, `readlinkat` (exit), `mkdirat`, `unlinkat`, `renameat(2)`, `symlinkat`, `linkat`, `fchmodat`, `fchownat`, `utimensat`, `truncate`, `*xattr`, `inotify_add_watch`, `name_to_handle_at` | path translation (guest โ†’ host), plus exit fixups for `readlink` and `rename` | **Yes, through libc wrappers.** The prototype covers open, stat, statx, access, readlink, opendir and fopen; the write family is next. Raw `svc` and glibc's internal callers (ld.so, fts, realpath, nss) still go to proot. | -| `chdir`/`fchdir`, `getcwd` (exit) | proot emulates the cwd; until 0014 the kernel's cwd never moved | With 0014 the kernel's cwd follows the guest's. `getcwd` stays in proot (cheap, rare). | +| `chdir`/`fchdir`, `getcwd` (exit) | proot emulates the cwd; until 0014 the kernel's cwd never moved | With 0014 the kernel's cwd follows the guest's. With 0028 `fchdir` takes the path of the open directory from `/proc//fd` instead of walking it again. `getcwd` stays in proot (cheap, rare). | | `execve`/`execveat` | runs the loader, maps `PT_INTERP` inside the rootfs, shebangs, tracks `/proc/self/exe` | **No.** This is the core of what proot is for. Costs 0.4โ€“0.8 ms per exec; the session scripts already avoid exec-heavy loops (`nap`). | | `brk` (entry and exit) | heap emulation: programs are mapped by proot's loader, so the kernel's brk area is the loader's | No (`PR_SET_MM` needs `CAP_SYS_RESOURCE`). **Fewer calls:** `GLIBC_TUNABLES=glibc.malloc.top_pad=โ€ฆ` grows the heap in larger steps. | | `bind`, `connect`, `accept(4)`, `getsockname`, `getpeername` | `sun_path` of Unix sockets | Same-path binds (runtime dir, files dir) need no translation, but the filter can't see the address. Possible fast-path candidate. | @@ -325,7 +325,7 @@ or repeatedly hit a path the wrappers cannot resolve. ### Opt-in tracer profiling -With **Setup > Diagnostics > Debugging tools** enabled, queue profiling for one session: +With **Setup > Developer > Debugging tools** enabled, queue profiling for one session: ```sh tools/droiddeckctl proot-profile enable --slow-us 1000 diff --git a/docs/development/soundtracks.md b/docs/development/soundtracks.md new file mode 100644 index 0000000000..a1b11a3997 --- /dev/null +++ b/docs/development/soundtracks.md @@ -0,0 +1,78 @@ +# Soundtracks + +Steam soundtracks get their own tab under Library, a built-in music player, and an Android media session. + +## Where soundtracks live + +Steam installs a soundtrack to `/steamapps/music/`, next to a normal `appmanifest_.acf`. This holds for the internal Steam library and for a second library folder. + +`Library.steamGames()` skips any manifest whose install directory exists only under `steamapps/music`. `Library.soundtracks()` returns exactly those entries, marked with `SteamGame.soundtrack`. While the Music tab is enabled, games and soundtracks therefore never mix in the Library tab, the launch drawer, game file sync or component preparation. + +Folders added by hand (Soundtracks tab, plus button) are stored in `added-soundtracks.json` and carry a negative app id, so they cannot collide with a Steam app id. + +## Turning it off + +Setup > Launcher > Soundtracks. When off, the tab disappears and installed Steam soundtracks show in Library again, as they did before. + +## Tracks, discs and duplicates + +`Soundtrack.load()` walks the folder (four levels deep) for mp3, flac, ogg, opus, wav, m4a and aac. Tags come from `MediaMetadataRetriever` and are cached per folder in `files/soundtrack-index`, keyed by path, size and modification time. + +`Soundtrack.group()` is pure and unit tested: + +1. The same track in several formats collapses to one. Identity is disc and track number when both tags exist, otherwise the cleaned title. Lossless wins over lossy. +2. Disc comes from the disc tag, otherwise from the subfolder (natural order), labelled with the folder name when it is numeric (for example `3+4`). A folder with no subfolders is one disc and shows no disc headers. Tags missing on the kept copy are filled from its duplicates, since FLAC files often use tag names Android does not read. +3. Tracks sort by the number at the start of the file name, then by track tag, then by name. This matches Valve's soundtrack documentation, which says the Steam music player takes play order from file names and not from metadata. Numbers shown on screen are positions inside the disc. +4. Titles come from the tag, otherwise from the file name with the artist, album and track number removed. + +## Cover art + +Steam's own library cache image first, then `AlbumArtwork`, `cover`, `folder` and similar files in the soundtrack folder. When none exists, the picture embedded in the first track that has one is used, so the grid shows it without opening the album. The player page shows the embedded picture of the track that is playing and falls back to the album cover for tracks without one. The media notification and the system media panel follow the same rule: while a track plays, its embedded picture replaces the item artwork in place, which does not restart playback, unless a cover was chosen in the art changer. The SteamGridDB artwork changer applies to Steam soundtracks like any other Steam entry. + +## Player page + +The layout follows Steam's soundtrack page and uses the DroidDeck theme colors and shapes, so every theme works. Cover, title, artist and total length sit on the left with seek, shuffle, previous, play or pause, next, repeat and volume. The track list with disc headers sits on the right. Portrait stacks the two. The action buttons (game files, shortcut, edit art, uninstall) use the same wide pill style as Steam's See More button. + +Controller: d-pad moves between buttons and rows, A confirms, B goes back, the sliders respond to left and right. + +Shortcuts use `droiddeck://soundtrack/` and open the soundtrack page. + +## Playback and Android media controls + +`SoundtrackService` is a media3 `MediaSessionService` with an `ExoPlayer`. It runs as a foreground service of type `mediaPlayback`, so playback keeps going when DroidDeck is closed and the notification and lock screen controls show the cover, title and artist. `SoundtrackController` connects a `MediaController` to it and exposes Compose state. + +Launching a game pauses the music unless Enable ingame is on (see Playing during games). Audio focus and headphone unplug are handled by ExoPlayer. + +Added dependencies: `androidx.media3:media3-exoplayer` and `androidx.media3:media3-session` 1.3.1. + +## Playback options + +The player page has a Playback options button that opens a panel with: + +- Speed and pitch, from 0.5x to 2x in 0.05 steps, applied through ExoPlayer's playback parameters. +- Skip silence. +- A sleep timer for 15, 30 or 60 minutes or the end of the current track. The timer runs in `SoundtrackService`, so it still fires when DroidDeck is closed. +- An equalizer with the device presets, one slider per band, and bass boost where the device supports it. The effects are attached to the player's audio session in the service. + +Settings are saved in `soundtrack_settings` and sent to the service whenever the controller connects. The last album, track and position are saved too, so the play button on an album resumes where it stopped. The position is saved on track changes, pauses and seeks. + +## Playing during games + +Setup โ€บ Launcher has an Enable ingame toggle, shown while soundtracks are on. When it is off, launching a game pauses the soundtrack. When it is on, the soundtrack keeps playing and the service stops requesting audio focus, so the game's own audio mixes with it. The setting is sent to the service with the `INGAME` session command and is read again when the service starts. + +## Searching and sorting + +Inside a soundtrack, a search field above the track list filters by title, artist and album, and a sort button orders the list by album order, title or length. Track numbers always count from 1 by position in the list shown. + +Custom (added) soundtracks, collections and Favorites can be reordered: select tracks first (long-press one, or use the select button), then with Album order selected and no search text, long-press a selected track and drag it. The order of an added soundtrack is stored in `soundtrack-order.json` and applied by `Soundtrack.load` within each disc; a collection stores its order in `soundtrack-collections.json`. Steam soundtracks cannot be reordered. The Music tab search also looks up tracks: soundtracks and collections whose names match come first, followed by a Tracks section. + +## Favorites and collections + +- The heart under the transport controls adds or removes the current track from Favorites. The bookmark button next to it opens the Saved panel to add the track to a collection or create one. +- The Music tab has a Collections chip. Favorites is the first entry under it. The bookmark in the Music header opens the same Saved panel to open or create a collection. +- Long-press a track to select. The selection bar has Select all, Deselect all, Add to collection, Add to favorites and, on a collection page, Remove from collection. +- A collection page has a Manage button to rename, add tracks, remove tracks or delete. Favorites cannot be renamed or deleted. +- Collection pages have Manage, Playback options, Shortcut and Edit art. Edit art changes the cover only, from a track cover or an image of your own, and is stored in `soundtrack-art/`. Added soundtracks have the same Edit art, with the images in their folder and the first track cover as the choices; Steam soundtracks keep the Steam art editor. +- Collections are stored in `soundtrack-collections.json` in the app files directory as snapshots of path, title, artist, album, length and cover. Tracks whose files are gone are skipped when a collection is played. +- Collection and Favorites playback does not overwrite the saved resume position of an album. + diff --git a/docs/development/steam-game-imports.md b/docs/development/steam-game-imports.md index 04065e3a55..2e4a0cc3e7 100644 --- a/docs/development/steam-game-imports.md +++ b/docs/development/steam-game-imports.md @@ -52,6 +52,12 @@ again. A failed title lookup undoes nothing. The launcher likewise drops artwork fetched for the app the files named before and fetches it again; pictures the user chose are kept. +A game that stays a shortcut but sits in a Steam install directory with a single matching +manifest links its shortcut prefix to that app's existing `compatdata/`, so cloud +saves the client downloaded are the ones the shortcut sees. A Steam library install only +uses its own library's prefix. An existing shortcut prefix is never replaced, a link to a +missing prefix is removed first, and nothing is copied. + The account's `.droiddeck-routes.json` maps shortcut IDs to real Steam app IDs so the Android launcher uses the same title and Proton prefix as Steam. Other accounts do not inherit those routes. Managed shortcuts are replaced; user-created shortcuts and diff --git a/docs/development/vram-budget.md b/docs/development/vram-budget.md index c9e6820efe..50e3becf70 100644 --- a/docs/development/vram-budget.md +++ b/docs/development/vram-budget.md @@ -1,6 +1,6 @@ # Reported video memory budget -The Performance VRAM setting enables `VK_LAYER_DROIDDECK_vram_cap` for games and reports smaller device-local `VK_EXT_memory_budget` budgets. DXVK exposes these through DXGI's `QueryVideoMemoryInfo`, including to D3D12 games using DXVK's DXGI alongside vkd3d-proton. Games that consult this budget can choose smaller working sets. The driver still supplies real heap sizes, usage figures, memory types, and actual allocation results. DXVK also receives its existing `dxgi.maxDeviceMemory` setting, which separately reduces the adapter's advertised dedicated video memory. A lower driver budget remains lower; the layer never increases it. +The Performance VRAM setting enables `VK_LAYER_DROIDDECK_vram_cap` for games and reports smaller device-local `VK_EXT_memory_budget` budgets. DXVK exposes these through DXGI's `QueryVideoMemoryInfo`, including to D3D12 games using DXVK's DXGI alongside vkd3d-proton. Games that consult this budget can choose smaller working sets. The driver still supplies real heap sizes, usage figures, memory types, and actual allocation results. DXVK also receives its existing `dxgi.maxDeviceMemory` setting, which separately reduces the adapter's advertised dedicated video memory, and, for caps below DXVK's 4096 MiB D3D9 default, `d3d9.maxAvailableMemory`, which caps the texture memory DXVK's D3D9 frontend reports, since D3D9 games do not read the DXGI setting. Higher caps leave the D3D9 setting alone so DXVK's lower per-game limits still apply. OpenGL games are not covered. A lower driver budget remains lower; the layer never increases it. This does not make vkd3d-proton automatically enforce the selected budget. In the [upstream allocator inspected during this investigation](https://github.com/HansKristian-Work/vkd3d-proton/blob/865b12ba0cc20796b3709397ce5d6d3b8a205b04/libs/vkd3d/memory.c), `heapBudget` is used for diagnostic reporting, while the [DXVK adapter](https://github.com/doitsujin/dxvk/blob/cf0a0d90f8965147741ad17dcd0b263817572ab3/src/dxgi/dxgi_adapter.cpp) returns the Vulkan budget to applications. Seeing a smaller budget in a VKD3D log verifies reporting, not reduced allocation or eviction. diff --git a/docs/lab-builds.md b/docs/lab-builds.md index 4f2ddfb5f0..2e01e3b9d8 100644 --- a/docs/lab-builds.md +++ b/docs/lab-builds.md @@ -5,6 +5,10 @@ or by hand, and loaded over the installed APK at the next start. Nothing is rein re-signed, so a tester on a release build keeps their games, sign-ins and settings while trying a change. +While a Lab build is active, add-on packs reuse the newest complete copy already installed on the +device, even when the checkout pins another version. This keeps helpers such as proot available +after restarting. If no complete copy exists, the pack uses the checkout's pin. + ## How it works - `tools/agent/dd-lab-build` builds the checkout with Gradle on the device (`processReleaseResources` @@ -25,6 +29,11 @@ change. Updates lists them under Lab builds: the one in use can be turned off, one built for this install can be used again, and any can be deleted. +The build targets the package owning `DD_AGENT_INBOX` when run from the Agent tab. +For a manual build of another package, set `DROIDDECK_PACKAGE`, for example +`DROIDDECK_PACKAGE=com.tencent.ig dd-lab-build`. This also selects the control provider, +Lab storage, and package to restart. + ## What a Lab build cannot change The manifest, native code (`cpp`, `jniLibs`, Rust), Gradle files, `App`, `AppLanguage`, and `LabOverlay` itself: diff --git a/tools/agent/dd-gh-login b/tools/agent/dd-gh-login index adf816a247..d3c7517e55 100755 --- a/tools/agent/dd-gh-login +++ b/tools/agent/dd-gh-login @@ -1,24 +1,17 @@ #!/bin/bash -# GitHub sign-in through Android's browser on the bottom screen, with the one-time code typed in. -serial=${ADB_SERIAL:-127.0.0.1:5555} -adb connect "$serial" >/dev/null 2>&1 +# Starts GitHub's device login and opens its approval page in Android. coproc GH { BROWSER=true gh auth login --hostname github.com --git-protocol https --web 2>&1; } gh_pid=$GH_PID -typed= -while IFS= read -r line <&"${GH[0]}"; do +exec {ghout}<&"${GH[0]}" {ghin}>&"${GH[1]}" +shown= +while IFS= read -r line <&"$ghout"; do printf '%s\n' "$line" code=$(grep -oE '[A-Z0-9]{4}-[A-Z0-9]{4}' <<<"$line" | head -1) - if [ -n "$code" ] && [ -z "$typed" ]; then - typed=1 - echo >&"${GH[1]}" - adb -s "$serial" shell "am start --display 2 -a android.intent.action.VIEW -d https://github.com/login/device" >/dev/null 2>&1 - # Chrome drops characters from `input text` and from fast key events on this page. - keys= - for ((i = 0; i < ${#code}; i++)); do - c=${code:i:1} - [ "$c" = - ] || keys+="input -d 2 keyevent KEYCODE_$c; sleep 0.4; " - done - (sleep 7; adb -s "$serial" shell "$keys" >/dev/null 2>&1) & + if [ -n "$code" ] && [ -z "$shown" ]; then + shown=1 + echo >&"$ghin" + printf 'GitHub device code: %s ยท github.com/login/device\n' "$code" + android-open https://github.com/login/device fi done wait "$gh_pid" diff --git a/tools/agent/dd-lab-build b/tools/agent/dd-lab-build index 44b62bd6b8..b29c6bc5a6 100755 --- a/tools/agent/dd-lab-build +++ b/tools/agent/dd-lab-build @@ -5,12 +5,17 @@ # compile what changed. Setup runs it once; it takes the longest. # --explain logs why each task ran and Kotlin's build report, to find out what makes a build slow. set -euo pipefail -pkg=com.droiddeck.launcher +pkg=${DROIDDECK_PACKAGE:-} +if [ -z "$pkg" ] && [[ ${DD_AGENT_INBOX:-} =~ ^/data/(user/[0-9]+|data)/([^/]+)/files/agent$ ]]; then + pkg=${BASH_REMATCH[2]} +fi +pkg=${pkg:-com.droiddeck.launcher} serial=${ADB_SERIAL:-127.0.0.1:5555} mode=build explain=() for arg in "$@"; do case $arg in + --package=*) pkg=${arg#--package=} ;; --no-restart) mode=no-restart ;; --prepare) mode=prepare ;; --explain) explain=(--info -Pkotlin.build.report.output=file) ;; @@ -31,16 +36,18 @@ progress() { # stage [permille task done total eta] fail() { progress failed 0 "$*"; echo "dd-lab-build: $*" >&2; exit 1; } trap 'progress failed 0 stopped; exit 143' INT TERM trap 'progress failed 0 "a command failed on line $LINENO"' ERR +[[ $pkg =~ ^[A-Za-z][A-Za-z0-9_]*(\.[A-Za-z][A-Za-z0-9_]*)+$ ]] || fail "invalid Android package: $pkg" +export DROIDDECK_PACKAGE=$pkg device() { adb -s "$serial" shell "$@" | tr -d '\r'; } # The app's agent loses every process it started when its turn ends, a build included, so it asks # the app to run the build in a process of its own and follows that build here. -agent=/data/user/0/$pkg/files/agent +agent=${DD_AGENT_INBOX:-/data/user/0/$pkg/files/agent} if [ -n "${DD_AGENT:-}" ] && [ -z "${DD_LAB_DETACHED:-}" ] && [ -d "$agent" ]; then trap - ERR log=$cache/dd-lab-build.log rm -f "$progress_file" - python3 -c 'import json,os,sys; print(json.dumps({"cwd": os.getcwd(), "args": sys.argv[1:]}))' "$@" > "$agent/lab-request.part" + python3 -c 'import json,os,sys; print(json.dumps({"cwd": os.getcwd(), "args": [*sys.argv[1:], "--package=" + os.environ["DROIDDECK_PACKAGE"]]}))' "$@" > "$agent/lab-request.part" mv "$agent/lab-request.part" "$agent/lab-request" echo "DroidDeck runs this build itself, so it keeps going if this turn ends. Its log follows." for _ in $(seq 1 30); do [ -f "$progress_file" ] && break; sleep 1; done @@ -102,7 +109,7 @@ export DROIDDECK_SOURCE_COMMIT=$base DROIDDECK_BUILD_LABEL="lab on $installed_la printf 'sdk.dir=%s\n' "$ANDROID_HOME" > local.properties if [ ! -d "$ANDROID_HOME/platforms/android-34" ]; then progress sdk - yes | "$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager" --licenses >/dev/null + (set +o pipefail; yes | "$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager" --licenses >/dev/null) "$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager" "platforms;android-34" "build-tools;35.0.0" >/dev/null fi @@ -125,7 +132,19 @@ gradle=(./gradlew :app:processReleaseResources :app:mergeDexRelease --max-worker -Pandroid.aapt2FromMavenOverride=$HOME/aapt2/aapt2 -Pkotlin.compiler.execution.strategy=daemon -Pkotlin.daemon.jvmargs=-Xmx${kotlin_heap}m -Dorg.gradle.jvmargs=-Xmx${gradle_heap}m --console=plain) progress planning -mapfile -t plan < <("${gradle[@]}" --dry-run -q 2>/dev/null | awk '/^:/ {print $1}' || true) +plan_file=$cache/dd-lab-build-plan +plan_key=$( + { + printf '%s\n' "$repo" "${gradle[@]}" + git ls-files -z -- '*gradle*' | xargs -0 -r sha256sum + } | sha256sum | cut -d ' ' -f1 +) +if [ "$(head -n 1 "$plan_file" 2>/dev/null)" != "$plan_key" ]; then + plan_output=$("${gradle[@]}" --dry-run) || fail "Gradle planning failed: $plan_output" + { printf '%s\n' "$plan_key"; awk '/^:/ {print $1}' <<<"$plan_output"; } > "$plan_file.part" + mv "$plan_file.part" "$plan_file" +fi +mapfile -t plan < <(tail -n +2 "$plan_file") total=${#plan[@]} # Each task's estimate is how long it took last time; a full compile of the app takes about 15 minutes. @@ -221,6 +240,6 @@ device cmd package compile -m verify -f $pkg >/dev/null progress restarting 1000 "$name" echo "Restarting DroidDeck on the Lab build; it shows a notification when it is back" # The app's own agent ends with the app, so it is told to carry on once the app is back. -if [ -n "${DD_AGENT:-}" ]; then mkdir -p "/data/user/0/$pkg/files/agent" && : > "/data/user/0/$pkg/files/agent/resume"; fi +if [ -n "${DD_AGENT:-}" ]; then mkdir -p "$agent" && : > "$agent/resume"; fi device "nohup sh -c 'sleep 3; monkey -p $pkg -c android.intent.category.LAUNCHER 1' >/dev/null 2>&1 &" for pid in $(device pidof $pkg); do kill "$pid" 2>/dev/null || true; done diff --git a/tools/agent/setup b/tools/agent/setup index 0b1f66f6a0..5c2405d8d6 100755 --- a/tools/agent/setup +++ b/tools/agent/setup @@ -61,7 +61,7 @@ if [ ! -x "$sdk/cmdline-tools/latest/bin/sdkmanager" ]; then mv "$sdk/cmdline-tools/cmdline-tools" "$sdk/cmdline-tools/latest" fi export JAVA_HOME=/usr/lib/jvm/java-17-openjdk-arm64 -yes | "$sdk/cmdline-tools/latest/bin/sdkmanager" --licenses >/dev/null +(set +o pipefail; yes | "$sdk/cmdline-tools/latest/bin/sdkmanager" --licenses >/dev/null) "$sdk/cmdline-tools/latest/bin/sdkmanager" "platforms;android-34" "build-tools;35.0.0" >/dev/null adb connect 127.0.0.1:5555 || true diff --git a/tools/build_local.sh b/tools/build_local.sh index d564f1e3c0..ee891aee97 100755 --- a/tools/build_local.sh +++ b/tools/build_local.sh @@ -433,6 +433,13 @@ if [[ "${DROIDDECK_SKIP_RUST:-0}" != 1 ]]; then CARGO_TARGET_DIR="${cache_dir}/ubisoft-target" bash tools/ubisoft-launcher/build.sh "${upc_out}" save_step ubisoft "${upc_key}" "${upc_out}" fi + rockstar_out="${repo_root}/app/src/main/resources/rockstar/helpers" + rockstar_key=$(inputs_hash "windows-gnu" tools/rockstar-launcher/src tools/rockstar-launcher/Cargo.toml tools/rockstar-launcher/Cargo.lock tools/rockstar-launcher/build.sh) + if ! restore_step rockstar "${rockstar_key}" "${rockstar_out}"; then + command -v i686-w64-mingw32-gcc >/dev/null 2>&1 || { echo "i686-w64-mingw32-gcc is required for the Rockstar launcher service." >&2; exit 1; } + CARGO_TARGET_DIR="${cache_dir}/rockstar-target" bash tools/rockstar-launcher/build.sh "${rockstar_out}" + save_step rockstar "${rockstar_key}" "${rockstar_out}" + fi fi python3 tools/powervr/fetch.py bash tools/packs/build.sh app/build/packs diff --git a/tools/droiddeckctl b/tools/droiddeckctl index 3e37811d28..ea82343888 100755 --- a/tools/droiddeckctl +++ b/tools/droiddeckctl @@ -571,7 +571,7 @@ def unpack_logs(archive: Path, destination: Path, session_id: str) -> None: def require_commands(adb: str, serial: str) -> dict: access = checked(provider_call(adb, serial, "access"), "ACCESS_FAILED") if access.get("commands") is not True: - raise ControlError("Debugging tools are off: turn on Setup > Diagnostics > Debugging tools on the device", + raise ControlError("Debugging tools are off: turn on Setup > Developer > Debugging tools on the device", "AGENT_COMMANDS_DISABLED") return access diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-battlenet b/tools/linuxfs/overlay/usr/local/bin/droiddeck-battlenet index 1ea487e873..3473e7dead 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-battlenet +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-battlenet @@ -41,6 +41,9 @@ FEX_WAIT = 120 START_GRACE = 90 POLL = 2 STOP_WAIT = 5 +DRIVES = "defghijklmnopqruvwxy" +PRODUCT_DB = ("ProgramData", "Battle.net", "Agent", "product.db") +INSTALL_FOLDER = (1, 3, 1) CLOSE_GRACE = 15 HANDOFF_WAIT = 120 GAME_SETTLE = 20 @@ -123,7 +126,7 @@ function install() { save(".form", form); if (form.indexOf('"' + lang + '"') < 0) lang = "enUS"; var locale = lang.toLowerCase(); - call("POST", "/install/" + uid, '{"account_country":"' + country + '","finalized":true,"game_dir":"' + dir + '","geo_ip_country":"' + + call("POST", "/install/" + uid, '{"account_country":"' + country + '","finalized":true,"game_dir":"' + dir.replace(/\\/g, "\\\\").replace(/"/g, '\\"') + '","geo_ip_country":"' + region + '","language":["' + locale + '"],"selected_asset_locale":"' + locale + '","selected_locale":"' + locale + '","shortcut":"none","tome_torrent":""}'); watch("/install/" + uid); @@ -226,8 +229,72 @@ def installed(root): return os.path.isfile(launcher(root)) -def install_path(library): - return "Z:" + library.rstrip("/") +def dosdevices(root): + return os.path.join(prefix(root), "pfx", "dosdevices") + + +def volume_root(path): + device = os.stat(path).st_dev + while path != "/": + parent = os.path.dirname(path) + if os.stat(parent).st_dev != device: + break + path = parent + return path + + +def inside(path, folder): + return path == folder or path.startswith(folder.rstrip("/") + "/") + + +def mapped_drive(root, path, volume): + folder = dosdevices(root) + try: + names = sorted(os.listdir(folder)) + except OSError: + return None + for name in names: + link = os.path.join(folder, name) + if len(name) == 2 and name[0].lower() in DRIVES and name[1] == ":" and os.path.islink(link): + target = os.path.realpath(link) + if inside(target, volume) and inside(path, target): + return name[0].lower(), target + return None + + +def map_drive(root, volume): + folder = dosdevices(root) + for letter in DRIVES: + link = os.path.join(folder, letter + ":") + if not os.path.lexists(link): + try: + os.makedirs(folder, exist_ok=True) + os.symlink(volume, link) + except OSError as error: + say("%s not mapped to a Wine drive: %s" % (volume, error)) + return None + say("Wine drive %s: is %s" % (letter.upper(), volume)) + return letter, volume + say("%s not mapped to a Wine drive: every letter is taken" % volume) + return None + + +def install_path(root, library): + library = library.rstrip("/") or "/" + try: + path = os.path.realpath(library) + volume = volume_root(path) + except OSError: + return "Z:" + library + if volume == "/": + return "Z:" + library + drive = mapped_drive(root, path, volume) + if drive is None and not wine_processes(os.path.join(prefix(root), "pfx")): + drive = map_drive(root, volume) + if drive is None: + return "Z:" + library + letter, target = drive + return letter.upper() + ":\\" + path[len(target):].strip("/").replace("/", "\\") def write_config(root, library=None): @@ -254,8 +321,8 @@ def write_config(root, library=None): client["HardwareAcceleration"] = "false" changes.append("acceleration") if library and isinstance(client.setdefault("Install", {}), dict) \ - and str(client["Install"].get("DefaultInstallPath", "")).rstrip("/\\") != install_path(library): - client["Install"]["DefaultInstallPath"] = install_path(library) + and str(client["Install"].get("DefaultInstallPath", "")).rstrip("/\\") != install_path(root, library).rstrip("\\"): + client["Install"]["DefaultInstallPath"] = install_path(root, library) changes.append("library") games = config.setdefault("Games", {}) for uid in CLIENT_32_BIT if isinstance(games, dict) else (): @@ -417,13 +484,106 @@ def wallpaper(root): def windows_path(root, path): - found = re.match(r"(?i)^([cz]):[\\/](.*)$", path.strip()) + found = re.match(r"(?i)^([a-z]):[\\/](.*)$", path.strip()) if not found: return None parts = [part for part in re.split(r"[\\/]+", found.group(2)) if part] - if not parts or ".." in parts: + if ".." in parts: return None - return os.path.join(drive_c(root) if found.group(1).lower() == "c" else "/", *parts) + letter = found.group(1).lower() + link = os.path.join(dosdevices(root), letter + ":") + if letter == "c": + target = drive_c(root) + elif os.path.islink(link): + target = os.path.realpath(link) + elif letter == "z": + target = "/" + else: + return None + return os.path.join(target, *parts) + + +def varint(data, at): + value = shift = 0 + while at < len(data) and shift < 64: + byte = data[at] + at += 1 + value |= (byte & 0x7F) << shift + if not byte & 0x80: + return value, at + shift += 7 + raise ValueError("varint") + + +def encode_varint(value): + out = bytearray() + while value > 0x7F: + out.append(value & 0x7F | 0x80) + value >>= 7 + out.append(value) + return bytes(out) + + +def rewrite_field(data, path, change): + out, at = bytearray(), 0 + while at < len(data): + start = at + tag, at = varint(data, at) + kind = tag & 7 + if kind == 0: + at = varint(data, at)[1] + elif kind == 1: + at += 8 + elif kind == 5: + at += 4 + elif kind == 2: + size, body = varint(data, at) + at = body + size + else: + raise ValueError("wire type") + if at > len(data): + raise ValueError("length") + if kind == 2 and tag >> 3 == path[0]: + value = data[body:at] + value = change(value) if len(path) == 1 else rewrite_field(value, path[1:], change) + out += encode_varint(tag) + encode_varint(len(value)) + value + else: + out += data[start:at] + return bytes(out) + + +def drive_folder(root, value): + try: + text = value.decode("utf-8") + except UnicodeDecodeError: + return value + if not re.match(r"(?i)^z:[\\/]", text): + return value + folder = windows_path(root, text) + if not folder or not os.path.isdir(folder): + return value + moved = install_path(root, folder) + return value if moved.startswith("Z:") else moved.replace("\\", "/").encode("utf-8") + + +def move_installs(root): + path = os.path.join(drive_c(root), *PRODUCT_DB) + try: + with open(path, "rb") as f: + data = f.read() + moved = rewrite_field(data, INSTALL_FOLDER, lambda value: drive_folder(root, value)) + if moved == data or wine_processes(os.path.join(prefix(root), "pfx")): + return False + with open(path, "rb") as f: + if f.read() != data: + return False + except (OSError, ValueError): + return False + with open(path + ".tmp", "wb") as f: + f.write(moved) + shutil.copymode(path, path + ".tmp") + os.replace(path + ".tmp", path) + return True def wow_folders(root): @@ -533,6 +693,11 @@ def configure(root, library=None): except OSError as error: say("Battle.net's config not written: %s" % error) return + try: + if move_installs(root): + say("Battle.net's installed games on a mapped volume now use its Wine drive") + except OSError as error: + say("Battle.net's installed games not moved to their Wine drive: %s" % error) try: wallpaper(root) except OSError as error: @@ -1227,7 +1392,6 @@ def agent_job(root, action, uid, product="", folder="", locale="enUS", country=" say("%s not made: %s" % (folder, error)) emit("ERROR", "folder") return 2 - windows = "Z:" + folder told = None while True: processes = wine_processes(pfx) @@ -1244,6 +1408,8 @@ def agent_job(root, action, uid, product="", folder="", locale="enUS", country=" time.sleep(POLL if poll is None else poll) with lock: stop_leftovers(pfx) + if action == "install": + windows = install_path(root, folder) emit("STATE", "starting") base = os.path.join(CACHE, "agent-%s" % uid) for suffix in (".json", ".game", ".form", ".error"): diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-game-env b/tools/linuxfs/overlay/usr/local/bin/droiddeck-game-env index 175b8d8d1c..459e8a6fac 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-game-env +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-game-env @@ -12,6 +12,7 @@ from pathlib import Path GAME_TU_DEBUG = "DROIDDECK_GAME_TU_DEBUG" CHROMIUM_FILES = {"chrome-sandbox", "chrome_100_percent.pak", "v8_context_snapshot.bin"} +D3D9_DEFAULT_MEMORY_MB = 4096 SYNC_KEYS = ("BL_SYNC", "BL_SYNC_FALLBACK", "BL_FSYNC_FIRST", "BL_SYNC_MIN_NOFILE", "PROTON_NO_ESYNC", "PROTON_NO_FSYNC", "PROTON_NO_NTSYNC", "WINEESYNC") SEED_REDISTS = "/usr/local/bin/droiddeck-seed-redists" PACK_KEYS = ("WINESERVER", "BL_SYNC_PACK", "WINEESYNC", "PROTON_NO_ESYNC", "PROTON_NO_FSYNC") @@ -144,6 +145,12 @@ def deep_rock_gdk_raytracing(game): return {}, ["-noraytracing", "-ini:Engine:[/Script/Engine.RendererSettings]:r.RayTracing=False"], "Deep Rock Galactic GDK: ray tracing off (D3D12 pipeline creation fails on Thor)" +@fix +def ff7_rebirth_feature_level(game): + if game.stem in ("ff7rebirth", "ff7rebirth_"): + return {"VKD3D_FEATURE_LEVEL": "12_2"}, [], "Final Fantasy VII Rebirth: D3D12 feature level 12_2 (the device-reported level fails its DX12 check)" + + @fix def arkham_city_x87(game): if "batmanac.exe" in game.files: @@ -396,7 +403,9 @@ def vram_cap(env): if not re.fullmatch(r"[1-9][0-9]{0,6}", value): return env result = env.copy() - cap = "dxgi.maxDeviceMemory = %d" % int(value) + cap = "dxgi.maxDeviceMemory = {0}".format(int(value)) + if int(value) < D3D9_DEFAULT_MEMORY_MB: + cap += "; d3d9.maxAvailableMemory = {0}".format(int(value)) own = result.get("DXVK_CONFIG", "").strip().strip(";").strip() result["DXVK_CONFIG"] = cap + "; " + own if own else cap result["DROIDDECK_VRAM_CAP"] = "1" diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-open b/tools/linuxfs/overlay/usr/local/bin/droiddeck-open index bf0aaff7c1..d39942a2cc 100644 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-open +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-open @@ -17,6 +17,7 @@ PROTON_RUN = os.path.join(BIN, "droiddeck-proton-run") APPIMAGE_RUN = os.path.join(BIN, "droiddeck-appimage-run") SCRIPT_RUN = os.path.join(BIN, "droiddeck-script-run") STEAM_LAUNCH = os.path.join(BIN, "droiddeck-steam-launch") +STORE_LAUNCH = os.path.join(BIN, "droiddeck-store-launch") PROGRAMS = os.path.join(BIN, "droiddeck-desktop-programs") CACHE = os.path.join(HOME, ".cache", "droiddeck") IMPORTS = {"appimage": ("/opt/appimages/user", "app"), "folder": ("/opt/droiddeck-apps", "entry")} @@ -272,12 +273,32 @@ def steam_title(path): return None +def exe_prefix(path): + try: + run = runpy.run_path(PROTON_RUN) + root = os.environ.get("STEAM_COMPAT_CLIENT_INSTALL_PATH") or run["STEAM_ROOT"] + target = run["locate"](path, root) + return ["--prefix", target.appid, "--compatdata", target.compatdata] + except (OSError, ValueError, KeyError, IndexError): + return None + + +def store_launcher(path): + try: + return runpy.run_path(STORE_LAUNCH)["store_launcher"](path) + except (OSError, ValueError, KeyError): + return None + + def command(path, args, what, window=False, appid=None): folder = os.path.dirname(path) if what == "steam": return [STEAM_LAUNCH, "desktop", appid], folder if what == "windows": - return [PROTON_RUN] + (["--window"] if window else []) + [path] + args, folder + launcher = None if args else store_launcher(path) + prefix = exe_prefix(path) if launcher else None + keep = prefix or [] + return [PROTON_RUN] + (["--window"] if window else []) + keep + [launcher or path] + args, folder if what == "x86 script": return [FEX, "run", "--mode", "on", "--for", folder, "--"] + interpreter(path) + [path] + args, folder if what == "script": diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-proton-run b/tools/linuxfs/overlay/usr/local/bin/droiddeck-proton-run index 164dbd0288..6dfcbadb25 100644 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-proton-run +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-proton-run @@ -315,8 +315,8 @@ def locate(program, root): os.path.dirname(program), root, "own") -def fixed(program, root, appid): - return Target(appid, os.path.join(root, "steamapps", "compatdata", str(appid)), +def fixed(program, root, appid, compatdata=None): + return Target(appid, compatdata or os.path.join(root, "steamapps", "compatdata", str(appid)), os.path.dirname(program), root, "fixed") @@ -451,6 +451,7 @@ def arguments(program, args, desktop=None, compatdata=None): def main(argv): window = False prefix = None + compatdata = None verb = VERB game_id = None desktop = None @@ -461,6 +462,8 @@ def main(argv): window = True elif option == "--prefix" and argv and prefix_id(argv[0]): prefix = argv.pop(0) + elif option == "--compatdata" and argv and os.path.isabs(argv[0]): + compatdata = argv.pop(0) elif option == "--verb" and argv and argv[0] in VERBS: verb = argv.pop(0) elif option == "--game-id" and argv and argv[0].isdigit() and argv[0] != "0": @@ -484,7 +487,7 @@ def main(argv): say("%s is not an app id" % app) return 2 if not argv and app is None: - say("usage: droiddeck-proton-run [--window] [--prefix ID] [--verb run] [--game-id ID] [--desktop WxH] PROGRAM [ARGS...]") + say("usage: droiddeck-proton-run [--window] [--prefix ID [--compatdata DIR]] [--verb run] [--game-id ID] [--desktop WxH] PROGRAM [ARGS...]") return 2 root = os.environ.get("STEAM_COMPAT_CLIENT_INSTALL_PATH") or STEAM_ROOT if options is None: @@ -509,7 +512,7 @@ def main(argv): if app is not None and int(app) >= STEAM_APP_LIMIT: target = shortcut_target(app, program, start, root) elif prefix: - target = fixed(program, root, prefix) + target = fixed(program, root, prefix, compatdata) else: target = locate(program, root) available = tools(root) diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-seed-redists b/tools/linuxfs/overlay/usr/local/bin/droiddeck-seed-redists index babcb86d3d..d2d2809bd3 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-seed-redists +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-seed-redists @@ -56,18 +56,75 @@ libraries="$steam_root" for library in $LIBRARIES; do libraries="$libraries $library"; done libraries=$(printf '%s\n%s\n' "$libraries" "$(sed -n 's/^[[:space:]]*"path"[[:space:]]*"\(.*\)"[[:space:]]*$/\1/p' "$steam_root/steamapps/libraryfolders.vdf" 2>/dev/null)" | awk 'NF && !seen[$0]++') -sig=$(while IFS= read -r library; do ls -l --time-style=+%s "$library"/steamapps/appmanifest_*.acf 2>/dev/null; done <<<"$libraries" | cksum) -if [ "$(head -n 1 "$cache" 2>/dev/null)" != "$sig" ]; then - { - printf '%s\n' "$sig" - while IFS= read -r library; do - [ -d "$library/steamapps/common" ] || continue - find "$library/steamapps/common" -mindepth 2 -maxdepth 5 -iname 'installscript*.vdf' \ - -not -path '*/Steamworks Shared/*' 2>/dev/null - done <<<"$libraries" | sort -u - } >"$cache.tmp" && mv -f "$cache.tmp" "$cache" +games=$(while IFS= read -r library; do + library="$library" awk ' + function flush() { if (dir != "") printf "%s|%s|%s|%s\t%s/steamapps/common/%s\n", file, build, updated, size, ENVIRON["library"], dir } + FNR == 1 { flush(); file = FILENAME; dir = build = updated = size = "" } + { + n = split($0, part, "\"") + for (i = 2; i + 2 <= n; i += 2) { + name = tolower(part[i]) + if (name == "installdir" && dir == "") dir = part[i + 2] + else if (name == "buildid" && build == "") build = part[i + 2] + else if (name == "lastupdated" && updated == "") updated = part[i + 2] + else if (name == "sizeondisk" && size == "") size = part[i + 2] + else continue + i += 2 + } + } + END { flush() } + ' "$library"/steamapps/appmanifest_*.acf 2>/dev/null +done <<<"$libraries") +legacy= +[ -s "$cache" ] && ! grep -q $'\t' "$cache" && legacy=$(tail -n +2 "$cache"; echo .) +declare -A scanned=() current=() +read_scanned() { + scanned=() + while IFS=$'\t' read -r key _; do + [ -n "$key" ] && scanned[$key]=1 + done < <(grep $'\t' "$cache" 2>/dev/null) +} +read_scanned +later= +fresh=() +while IFS=$'\t' read -r key dir; do + [ -n "$key" ] || continue + current[$key]=1 + [ -z "${scanned[$key]:-}" ] || continue + if [ -z "$legacy" ] && [ -n "${DROIDDECK_SEED_SCRIPTS:-}${DROIDDECK_SEED_LATER:-}" ]; then + [ -z "${DROIDDECK_SEED_LATER:-}" ] || later=1 + continue + fi + [ -d "$dir" ] || continue + scanned[$key]=1 + if [ -n "$legacy" ] && [ "$cache" -nt "${key%%|*}" ]; then + found=$(printf '%s\n' "${legacy%.}" | dir="$dir" awk 'index($0, ENVIRON["dir"] "/") == 1') + else + found=$(find "$dir" -mindepth 1 -maxdepth 4 -iname 'installscript*.vdf' \ + -not -path '*/Steamworks Shared/*' 2>/dev/null) || continue + found=$(printf '%s\n' "$found" | sort -u) + fi + fresh+=("$key" "$found") +done <<<"$games" +exec 9>"$cache.lock" && command -v flock >/dev/null 2>&1 && flock 9 +if [ ${#fresh[@]} -gt 0 ]; then + read_scanned + for ((i = 0; i < ${#fresh[@]}; i += 2)); do + [ -z "${scanned[${fresh[i]}]:-}" ] || continue + printf '%s\n' "${fresh[i + 1]}" | key="${fresh[i]}" awk '{ print ENVIRON["key"] "\t" $0 }' >>"$cache" + done fi -game_scripts() { { tail -n +2 "$cache" 2>/dev/null; printf '%s\n' "${DROIDDECK_SEED_SCRIPTS:-}"; } | sed '/^$/d' | tr '\n' '\0'; } +if [ -n "$later" ]; then + (DROIDDECK_SEED_LATER= DROIDDECK_SEED_SCRIPTS= DROIDDECK_SEED_DEFERRED=1 setsid "$0" "$steam_root" >/dev/null 2>&1 9>&- &) +fi +if [ -e "$cache" ]; then + keys=$(printf '%s\n' "${!current[@]}") awk -F'\t' ' + BEGIN { n = split(ENVIRON["keys"], key, "\n"); for (i = 1; i <= n; i++) want[key[i]] = 1 } + NF > 1 && ($1 in want) + ' "$cache" >"$cache.tmp" && { cmp -s "$cache.tmp" "$cache" && rm -f "$cache.tmp" || mv -f "$cache.tmp" "$cache"; } +fi +[ -z "${DROIDDECK_SEED_DEFERRED:-}" ] || ! pgrep -x wineserver >/dev/null 2>&1 || exit 0 +game_scripts() { { cut -s -f2- "$cache" 2>/dev/null; printf '%s\n' "${DROIDDECK_SEED_SCRIPTS:-}"; } | sed '/^$/d' | tr '\n' '\0'; } game_pairs=$(game_scripts | read_scripts) [ -n "$(printf '%s' "$game_pairs" | tr -d '[:space:]')" ] && pairs=$(printf '%s\n%s\n' "$pairs" "$game_pairs" | sort -u | sed '/^$/d') declare -A vulkan=() diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-session b/tools/linuxfs/overlay/usr/local/bin/droiddeck-session index df301aadaf..fbea003241 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-session +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-session @@ -132,8 +132,7 @@ clear_stale_tmp() { [ -z "${BL_INSIDE:-}" ] && clear_stale_tmp if [ -z "${BL_INSIDE:-}" ]; then if [ "${BL_ZRAM:-0}" = 1 ]; then printf 0 > /tmp/.bl-zram; else rm -f /tmp/.bl-zram; fi - rm -f /tmp/.bl-clock - head -c 8 /dev/zero > /tmp/.bl-clock + dd if=/dev/zero of=/tmp/.bl-clock bs=8 count=1 conv=notrunc status=none fi steam_devtools() { @@ -512,6 +511,12 @@ if [ -z "${BL_INSIDE:-}" ]; then echo "== gamescope: games at ${nested}x${nested_h} stretched to the ${width}x${height} output" fi fi + if [ "$mode" = run ] && [ "${BL_GAME_WIDTH:-0}" -gt 0 ] && [ "${BL_GAME_HEIGHT:-0}" -gt 0 ]; then + nested=$BL_GAME_WIDTH + nested_h=$BL_GAME_HEIGHT + game_size=1 + echo "== gamescope: the game runs at ${nested}x${nested_h}, scaled to the ${width}x${height} output with its proportions kept" + fi backend=${BL_GAMESCOPE_BACKEND:-wayland} case "$backend" in wayland) ;; @@ -529,7 +534,7 @@ if [ -z "${BL_INSIDE:-}" ]; then echo "== gamescope: composites every frame (Mali bridge: the Steam UI flickers on separate planes)" fi args=(--backend "$backend" --expose-wayland -f -W "$width" -H "$height" -w "$nested" -h "$nested_h") - if [ "$nested" != "$width" ] || [ "$nested_h" != "$height" ]; then + if [ "${game_size:-0}" != 1 ] && { [ "$nested" != "$width" ] || [ "$nested_h" != "$height" ]; }; then args+=(-S stretch) export BL_STRETCHED=1 fi @@ -812,19 +817,30 @@ case $mode in fi } bl_zram_usage() { - local _p _k _v _u _rss=0 _swap=0 + local _p _k _v _u _resident _anonymous _rss=0 _anon=0 _swap=0 for _p in "$@"; do + _resident=0 _anonymous=-1 while read -r _k _v _u; do - case $_k in VmRSS:) _rss=$((_rss + _v)) ;; VmSwap:) _swap=$((_swap + _v)) ;; esac + case $_v in ''|*[!0-9]*) continue ;; esac + case $_k in + VmRSS:) _resident=$_v ;; + RssAnon:) _anonymous=$_v ;; + VmSwap:) _swap=$((_swap + _v)) ;; + esac done 2>/dev/null < "/proc/$_p/status" + [ "$_anonymous" -ge 0 ] || _anonymous=$_resident + _rss=$((_rss + _resident)) _anon=$((_anon + _anonymous)) done - _bl_rss=$_rss + _bl_rss=$_rss _bl_anon=$_anon _bl_swap=$_swap echo "$# processes, resident $((_rss / 1024)) MB, in zram $((_swap / 1024)) MB" } bl_memory_read() { - local _k _v _u _kind _fields _avg - _bl_mem_total=0 _bl_available=-1 _bl_swap_total=0 _bl_swap_free=-1 _bl_psi=0 + local _k _v _u _kind _fields _avg _whole _frac _gpu_bytes _growth _saved_growth _saved_fall + _saved_growth=${_bl_preserved_growth:-0} _saved_fall=${_bl_preserved_fall:-0} + _bl_preserved_growth=0 _bl_preserved_fall=0 + _bl_mem_total=0 _bl_available=-1 _bl_swap_total=0 _bl_swap_free=-1 + _bl_psi_some=0 _bl_psi_full=0 _bl_gpu=0 _bl_unevictable=0 _bl_shmem=0 while read -r _k _v _u; do case $_v in ''|*[!0-9]*) continue ;; esac case $_k in @@ -832,15 +848,50 @@ case $mode in MemAvailable:) _bl_available=$_v ;; SwapTotal:) _bl_swap_total=$_v ;; SwapFree:) _bl_swap_free=$_v ;; + Unevictable:) _bl_unevictable=$_v ;; + Shmem:) _bl_shmem=$_v ;; esac done 2>/dev/null < /proc/meminfo if [ -r /proc/pressure/memory ]; then while read -r _kind _fields; do - [ "$_kind" = some ] || continue - _avg=${_fields#avg10=} _avg=${_avg%% *} _avg=${_avg%%.*} - case $_avg in ''|*[!0-9]*) ;; *) _bl_psi=$((10#$_avg)) ;; esac + [ "$_kind" = some ] || [ "$_kind" = full ] || continue + _avg=${_fields#avg10=} _avg=${_avg%% *} + _whole=${_avg%%.*} _frac=${_avg#*.} + [ "$_frac" = "$_avg" ] && _frac=00 + _frac=${_frac}00 + _frac=${_frac:0:2} + case $_whole$_frac in ''|*[!0-9]*) continue ;; esac + if [ "$_kind" = some ]; then + _bl_psi_some=$((10#$_whole * 100 + 10#$_frac)) + else + _bl_psi_full=$((10#$_whole * 100 + 10#$_frac)) + fi done 2>/dev/null < /proc/pressure/memory fi + if [ -r /sys/class/kgsl/kgsl/page_alloc ]; then + read -r _gpu_bytes _u < /sys/class/kgsl/kgsl/page_alloc + case $_gpu_bytes in ''|*[!0-9]*) _gpu_bytes=0 ;; esac + _bl_gpu=$((_gpu_bytes / 1024)) + fi + _bl_psi=$_bl_psi_some + [ "$_bl_psi_full" -gt "$_bl_psi" ] && _bl_psi=$_bl_psi_full + if [ "${_bl_sample_at:-}" = "" ]; then + _bl_growth=0 _bl_fall=0 + _bl_sample_at=$SECONDS _bl_sample_available=$_bl_available _bl_sample_gpu=$_bl_gpu + _bl_sample_unevictable=$_bl_unevictable _bl_sample_shmem=$_bl_shmem + elif [ "$SECONDS" -gt "$_bl_sample_at" ]; then + _bl_growth=0 _bl_fall=0 + _growth=$((_bl_gpu - _bl_sample_gpu)); [ "$_growth" -gt 0 ] && _bl_growth=$((_bl_growth + _growth)) + _growth=$((_bl_unevictable - _bl_sample_unevictable)); [ "$_growth" -gt 0 ] && _bl_growth=$((_bl_growth + _growth)) + _growth=$((_bl_shmem - _bl_sample_shmem)); [ "$_growth" -gt 0 ] && _bl_growth=$((_bl_growth + _growth)) + _bl_fall=$((_bl_sample_available - _bl_available)) + [ "$_saved_growth" -gt "$_bl_growth" ] && _bl_growth=$_saved_growth + [ "$_saved_fall" -gt "$_bl_fall" ] && _bl_fall=$_saved_fall + _bl_sample_at=$SECONDS _bl_sample_available=$_bl_available _bl_sample_gpu=$_bl_gpu + _bl_sample_unevictable=$_bl_unevictable _bl_sample_shmem=$_bl_shmem + fi + _bl_real_available=$_bl_available + [ "$_bl_real_available" -ge 0 ] && _bl_real_available=$((_bl_real_available - _bl_growth)) _bl_headroom=$((_bl_mem_total / 5)) [ "$_bl_headroom" -ge $((512 * 1024)) ] || _bl_headroom=$((512 * 1024)) [ "$_bl_headroom" -le $((1536 * 1024)) ] || _bl_headroom=$((1536 * 1024)) @@ -852,25 +903,29 @@ case $mode in } bl_memory_tight() { [ "$_bl_mem_total" -gt 0 ] && [ "$_bl_available" -ge 0 ] && - { [ "$_bl_available" -lt "$_bl_headroom" ] || - { [ "$_bl_psi" -ge 1 ] && [ "$_bl_available" -lt $((_bl_mem_total / 3)) ]; }; } + { [ "$_bl_real_available" -lt "$_bl_headroom" ] || + { [ "$_bl_psi" -ge 100 ] && [ "$_bl_real_available" -lt $((_bl_mem_total / 3)) ]; } || + { [ "$_bl_fall" -ge $((256 * 1024)) ] && [ "$_bl_real_available" -lt $((_bl_headroom * 2)) ]; }; } } bl_client_can_pageout() { bl_memory_read bl_zram_usage "${_bl_pids[@]}" > /dev/null - [ "$_bl_mem_total" -gt 0 ] && [ "$_bl_swap_total" -gt 0 ] && - [ $((_bl_swap_free - _bl_rss)) -ge "$_bl_swap_reserve" ] + [ "$_bl_mem_total" -gt 0 ] && bl_zram_has_room + } + bl_zram_has_room() { + [ "$_bl_swap_total" -gt 0 ] && + [ $((_bl_swap_free - _bl_anon - ${_bl_client_reserve:-0})) -ge "$_bl_swap_reserve" ] } bl_client_can_readback() { bl_memory_read bl_zram_usage "${_bl_pids[@]}" > /dev/null - [ "$_bl_mem_total" -gt 0 ] && ! bl_memory_tight && - [ "$_bl_available" -ge $((_bl_swap * 2)) ] && - [ $((_bl_available - _bl_swap)) -ge "$_bl_headroom" ] + [ "$_bl_mem_total" -gt 0 ] && ! bl_memory_tight && ! bl_memory_critical && + [ "$_bl_real_available" -ge $((_bl_swap * 2)) ] && + [ $((_bl_real_available - _bl_swap)) -ge "$_bl_headroom" ] } bl_client_pressure() { [ "${BL_ZRAM_CLIENT:-1}" = 1 ] && [ "$_bl_game" = 1 ] && - [ "${#_bl_pids[@]}" -gt 0 ] && bl_memory_tight || return 0 + [ "${#_bl_pids[@]}" -gt 0 ] && { bl_memory_tight || bl_memory_critical; } || return 0 [ "$_bl_pressure_at" -lt 0 ] || [ $((SECONDS - _bl_pressure_at)) -ge "$_bl_pressure_backoff" ] || return 0 [ "$_bl_packed" -lt 0 ] || [ $((SECONDS - _bl_packed)) -ge 30 ] || return 0 @@ -880,12 +935,29 @@ case $mode in return 0 fi [ "$_bl_rss" -ge $((128 * 1024)) ] || return 0 - local _before=$_bl_rss - bl_zram_send 1 "memory pressure, compressing the client (available $((_bl_available / 1024)) MB, swap free $((_bl_swap_free / 1024)) MB)" client + _bl_pressure_before=$_bl_rss + if [ "${1:-}" = defer ]; then + _bl_client_reserve=$_bl_anon + _bl_client_pending=1 + fi + bl_zram_send 1 "memory pressure, compressing the client (available $((_bl_available / 1024)) MB, swap free $((_bl_swap_free / 1024)) MB)" client "${1:-}" _bl_packed=$SECONDS + if [ "${1:-}" = defer ]; then + _bl_client_targets=("${_bl_zram_targets[@]}") + else + bl_client_pressure_result + fi + } + bl_client_pressure_finish() { + [ "${_bl_client_pending:-0}" = 1 ] || return 0 + bl_zram_finish 1 "${_bl_client_targets[@]}" + bl_client_pressure_result "${_bl_client_targets[@]}" + _bl_client_pending=0 _bl_client_reserve=0 _bl_client_targets=() + } + bl_client_pressure_result() { [ "${_bl_pageout_complete:-0}" = 1 ] || return 0 - bl_zram_usage "${_bl_pids[@]}" > /dev/null - if [ $((_before - _bl_rss)) -lt $((16 * 1024)) ]; then + if [ "$#" -gt 0 ]; then bl_zram_usage "$@" > /dev/null; else bl_zram_usage "${_bl_pids[@]}" > /dev/null; fi + if [ $((_bl_pressure_before - _bl_rss)) -lt $((16 * 1024)) ]; then _bl_pressure_backoff=$((_bl_pressure_backoff * 2 > 300 ? 300 : _bl_pressure_backoff * 2)) else _bl_pressure_backoff=30 @@ -893,15 +965,13 @@ case $mode in } bl_memory_critical() { [ "$_bl_mem_total" -gt 0 ] && [ "$_bl_available" -ge 0 ] && - { [ "$_bl_available" -lt "$_bl_tier_headroom" ] || - { [ "$_bl_psi" -ge 1 ] && [ "$_bl_available" -lt $((_bl_tier_headroom * 3 / 2)) ]; }; } - } - bl_low_ram() { - [ "$_bl_mem_total" -gt 0 ] && [ "$_bl_mem_total" -le $((13 * 1024 * 1024)) ] + { [ "$_bl_real_available" -lt "$_bl_tier_headroom" ] || + { [ "$_bl_psi" -ge 100 ] && [ "$_bl_real_available" -lt $((_bl_tier_headroom * 3 / 2)) ]; } || + { [ "$_bl_fall" -ge $((256 * 1024)) ] && [ "$_bl_real_available" -lt $((_bl_tier_headroom * 2)) ]; }; } } bl_session_pressure() { bl_memory_read - [ "$_bl_game" = 1 ] && bl_low_ram && bl_memory_critical || return 0 + [ "$_bl_game" = 1 ] && bl_memory_critical || return 0 local _wait=$_bl_tier_backoff _before _pids _targets [ "$_bl_available" -ge $((_bl_headroom / 2)) ] || [ "$_bl_tier_pushed" -lt 0 ] || _wait=30 [ "$_bl_tier_at" -lt 0 ] || [ $((SECONDS - _bl_tier_at)) -ge "$_wait" ] || return 0 @@ -917,21 +987,18 @@ case $mode in fi fi _bl_tier_at=$SECONDS _bl_tier_pushed=0 - bl_zram_pick game + bl_zram_pick session bl_zram_usage "${_pids[@]}" > /dev/null [ "$_bl_rss" -ge $((256 * 1024)) ] || return 0 - if [ "$_bl_swap_total" -le 0 ] || [ $((_bl_swap_free - _bl_rss)) -lt "$_bl_swap_reserve" ]; then + if ! bl_zram_has_room; then step "zRAM: low-memory page-out skipped, swap headroom too small ($((_bl_swap_free / 1024)) MB free)" return 0 fi _targets=("${_pids[@]}") _before=$_bl_swap - bl_zram_send 1 "low memory (available $((_bl_available / 1024)) MB), compressing idle game memory" game + bl_zram_send 1 "low memory (available $((_bl_real_available / 1024)) MB), compressing idle game memory" session bl_zram_usage "${_targets[@]}" > /dev/null _bl_tier_pushed=$((_bl_swap - _before)) bl_tier_note "${_targets[@]}" - if [ "${_bl_pageout_complete:-0}" = 1 ] && [ "${BL_ZRAM_CLIENT:-1}" = 1 ] && [ "${#_bl_pids[@]}" -gt 0 ]; then - _bl_pressure_at=$SECONDS _bl_packed=$SECONDS - fi } bl_proc_start() { local _s= @@ -962,7 +1029,7 @@ case $mode in } bl_watch_nap() { local _i - if [ "$_bl_game" = 1 ] && bl_low_ram && [ "$_bl_available" -ge 0 ] && [ "$_bl_available" -lt $((_bl_tier_headroom * 2)) ]; then + if [ "$_bl_game" = 1 ] && [ "$_bl_available" -ge 0 ] && [ "$_bl_real_available" -lt $((_bl_tier_headroom * 2)) ]; then for _i in 1 2 3 4 5; do nap 1 bl_memory_read @@ -1018,10 +1085,16 @@ case $mode in for _p in "${_pids[@]}"; do rm -f "/tmp/.bl-zram.ack.$_p"; done printf '%s' "$_mode" > /tmp/.bl-zram [ "${#_pids[@]}" = 0 ] || kill -URG "${_pids[@]}" 2>/dev/null - if [ "$_mode" = 1 ]; then bl_zram_wait "${_pids[@]}"; else nap 5; fi + _bl_zram_targets=("${_pids[@]}") + [ "${4:-}" != defer ] || return 0 + bl_zram_finish "$_mode" "${_pids[@]}" + } + bl_zram_finish() { + local _mode=$1 + shift + if [ "$_mode" = 1 ]; then bl_zram_wait "$@"; else nap 5; fi bl_zram_scan - bl_zram_pick "$_which" - step "zRAM: done ($(bl_zram_usage "${_pids[@]}"))" + step "zRAM: done ($(bl_zram_usage "$@"))" } bl_game_focused() { if [ "${BL_DESKTOP:-}" = 1 ] || [ -z "${BL_LAUNCH_DIR:-}" ]; then @@ -1048,6 +1121,8 @@ case $mode in } _bl_since=-1 _bl_since_apps= _bl_packed=-1 _bl_measured=-1 _bl_unpack=0 _bl_capped=-1 _bl_backoff=30 _bl_pressure_at=-1 _bl_pressure_backoff=30 _bl_tier_at=-1 _bl_tier_backoff=30 _bl_tier_pushed=0 _bl_tier_back=0 _bl_tier_targets=() _bl_tier_swaps=() _bl_tier_starts=() + _bl_client_pending=0 _bl_client_reserve=0 _bl_client_targets=() + _bl_sample_at= _bl_sample_available=0 _bl_sample_gpu=0 _bl_sample_unevictable=0 _bl_sample_shmem=0 while kill -0 $$ 2>/dev/null; do bl_zram_scan bl_memory_read @@ -1074,8 +1149,11 @@ case $mode in _bl_backoff=30 fi fi + _bl_preserved_growth=$_bl_growth _bl_preserved_fall=$_bl_fall + bl_client_pressure defer + _bl_preserved_growth=$_bl_growth _bl_preserved_fall=$_bl_fall bl_session_pressure - bl_client_pressure + bl_client_pressure_finish if [ "$_bl_game" = 1 ] && bl_game_focused; then if [ "$_bl_since" -lt 0 ] || [ "$_bl_since_apps" != "$_bl_apps" ]; then _bl_since=$SECONDS _bl_since_apps=$_bl_apps @@ -1118,7 +1196,7 @@ case $mode in step "adding the app's own games to the client's library" droiddeck-steam-shortcuts "$steam_root" "$BL_ADDED_GAMES" || true fi - droiddeck-seed-redists "$steam_root" || true + DROIDDECK_SEED_LATER=1 droiddeck-seed-redists "$steam_root" || true else _bl_x64_tool=$(droiddeck-steam-x64 --default-tool) if [ -n "$_bl_x64_tool" ]; then @@ -1132,7 +1210,7 @@ case $mode in if [ -z "${BL_DESKTOP:-}" ] && [ "${BL_STEAM_UI:-}" != desktop ]; then droiddeck-steam-ui-scale "$steam_root" "${BL_WIDTH:-1280}" "${BL_HEIGHT:-720}" || true fi - droiddeck-seed-redists "$steam_root" || true + DROIDDECK_SEED_LATER=1 droiddeck-seed-redists "$steam_root" || true fi if [ -n "${BL_SHADER_PRECACHE:-}" ]; then droiddeck-steam-shaders "$BL_SHADER_PRECACHE" "$XDG_DATA_HOME/Steam" \ @@ -1396,6 +1474,8 @@ case $mode in decky_stop() { [ -z "$decky_child" ] || kill "$decky_child" 2>/dev/null; [ -z "$decky_child" ] || wait "$decky_child" 2>/dev/null; exit 0; } trap decky_stop TERM INT HUP decky_exits=0 + # The guest has no "deck" user, which Decky otherwise requires at startup. + export UNPRIVILEGED_USER=root while :; do if [ "$decky_arch" = x86_64 ]; then /usr/local/bin/droiddeck-fex run --mode on -- "$decky_loader" >>"$HOME/homebrew/services/PluginLoader.log" 2>&1 & else "$decky_loader" >>"$HOME/homebrew/services/PluginLoader.log" 2>&1 & diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-games b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-games index c902676d3f..ac8213d41e 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-games +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-games @@ -71,7 +71,11 @@ def store_game(game): def manifest_ids(steamapps, name): matches = [] - for manifest in Path(steamapps).glob("appmanifest_*.acf"): + try: + manifests = list(Path(steamapps).glob("appmanifest_*.acf")) + except OSError: + return matches + for manifest in manifests: try: install = re.search(r'"installdir"\s*"([^"\\]*)"', manifest.read_text(), re.I) if install and install[1] == name: @@ -81,13 +85,21 @@ def manifest_ids(steamapps, name): return matches -def identify(game): +def manifest_identity(game): folder = Path(game["folder"]) steamapps = folder.parent.parent for library in ([steamapps] if folder.parent.name == "common" and steamapps.name == "steamapps" else []) + [folder.parent / WINNATIVE]: matches = [appid for appid in manifest_ids(library, folder.name) if appid != SPACEWAR] if matches: - return matches[0] if len(matches) == 1 else None + return (matches[0], library) if len(matches) == 1 else None + return False + + +def identify(game): + folder = Path(game["folder"]) + found = manifest_identity(game) + if found is not False: + return found[0] if found is not None else None ids = set() for parent in {folder, Path(game["exe"]).parent}: try: @@ -508,6 +520,57 @@ def release(steam_root, game, stale, reason): print(f"droiddeck-steam-games: {game.get('name', appid)} {reason}; it is no longer Steam app {appid}") +PREFIX_LINKS = ".droiddeck-prefix-links.json" + + +def steam_prefix(steam_root, game): + identity = manifest_identity(game) + if not identity or not identity[0]: + return None, None + appid, steamapps = identity + installed = steamapps == Path(game["folder"]).parent.parent + for library in [steamapps.parent] if installed else dict.fromkeys([steamapps.parent] + libraries(steam_root)): + prefix = library / "steamapps/compatdata" / str(appid) + if (prefix / "pfx/drive_c").is_dir(): + return appid, str(prefix) + return appid, None + + +def share_prefix(steam_root, game): + shortcut = Path(steam_root) / "steamapps/compatdata" / str(game["appid"] & 0xFFFFFFFF) + record = Path(steam_root) / "steamapps" / PREFIX_LINKS + links = read_json(record, {}) + if not isinstance(links, dict): + links = {} + before = dict(links) + key = str(shortcut) + name = game.get("name", "game") + appid, target = steam_prefix(steam_root, game) + try: + current = os.readlink(shortcut) if os.path.islink(shortcut) else None + if current is not None and links.get(key) == current and current != target: + if target is not None or (not os.path.exists(shortcut) and Path(current).parent.parent.is_dir()): + shortcut.unlink() + current = None + if current is None: + links.pop(key, None) + if current is None and os.path.lexists(shortcut): + if target is not None: + print(f"droiddeck-steam-games: {name} keeps its own prefix; Steam app {appid} saves are in {target}") + elif current is None and target is not None: + shortcut.parent.mkdir(parents=True, exist_ok=True) + shortcut.symlink_to(target) + links[key] = target + print(f"droiddeck-steam-games: {name} shares the saves prefix of Steam app {appid}") + except OSError as error: + print(f"droiddeck-steam-games: {name} keeps its own prefix ({error})") + if links != before: + try: + save_json(record, links) + except OSError as error: + print(f"droiddeck-steam-games: prefix links not recorded ({error})") + + def route(steam_root, acct, games): snapshot = read_json(Path(acct) / "config" / STATE, {}) if not isinstance(snapshot, dict): @@ -557,6 +620,7 @@ def route(steam_root, acct, games): elif named and seeded(steamapps, game, appid): routes[str(game["appid"])] = appid continue + share_prefix(steam_root, game) shortcuts.append(game) try: park(steamapps) diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-x64 b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-x64 index 481d25d194..0aeb0e594c 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-x64 +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-x64 @@ -449,7 +449,11 @@ mkdir -p "$srt_libs" for d in "$STEAM_X64"/steamrt64/pv-runtime/steam-runtime-steamrt/steamrt3c_platform_*/files/lib/x86_64-linux-gnu \ "$STEAM_X64"/steamrt64/pv-runtime/steam-runtime-steamrt/steamrt3c_platform_*/files/usr/lib/x86_64-linux-gnu; do [ -d "$d" ] || continue - for f in "$d"/*.so*; do [ -e "$srt_libs/$(basename "$f")" ] || ln -s "$f" "$srt_libs/"; done + for f in "$d"/*.so*; do + [ -e "$f" ] || [ -L "$f" ] || continue + s="$srt_libs/$(basename "$f")" + { [ -e "$s" ] || [ -L "$s" ]; } || ln -s "$f" "$srt_libs/" + done done FEX_ROOTFS=$ROOTFS /usr/local/bin/FEX "$ROOTFS/usr/sbin/ldconfig.real" -n "$srt_libs" >>"$LOG" 2>&1 || step "ldconfig on $srt_libs failed" sniper_compat=$X64_HOME/sniper-compat @@ -458,6 +462,7 @@ mkdir -p "$sniper_compat" hb=$(ls "$srt_libs"/libharfbuzz.so.0.* 2>/dev/null | head -n 1) if [ -n "$hb" ]; then ln -s "$hb" "$sniper_compat/libharfbuzz.so.0"; else step "warning: no HarfBuzz in Valve's runtime for the newer-runtime titles"; fi for f in "$srt_libs"/*; do + [ -e "$f" ] || [ -L "$f" ] || continue n=$(basename "$f") if [ -e "$ROOTFS/usr/lib/x86_64-linux-gnu/$n" ] || [ -e "$ROOTFS/lib/x86_64-linux-gnu/$n" ]; then rm -f "$f"; fi done diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-store-launch b/tools/linuxfs/overlay/usr/local/bin/droiddeck-store-launch index ca6ddebc84..3d07aaba6a 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-store-launch +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-store-launch @@ -48,14 +48,14 @@ def sidecar_at(folder): return sidecar -def find_store_game(argv): +def find_store_game(argv, depth=MAX_DEPTH): for raw in argv: arg = raw.strip().strip('"').strip("'").replace("\\", "/") low = arg.lower() if not (low.endswith(LAUNCHER) or low.endswith(".exe") or low.endswith(".bat")) or "/" not in arg: continue folder = Path(arg).parent - for _ in range(MAX_DEPTH): + for _ in range(depth): sidecar = sidecar_at(folder) if sidecar is not None: return folder, sidecar @@ -65,6 +65,21 @@ def find_store_game(argv): return None +def store_launcher(path): + real = os.path.realpath(path) + for start in dict.fromkeys([os.path.abspath(path), real]): + found = find_store_game([start], depth=len(Path(start).parts)) + if found is None: + continue + folder, sidecar = found + launcher, exe = str(sidecar.get("launcher") or ""), str(sidecar.get("exe") or "") + if not launcher or not exe or (folder / launcher).is_symlink() or not (folder / launcher).is_file(): + continue + if os.path.realpath(folder / exe).lower() == real.lower(): + return str(folder / launcher) + return None + + def drop_stale(folder, now=None): code = folder / EPIC_CODE try: @@ -271,6 +286,12 @@ def cloud_on(sidecar): def exited(argv, code=0): found = find_store_game(argv) launch_dir = os.environ.get("BL_LAUNCH_DIR", "") + if found is not None and launch_dir and str(found[1].get("store")) == "rockstar": + ask(Path(launch_dir) / "stores", {"op": "rockstar-exited", "store": "rockstar", "id": str(found[1].get("id"))}, timeout=1.0) + compat_data = os.environ.get("STEAM_COMPAT_DATA_PATH") + if compat_data: + (Path(compat_data) / "pfx" / ROCKSTAR_FOLDER / "launch.json").unlink(missing_ok=True) + return 0 if found is not None and str(found[1].get("store")) == "epic" and os.environ.get(EPIC_HANDLED) != "1" \ and os.access(EPIC_CLIENT, os.X_OK): try: @@ -292,6 +313,231 @@ def exited(argv, code=0): UBISOFT_DIR = "drive_c/Program Files (x86)/Ubisoft/Ubisoft Game Launcher" UBISOFT_WINDOWS_DIR = "C:\\Program Files (x86)\\Ubisoft\\Ubisoft Game Launcher\\" UBISOFT_INSTALLER_URL = "https://static3.cdn.ubi.com/orbit/launcher_installer/UbisoftConnectInstaller.exe" +ROCKSTAR_SERVICE = Path("/usr/local/lib/droiddeck-rockstar") +ROCKSTAR_FOLDER = "drive_c/Program Files/Rockstar Games/Launcher" +ROCKSTAR_TITLES = {"gta3": "Grand Theft Auto III", "gtavc": "Grand Theft Auto: Vice City", "gtasa": "GTA: San Andreas", + "gta4": "Grand Theft Auto IV", "lanoire": "LANoireMTL"} + + +def rockstar_sdk(folder, sidecar): + if str(sidecar.get("id")) in ("gta4", "lanoire"): + return True + root = folder.resolve() + exe = (folder / str(sidecar.get("exe") or "").replace("\\", "/")).resolve() + if not exe.is_relative_to(root): + return False + for directory in {root, exe.parent}: + if directory.is_dir() and any(p.is_file() and not p.is_symlink() and p.name.lower() in ("socialclub.dll", "socialclub64.dll") + for p in directory.iterdir()): + return True + if str(sidecar.get("id")) in ROCKSTAR_TITLES: + return False + level = [root] + for _ in range(4): + children = [] + for directory in level: + for path in directory.iterdir(): + if path.is_symlink(): + continue + if path.name.lower() == "title.rgl" and path.is_file() and path.resolve().is_relative_to(root) and 112 <= path.stat().st_size <= 1048576: + with path.open("rb") as source: + if source.read(4) == b"RGLM": + return True + if len(children) < 256 and path.is_dir() and path.resolve().is_relative_to(root): + children.append(path) + level = children + return False + + +def rockstar_registry(folder, title, compat_data, proton, sdk_arch=None): + pfx = Path(compat_data) / "pfx" + launcher = r"C:\Program Files\Rockstar Games\Launcher" + values = [(r"Rockstar Games\Launcher", launcher)] + if title: + values.append(("Rockstar Games\\" + title, windows_path(str(folder)))) + entries = [("Software\\" + view + key, value) for view in ("", "Wow6432Node\\") for key, value in values] + if sdk_arch: + entries.append((r"Software\Rockstar Games\Rockstar Games Social Club", r"C:\Program Files\Rockstar Games\Social Club")) + program = "Program Files (x86)" if sdk_arch == "x86" else "Program Files" + entries.append((r"Software\Wow6432Node\Rockstar Games\Rockstar Games Social Club", "C:\\" + program + r"\Rockstar Games\Social Club")) + reg = pfx / "system.reg" + if all(has_value(reg, "[" + key.replace("\\", "\\\\") + "]", "InstallFolder", value) for key, value in entries): + return True + if wait_for_server(pfx, 2): + return all(set_value(reg, "[" + key.replace("\\", "\\\\") + "]", "InstallFolder", value) for key, value in entries) + with tempfile.TemporaryDirectory(prefix="droiddeck-rockstar-") as temp: + path = Path(temp) / "install.reg" + text = "Windows Registry Editor Version 5.00\r\n\r\n" + text += "\r\n".join('[HKEY_LOCAL_MACHINE\\%s]\r\n"InstallFolder"="%s"\r\n' % (key, reg_escape(value)) for key, value in entries) + path.write_text(text, encoding="utf-16") + result = subprocess.run([proton, "run", "reg.exe", "import", windows_path(str(path))], + stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=45) + return result.returncode == 0 + + +def rockstar_runtime(folder, exe, compat_data, arch): + if arch == "x86": + rockstar_runtime(folder, exe, compat_data, "x64") + pfx = Path(compat_data) / "pfx" + target = pfx / "drive_c" / ("Program Files (x86)" if arch == "x86" else "Program Files") / "Rockstar Games/Social Club" + if not target.resolve().is_relative_to(pfx.resolve()): + raise ValueError("invalid Social Club destination") + required = ("socialclub.dll", "socialclub.pak") + (("SocialClubHelper.exe",) if arch == "x64" else ()) + marker = target / ".droiddeck-installing" + if all((target / name).is_file() for name in required) and not marker.exists(): + return "present" + root = folder.resolve() + installers = [base / sub / "Social-Club-Setup.exe" for base in (root, exe.parent) + for sub in ("Redistributables", "Installers")] + installer = next((p for p in installers if p.is_file() and p.resolve().is_relative_to(root) and p.stat().st_size <= 256 * 1024 * 1024), None) + if installer is None: + return "game-runtime" + tool = shutil.which("7z") + if not tool: + return "no-unpacker" + listing = subprocess.run([tool, "l", "-t7z", "-slt", "-ba", str(installer)], capture_output=True, + stdin=subprocess.DEVNULL, timeout=30) + if listing.returncode: + return "installer-unreadable" + entries, size = [], 0 + for block in listing.stdout.decode("utf-8", "replace").split("\n\n"): + fields = dict(line.split(" = ", 1) for line in block.splitlines() if " = " in line) + name = fields.get("Path", "").replace("\\", "/") + if not name.startswith(arch + "/"): + continue + if ".." in name.split("/") or ":" in name or fields.get("Symbolic Link") or fields.get("Hard Link"): + raise ValueError("invalid Social Club archive path") + entry_size = int(fields.get("Size", "0")) + if entry_size < 0: + raise ValueError("invalid Social Club member size") + size += entry_size + entries.append(name) + if not entries or len(entries) > 2048 or size > 768 * 1024 * 1024: + raise ValueError("invalid Social Club archive size") + with tempfile.TemporaryDirectory(prefix="droiddeck-socialclub-") as temporary: + result = subprocess.run([tool, "x", "-t7z", "-y", "-o" + temporary, str(installer), arch + "/*"], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, stdin=subprocess.DEVNULL, timeout=180) + source = Path(temporary) / arch + if result.returncode or not all((source / name).is_file() for name in required): + return "installer-incomplete" + target.mkdir(parents=True, exist_ok=True) + if marker.is_symlink(): + raise ValueError("invalid Social Club install marker") + marker.touch() + for path in source.rglob("*"): + if path.is_symlink() or not path.resolve().is_relative_to(source.resolve()): + raise ValueError("invalid Social Club archive member") + if not path.is_file(): + continue + output = target / path.relative_to(source) + if not output.resolve().is_relative_to(pfx.resolve()): + raise ValueError("invalid Social Club output path") + output.parent.mkdir(parents=True, exist_ok=True) + with tempfile.NamedTemporaryFile(dir=output.parent, delete=False) as stage: + stage_path = Path(stage.name) + try: + with path.open("rb") as stream: + shutil.copyfileobj(stream, stage) + except BaseException: + stage_path.unlink(missing_ok=True) + raise + os.replace(stage_path, output) + marker.unlink() + return "installed" + + +def prepare_rockstar(folder, sidecar, compat_data, launch_dir, proton="", ask_app=None): + if not compat_data: + return "no-prefix" + target = Path(compat_data) / "pfx" / ROCKSTAR_FOLDER + if not target.resolve().is_relative_to((Path(compat_data) / "pfx").resolve()): + return "invalid-service-path" + config = target / "launch.json" + config.unlink(missing_ok=True) + legacy = str(sidecar.get("id")) in ROCKSTAR_TITLES + sdk = rockstar_sdk(folder, sidecar) + title = ROCKSTAR_TITLES.get(str(sidecar.get("id"))) + if not launch_dir: + return "no-channel" + root = folder.resolve() + exe = (folder / str(sidecar.get("exe") or "").replace("\\", "/")).resolve() + if not exe.is_relative_to(root): + return "invalid-game-path" + workdir = (folder / str(sidecar["workdir"])).resolve() if sidecar.get("workdir") is not None else exe.parent + if not workdir.is_relative_to(root) or not exe.is_file() or legacy and not any((p / "MTLX.dll").is_file() for p in (root, exe.parent)): + return "invalid-game-path" + args = sidecar.get("args") or [] + if not isinstance(args, list) or any(not isinstance(arg, str) or "\0" in arg for arg in args): + return "invalid-game-arguments" + with exe.open("rb") as source: + if source.read(2) != b"MZ": + return "invalid-game-exe" + source.seek(0x3c) + raw = source.read(4) + if len(raw) != 4: + return "invalid-game-exe" + source.seek(int.from_bytes(raw, "little")) + signature = source.read(6) + if len(signature) != 6 or signature[:4] != b"PE\0\0" or signature[4:] not in (b"\x4c\x01", b"\x64\x86"): + return "invalid-game-exe" + service = ROCKSTAR_SERVICE / ("Launcher32.exe" if signature[4:] == b"\x4c\x01" else "Launcher64.exe") + if not service.is_file(): + return "no-service" + made = "present" if (Path(compat_data) / "pfx/user.reg").is_file() else create_prefix(compat_data, proton) + if made not in ("created", "present"): + return "prefix-" + made + arch = "x86" if signature[4:] == b"\x4c\x01" else "x64" + if sdk: + log("rockstar runtime: " + rockstar_runtime(folder, exe, compat_data, arch)) + if not rockstar_registry(folder, title, compat_data, proton, sdk_arch=arch if sdk else None): + return "registry-unavailable" + target.mkdir(parents=True, exist_ok=True) + with tempfile.NamedTemporaryFile(prefix="Launcher-", suffix=".exe", dir=target, delete=False) as temporary: + temporary_path = Path(temporary.name) + try: + with service.open("rb") as source: + shutil.copyfileobj(source, temporary) + except BaseException: + temporary_path.unlink(missing_ok=True) + raise + os.replace(temporary_path, target / "Launcher.exe") + answer = (ask_app or ask)(Path(launch_dir) / "stores", {"op": "rockstar-launch", "store": "rockstar", "id": str(sidecar.get("id"))}, timeout=120.0) + if not isinstance(answer, dict) or not answer.get("ok"): + return "session-" + (str(answer.get("reason") or "refused") if isinstance(answer, dict) else "timeout") + if legacy and (not isinstance(answer.get("material"), str) or not re.fullmatch(r"[0-9A-Fa-f]{640}", answer["material"])): + return "invalid-material" + expires = answer.get("expiresAt") + if not isinstance(expires, int) or not time.time() * 1000 < expires <= time.time() * 1000 + 120_000: + return "invalid-expiry" + launch = {"folder": windows_path(str(root)), "exe": windows_path(str(exe)), "workdir": windows_path(str(workdir)), + "args": args, "expiresAt": expires} + if legacy: + launch.update(pipe=answer.get("pipe"), material=answer["material"]) + if sdk: + session = answer.get("session") + if not isinstance(session, dict) or not isinstance(session.get("accountId"), str) \ + or not re.fullmatch(r"[1-9][0-9]{0,19}", session["accountId"]) or int(session["accountId"]) > 2**64 - 1 \ + or any(not isinstance(session.get(key), str) or not session[key] or "\0" in session[key] + or len(session[key].encode("utf-8")) > limit for key, limit in (("identity", 512), ("ticket", 49152))): + return "invalid-sdk-session" + launch["session"] = {key: session[key] for key in ("accountId", "identity", "ticket")} + if "titleId" in session: + if not isinstance(session["titleId"], str) or not re.fullmatch(r"[a-z][a-z0-9_]{0,63}", session["titleId"]): + return "invalid-sdk-title" + launch["session"]["titleId"] = session["titleId"] + if len(json.dumps(launch).encode("utf-8")) > 65536: + return "handoff-too-large" + with tempfile.NamedTemporaryFile(mode="w", prefix="launch-", suffix=".json", dir=target, delete=False) as temporary: + temporary_path = Path(temporary.name) + try: + json.dump(launch, temporary) + except BaseException: + temporary_path.unlink(missing_ok=True) + raise + os.replace(temporary_path, config) + return "ready" + + UBISOFT_CACHE = Path("/root/.cache/droiddeck/ubisoft") UBISOFT_LAUNCH = ".droiddeck-ubisoft.json" UBISOFT_SERVICE = Path("/usr/local/lib/droiddeck-ubisoft/droiddeck-upc.exe") @@ -1326,6 +1572,19 @@ def main(argv): prepare_gog(sidecar, compat_data, launch_dir) log("gog registry: " + apply_gog_registry(folder, compat_data, os.environ.get("BL_STORE_PROTON", ""))) log("gog support data: " + gog_support_data(folder, compat_data, os.environ.get("BL_STORE_PROTON", ""))) + if store == "rockstar": + if game not in ROCKSTAR_TITLES and not rockstar_sdk(folder, sidecar): + if compat_data: + (Path(compat_data) / "pfx" / ROCKSTAR_FOLDER / "launch.json").unlink(missing_ok=True) + return STORE_GAME + try: + state = prepare_rockstar(folder, sidecar, compat_data, launch_dir, os.environ.get("BL_STORE_PROTON", "")) + except (OSError, ValueError, subprocess.TimeoutExpired): + state = "preparation-failed" + log("rockstar %s: %s" % (game, state)) + if state != "ready" and launch_dir: + ask(Path(launch_dir) / "stores", {"op": "rockstar-exited", "store": "rockstar", "id": game}, timeout=1.0) + return STORE_GAME if state == "ready" else RAN_FAILED if store == "ubisoft": try: log("ubisoft %s: %s" % (game, prepare_ubisoft(folder, sidecar, compat_data, launch_dir, os.environ.get("BL_STORE_PROTON", "")))) diff --git a/tools/linuxfs/overlay/usr/local/bin/steam-compatibility b/tools/linuxfs/overlay/usr/local/bin/steam-compatibility index 426b6c173b..cf616c86fc 100755 --- a/tools/linuxfs/overlay/usr/local/bin/steam-compatibility +++ b/tools/linuxfs/overlay/usr/local/bin/steam-compatibility @@ -1540,7 +1540,7 @@ def register_default(config_path, apps=(), protect=(), default=None, catalog=Non auto = followers(state, current) known = {app for app in state.get("owned", ()) if isinstance(app, str)} if isinstance(state.get("owned"), list) else set() pinned = {app: current[app] for app in set(owned) - known - if current.get(app) in {TOOL, previous} | gone and app not in auto} + if app in current and current.get(app) in {TOOL, previous} | gone and app not in auto} if pinned and isinstance(auto, dict): state["auto"] = dict(auto, **pinned) state["owned"] = sorted(set(owned), key=app_order) diff --git a/tools/linuxfs/preload/clockpause.c b/tools/linuxfs/preload/clockpause.c index 19a1d728ab..eed7a401d7 100644 --- a/tools/linuxfs/preload/clockpause.c +++ b/tools/linuxfs/preload/clockpause.c @@ -81,7 +81,6 @@ static void cp_init(void) { struct stat st; void *map; int fd; - if (strcmp(program_invocation_short_name, "plasmashell") != 0) return; if (!cp_find_cond_bit()) return; fd = open(CP_CTL, O_RDONLY | O_CLOEXEC); if (fd < 0) return; diff --git a/tools/linuxfs/preload/descriptor.c b/tools/linuxfs/preload/descriptor.c new file mode 100644 index 0000000000..681dce999e --- /dev/null +++ b/tools/linuxfs/preload/descriptor.c @@ -0,0 +1,291 @@ +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define DESCRIPTOR "user.wine.sd" +#define STORE "/.droiddeck-descriptors" +#define ENTRY_MAX (PATH_MAX * 2) + +int bl_is_wineserver(void) __attribute__((visibility("hidden"))); + +static int store_seen; + +static int kept(const char *name) { + return name != NULL && strcmp(name, DESCRIPTOR) == 0 && bl_is_wineserver(); +} + +static int store_root(char *out, size_t size) { + const char *prefix = getenv("WINEPREFIX"); + int n; + + if (prefix == NULL || prefix[0] != '/') return -1; + n = snprintf(out, size, "%s" STORE, prefix); + return n > 0 && (size_t)n < size ? n : -1; +} + +static int store_exists(void) { + char root[PATH_MAX]; + + if (store_seen) return 1; + if (store_root(root, sizeof(root)) < 0) return 0; + store_seen = access(root, F_OK) == 0; + return store_seen; +} + +static int entry_for(const char *path, char *out, size_t size, const char *suffix, int create) { + int used = store_root(out, size); + const char *part = path, *end; + + if (used < 0 || path[0] != '/') return -1; + if (create && mkdir(out, 0700) != 0 && errno != EEXIST) return -1; + while (*part == '/') part++; + if (*part == '\0') return -1; + for (;;) { + size_t length; + const char *tail; + + end = strchr(part, '/'); + length = end ? (size_t)(end - part) : strlen(part); + tail = end ? ".d" : suffix; + if (length + strlen(tail) > NAME_MAX || used + length + strlen(tail) + 2 > size) return -1; + out[used++] = '/'; + memcpy(out + used, part, length); + used += (int)length; + strcpy(out + used, tail); + used += (int)strlen(tail); + if (!end) break; + if (create && mkdir(out, 0700) != 0 && errno != EEXIST) return -1; + part = end + 1; + } + if (create) store_seen = 1; + return 0; +} + +static int path_of(int fd, char *out, size_t size) { + char link[40]; + ssize_t n; + + snprintf(link, sizeof(link), "/proc/self/fd/%d", fd); + n = readlink(link, out, size - 1); + if (n <= 0 || out[0] != '/') return -1; + out[n] = '\0'; + return 0; +} + +static int resolved(const char *path, char *out, size_t size) { + int fd, result; + + if (path == NULL) return -1; + fd = open(path, O_PATH | O_NOFOLLOW | O_CLOEXEC); + if (fd < 0) return -1; + result = path_of(fd, out, size); + close(fd); + return result; +} + +static int entry_of(int fd, char *out, size_t size, int create) { + char path[PATH_MAX]; + + if (path_of(fd, path, sizeof(path)) != 0) return -1; + return entry_for(path, out, size, ".sd", create); +} + +static ssize_t stored_read(int fd, void *value, size_t size) { + char entry[ENTRY_MAX]; + struct stat st; + ssize_t got = 0; + int file; + + if (entry_of(fd, entry, sizeof(entry), 0) != 0) return -2; + file = open(entry, O_RDONLY | O_NOFOLLOW | O_CLOEXEC); + if (file < 0) { + if (errno != ENOENT) return -2; + errno = ENODATA; + return -1; + } + if (fstat(file, &st) != 0) { + close(file); + return -2; + } + if (size == 0) { + close(file); + return (ssize_t)st.st_size; + } + if ((size_t)st.st_size > size) { + close(file); + errno = ERANGE; + return -1; + } + while (got < st.st_size) { + ssize_t n = read(file, (char *)value + got, (size_t)(st.st_size - got)); + if (n <= 0) { + close(file); + return -2; + } + got += n; + } + close(file); + return got; +} + +static int stored_write(int fd, const void *value, size_t size) { + char entry[ENTRY_MAX], fresh[ENTRY_MAX + 8]; + size_t put = 0; + int file; + + if (entry_of(fd, entry, sizeof(entry), 1) != 0) return -1; + snprintf(fresh, sizeof(fresh), "%s.new", entry); + file = open(fresh, O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW | O_CLOEXEC, 0600); + if (file < 0) return -1; + while (put < size) { + ssize_t n = write(file, (const char *)value + put, size - put); + if (n <= 0) { + close(file); + unlinkat(AT_FDCWD, fresh, 0); + return -1; + } + put += (size_t)n; + } + if (close(file) != 0 || renameat(AT_FDCWD, fresh, AT_FDCWD, entry) != 0) { + unlinkat(AT_FDCWD, fresh, 0); + return -1; + } + return 0; +} + +ssize_t fgetxattr(int fd, const char *name, void *value, size_t size) { + static ssize_t (*next)(int, const char *, void *, size_t); + ssize_t result; + + if (next == NULL) next = dlsym(RTLD_NEXT, "fgetxattr"); + if (next == NULL) { + errno = ENOSYS; + return -1; + } + result = next(fd, name, value, size); + if (result >= 0 || errno != ENOTSUP || !kept(name)) return result; + result = stored_read(fd, value, size); + if (result == -2) { + errno = ENOTSUP; + return -1; + } + return result; +} + +int fsetxattr(int fd, const char *name, const void *value, size_t size, int flags) { + static int (*next)(int, const char *, const void *, size_t, int); + int saved = errno, result; + + if (next == NULL) next = dlsym(RTLD_NEXT, "fsetxattr"); + if (next == NULL) { + errno = ENOSYS; + return -1; + } + result = next(fd, name, value, size, flags); + if (result == 0 || errno != ENOTSUP || !kept(name)) return result; + if (stored_write(fd, value, size) != 0) { + errno = ENOTSUP; + return -1; + } + errno = saved; + return 0; +} + +int fremovexattr(int fd, const char *name) { + static int (*next)(int, const char *); + char entry[ENTRY_MAX]; + int saved = errno, result; + + if (next == NULL) next = dlsym(RTLD_NEXT, "fremovexattr"); + if (next == NULL) { + errno = ENOSYS; + return -1; + } + result = next(fd, name); + if (result == 0 || errno != ENOTSUP || !kept(name)) return result; + if (entry_of(fd, entry, sizeof(entry), 0) != 0) { + errno = ENOTSUP; + return -1; + } + if (unlinkat(AT_FDCWD, entry, 0) != 0) { + errno = errno == ENOENT ? ENODATA : ENOTSUP; + return -1; + } + errno = saved; + return 0; +} + +static int tracked(const char *path, char *out, size_t size) { + int saved = errno, found; + + found = bl_is_wineserver() && store_exists() && resolved(path, out, size) == 0; + errno = saved; + return found; +} + +static void forget(const char *path, int folder) { + char entry[ENTRY_MAX]; + int saved = errno; + + if (entry_for(path, entry, sizeof(entry), ".sd", 0) == 0) unlinkat(AT_FDCWD, entry, 0); + if (folder && entry_for(path, entry, sizeof(entry), ".d", 0) == 0) unlinkat(AT_FDCWD, entry, AT_REMOVEDIR); + errno = saved; +} + +static void follow(const char *from, const char *to) { + static const char *const kinds[] = {".sd", ".d"}; + char old[ENTRY_MAX], new[ENTRY_MAX]; + int saved = errno; + + for (size_t i = 0; i < 2; i++) { + if (entry_for(from, old, sizeof(old), kinds[i], 0) != 0) continue; + if (access(old, F_OK) != 0) { + if (i == 0 && entry_for(to, new, sizeof(new), kinds[i], 0) == 0) unlinkat(AT_FDCWD, new, 0); + continue; + } + if (entry_for(to, new, sizeof(new), kinds[i], 1) != 0 || renameat(AT_FDCWD, old, AT_FDCWD, new) != 0) { + if (i == 0) unlinkat(AT_FDCWD, old, 0); + } + } + errno = saved; +} + +__attribute__((visibility("hidden"))) +int bl_descriptor_unlink(const char *path, int (*real)(const char *)) { + char target[PATH_MAX]; + int known = tracked(path, target, sizeof(target)), result = real(path); + + if (result == 0 && known) forget(target, 0); + return result; +} + +__attribute__((visibility("hidden"))) +int bl_descriptor_rmdir(const char *path, int (*real)(const char *)) { + char target[PATH_MAX]; + int known = tracked(path, target, sizeof(target)), result = real(path); + + if (result == 0 && known) forget(target, 1); + return result; +} + +__attribute__((visibility("hidden"))) +int bl_descriptor_remove(const char *path, int (*real)(const char *)) { + return bl_descriptor_rmdir(path, real); +} + +__attribute__((visibility("hidden"))) +int bl_descriptor_rename(const char *from, const char *to, int (*real)(const char *, const char *)) { + char old[PATH_MAX], new[PATH_MAX]; + int known = tracked(from, old, sizeof(old)), result = real(from, to); + + if (result == 0 && known && tracked(to, new, sizeof(new))) follow(old, new); + return result; +} diff --git a/tools/linuxfs/preload/dircache.c b/tools/linuxfs/preload/dircache.c index 296faa616b..a94717bd78 100644 --- a/tools/linuxfs/preload/dircache.c +++ b/tools/linuxfs/preload/dircache.c @@ -83,6 +83,19 @@ static int notify = -1; static int forked; static struct { dev_t dev; int fuse; } devs[8]; static int ndevs; +// Libraries preloaded after this one can call back in while a lock is held (the native userland +// hook's inotify_add_watch calls mkdir() by name); such calls go straight to the next library. +static __thread int holding; + +static void take(pthread_mutex_t *m) { + pthread_mutex_lock(m); + holding++; +} + +static void give(pthread_mutex_t *m) { + holding--; + pthread_mutex_unlock(m); +} static long long now_ns(void) { struct timespec t; @@ -109,32 +122,32 @@ static int enabled(void) { } static int eligible(const char *path) { - if (path == NULL || path[0] != '/' || !enabled()) return 0; + if (holding || path == NULL || path[0] != '/' || !enabled()) return 0; const char *s = strstr(path, "/steamapps"); return s && (s[10] == '/' || s[10] == 0); } static int on_fuse(dev_t dev, const char *path) { - pthread_mutex_lock(&lock); + take(&lock); for (int i = 0; i < ndevs; i++) { if (devs[i].dev == dev) { int fuse = devs[i].fuse; - pthread_mutex_unlock(&lock); + give(&lock); return fuse; } } - pthread_mutex_unlock(&lock); + give(&lock); struct statfs fs; int saved = errno; int fuse = statfs(path, &fs) == 0 && (unsigned long)fs.f_type == FUSE_MAGIC; errno = saved; - pthread_mutex_lock(&lock); + take(&lock); if (ndevs < 8) { devs[ndevs].dev = dev; devs[ndevs].fuse = fuse; ndevs++; } - pthread_mutex_unlock(&lock); + give(&lock); return fuse; } @@ -404,7 +417,7 @@ __attribute__((constructor)) static void resolve(void) { #pragma GCC diagnostic pop static DIR *hit(const struct stat *st, struct handle *h, long long now) { - pthread_mutex_lock(&lock); + take(&lock); if (!changing) pump(NULL, 0); int slot = find(st->st_dev, st->st_ino); if (slot >= 0 && same(table[slot], st) && now - table[slot]->filled < DIR_TTL_NS && records(table[slot]) == 0) { @@ -413,7 +426,7 @@ static DIR *hit(const struct stat *st, struct handle *h, long long now) { h->snap->used = now; DIR *d = wrap(h); if (d) { - pthread_mutex_unlock(&lock); + give(&lock); return d; } unref(h->snap); @@ -421,7 +434,7 @@ static DIR *hit(const struct stat *st, struct handle *h, long long now) { } else if (slot >= 0) { drop(slot); } - pthread_mutex_unlock(&lock); + give(&lock); return NULL; } @@ -462,11 +475,11 @@ static int above(struct handle *h, const char *path) { } static int track(struct handle *h, const char *path) { - pthread_mutex_lock(&lock); + take(&lock); h->wd = watch(path, WATCHED); DIR *d = h->wd >= 0 && above(h, path) ? wrap(h) : NULL; if (d == NULL) let_go(h->wd, h->up, h->nup); - pthread_mutex_unlock(&lock); + give(&lock); return d != NULL; } @@ -486,11 +499,11 @@ static void filling(struct handle *h, DIR *real, const struct stat *st, long lon } static void untrack(struct handle *h) { - pthread_mutex_lock(&lock); + take(&lock); int i = registered((DIR *)h); if (i >= 0) __atomic_store_n(&handles[i], NULL, __ATOMIC_RELEASE); let_go(h->wd, h->up, h->nup); - pthread_mutex_unlock(&lock); + give(&lock); } DIR *opendir(const char *path) { @@ -553,11 +566,11 @@ static void finish(struct handle *h) { h->fill = NULL; int current = stat(h->path, &st) == 0 && same(l, &st); if (current) l->folds = folds(h->path, &st); - pthread_mutex_lock(&lock); + take(&lock); if (!changing) pump(NULL, 0); if (current && !__atomic_load_n(&h->dirty, __ATOMIC_RELAXED)) install(l); else destroy(l); - pthread_mutex_unlock(&lock); + give(&lock); } static struct dirent64 *entry(struct handle *h) { @@ -624,7 +637,8 @@ int readdir_r(DIR *d, struct dirent *out, struct dirent **result) { int closedir(DIR *d) { NEXT(closedir); - pthread_mutex_lock(&lock); + if (holding && registered(d) < 0) return next_closedir(d); + take(&lock); int i = registered(d); struct handle *h = i >= 0 ? handles[i] : NULL; if (h) { @@ -632,7 +646,7 @@ int closedir(DIR *d) { if (h->snap) unref(h->snap); let_go(h->wd, h->up, h->nup); } - pthread_mutex_unlock(&lock); + give(&lock); if (h == NULL) return next_closedir(d); int r = 0; if (h->real) r = next_closedir(h->real); @@ -704,10 +718,10 @@ static int watching(const char *path) { } static void begin(void) { - pthread_mutex_lock(&lock); + take(&lock); pump(NULL, 0); changing = 1; - pthread_mutex_unlock(&lock); + give(&lock); } static void before(struct side *s) { @@ -796,10 +810,10 @@ static int patch(struct side *s, int what, uint32_t event, int ok, int error, co } static void end(struct expect *x, int nx) { - pthread_mutex_lock(&lock); + take(&lock); pump(x, nx); changing = 0; - pthread_mutex_unlock(&lock); + give(&lock); } int bl_dircache_create(int dirfd, const char *path, int flags, mode_t mode, @@ -809,17 +823,17 @@ int bl_dircache_create(int dirfd, const char *path, int flags, mode_t mode, struct side s; if (!(flags & O_CREAT) || (dirfd != AT_FDCWD && (path == NULL || path[0] != '/')) || !watching(path) || !split(path, &s)) return real(dirfd, path, flags, mode); - pthread_mutex_lock(&oplock); + take(&oplock); begin(); before(&s); int fd = real(dirfd, path, flags, mode); int saved = errno; struct expect x; - pthread_mutex_lock(&lock); + take(&lock); int nx = patch(&s, ADDED, IN_CREATE, fd >= 0, saved, path, &x); - pthread_mutex_unlock(&lock); + give(&lock); end(&x, nx); - pthread_mutex_unlock(&oplock); + give(&oplock); errno = saved; return fd; } @@ -829,26 +843,34 @@ int bl_dircache_create(int dirfd, const char *path, int flags, mode_t mode, NEXT(name); \ struct side s; \ if (!watching(path) || !split(path, &s)) return call; \ - pthread_mutex_lock(&oplock); \ + take(&oplock); \ begin(); \ before(&s); \ int r = call; \ int saved = errno; \ struct expect x; \ - pthread_mutex_lock(&lock); \ + take(&lock); \ int nx = patch(&s, what, event, r == 0, saved, what == ADDED ? path : NULL, &x); \ if (r == 0 && what == REMOVED) forget_below(path); \ - pthread_mutex_unlock(&lock); \ + give(&lock); \ end(&x, nx); \ - pthread_mutex_unlock(&oplock); \ + give(&oplock); \ errno = saved; \ return r; \ } ONE_PATH(mkdir, ADDED, IN_CREATE, next_mkdir(path, mode), mode_t mode) -ONE_PATH(rmdir, REMOVED, IN_DELETE, next_rmdir(path)) -ONE_PATH(unlink, REMOVED, IN_DELETE, next_unlink(path)) -ONE_PATH(remove, REMOVED, IN_DELETE, next_remove(path)) +int bl_descriptor_unlink(const char *path, int (*real)(const char *)) __attribute__((visibility("hidden"))); +int bl_descriptor_rmdir(const char *path, int (*real)(const char *)) __attribute__((visibility("hidden"))); +int bl_descriptor_remove(const char *path, int (*real)(const char *)) __attribute__((visibility("hidden"))); +int bl_descriptor_rename(const char *from, const char *to, int (*real)(const char *, const char *)) + __attribute__((visibility("hidden"))); + +static int moved(const char *from, const char *to) { return bl_descriptor_rename(from, to, next_rename); } + +ONE_PATH(rmdir, REMOVED, IN_DELETE, bl_descriptor_rmdir(path, next_rmdir)) +ONE_PATH(unlink, REMOVED, IN_DELETE, bl_descriptor_unlink(path, next_unlink)) +ONE_PATH(remove, REMOVED, IN_DELETE, bl_descriptor_remove(path, next_remove)) #define TWO_PATHS(name, gone, event, call) \ int name(const char *from, const char *to) { \ @@ -856,7 +878,7 @@ ONE_PATH(remove, REMOVED, IN_DELETE, next_remove(path)) struct side a, b; \ int track_a = gone && watching(from) && split(from, &a), track_b = watching(to) && split(to, &b); \ if (!track_a && !track_b) return call(from, to); \ - pthread_mutex_lock(&oplock); \ + take(&oplock); \ begin(); \ if (track_a) before(&a); \ if (track_b) before(&b); \ @@ -864,16 +886,16 @@ ONE_PATH(remove, REMOVED, IN_DELETE, next_remove(path)) int saved = errno; \ struct expect x[2]; \ int nx = 0; \ - pthread_mutex_lock(&lock); \ + take(&lock); \ if (track_a) nx += patch(&a, REMOVED, IN_MOVED_FROM, r == 0, saved, NULL, &x[nx]); \ if (track_b) { \ if (track_a && strcmp(a.dir, b.dir) == 0) b.known = stat(b.dir, &b.before) == 0; \ nx += patch(&b, ADDED, event, r == 0, saved, to, &x[nx]); \ } \ if (r == 0 && gone) { forget_below(from); forget_below(to); } \ - pthread_mutex_unlock(&lock); \ + give(&lock); \ end(x, nx); \ - pthread_mutex_unlock(&oplock); \ + give(&oplock); \ errno = saved; \ return r; \ } @@ -881,7 +903,7 @@ ONE_PATH(remove, REMOVED, IN_DELETE, next_remove(path)) int bl_link_lock(const char *oldpath, const char *newpath, int result) __attribute__((visibility("hidden"))); static int link_or_lock(const char *from, const char *to) { return bl_link_lock(from, to, next_link(from, to)); } -TWO_PATHS(rename, 1, IN_MOVED_TO, next_rename) +TWO_PATHS(rename, 1, IN_MOVED_TO, moved) TWO_PATHS(link, 0, IN_CREATE, link_or_lock) TWO_PATHS(symlink, 0, IN_CREATE, next_symlink) @@ -923,13 +945,13 @@ int bl_dircache_absent(const char *path) { for (const char *c = s.name; *c; c++) if ((unsigned char)*c >= 0x80) return 0; long long now = now_ns(); - pthread_mutex_lock(&lock); + take(&lock); int absent = 0; if (!changing) { pump(NULL, 0); absent = listed_absent(s.dir, s.name, now); } - pthread_mutex_unlock(&lock); + give(&lock); return absent; } diff --git a/tools/linuxfs/preload/owner.c b/tools/linuxfs/preload/owner.c index 78ada3bf00..1e493f8a80 100644 --- a/tools/linuxfs/preload/owner.c +++ b/tools/linuxfs/preload/owner.c @@ -12,7 +12,8 @@ #define FAT_MAGIC 0x4d44 #define EXFAT_MAGIC 0x2011bab0 -static int is_wineserver(void) { +__attribute__((visibility("hidden"))) +int bl_is_wineserver(void) { static int cached = -1; char exe[PATH_MAX]; const char *base; @@ -43,7 +44,7 @@ void bl_storage_owner(int fd, struct stat *st) { int saved = errno; uid_t uid; - if (st != NULL && is_wineserver()) { + if (st != NULL && bl_is_wineserver()) { uid = getuid(); if (st->st_uid != uid && has_no_unix_owner(fd)) st->st_uid = uid; } @@ -60,7 +61,7 @@ int fchmod(int fd, mode_t mode) { return -1; } result = next_fchmod(fd, mode); - if (result != 0 && errno == EPERM && is_wineserver()) { + if (result != 0 && errno == EPERM && bl_is_wineserver()) { if (has_no_unix_owner(fd)) { errno = saved; return 0; diff --git a/tools/linuxfs/preload/venus.c b/tools/linuxfs/preload/venus.c index 4feb9ee03a..aae9ebbec2 100644 --- a/tools/linuxfs/preload/venus.c +++ b/tools/linuxfs/preload/venus.c @@ -12,7 +12,14 @@ #include #include +extern char **environ; + __attribute__((constructor)) static void bl_venus_keep_kopper(void) { + static const char name[] = "LIBGL_KOPPER_DISABLE="; const char *debug = getenv("VN_DEBUG"); - if (debug && strstr(debug, "vtest")) unsetenv("LIBGL_KOPPER_DISABLE"); + if (!debug || !strstr(debug, "vtest") || !environ) return; + char **out = environ; + for (char **in = environ; *in; in++) + if (strncmp(*in, name, sizeof name - 1)) *out++ = *in; + *out = NULL; } diff --git a/tools/proot/PATCHES.md b/tools/proot/PATCHES.md index c4173a48c7..6347023473 100644 --- a/tools/proot/PATCHES.md +++ b/tools/proot/PATCHES.md @@ -162,9 +162,26 @@ Prototype (inert unless `PROOT_FASTPATH` is set; see `docs/development/proot-per `ENOSYS`, because its arguments are host paths; the fast path then stops for that process and repeats the call through a plain `svc`, which the guest's filter traps with the guest path. `bench/guest-trap.c` installs a tagged `openat` trap and checks its handler answers the call. + The kernel and filesystems also return `ENOSYS` themselves: Android's FUSE daemon has no + `symlink`, so `symlinkat` on a storage card fails with it. The fast path therefore asks again + with the same call number and invalid arguments. A trap answers `ENOSYS` again and the fast path + stops for the process; any other error means the call reached the kernel, so only that one call + is repeated through a plain `svc` and the fast path stays on. Old kernel fixes: +- `0028-fchdir-open-directory.patch` - `fchdir` resolved the directory again from its guest path, + one `lstat` per path component, then an `lstat` and an `O_PATH` open of the result. The + descriptor is already open, so `/proc//fd/` gives its host path and one `stat` through + that link confirms it is a live directory. The guest path it maps to is checked to map back to + the same host path, and the parent of the binding it falls under is checked to still resolve + to itself, so the cwd PRoot records is the one the old walk produced; a deleted directory, a + path outside the guest, a binding whose ancestor became a symlink, or anything else that does + not round-trip takes the old walk. Listing a directory in Wine does `fchdir` there and back: on a memory card behind + Android's FUSE daemon the old walk cost about 4 ms per call in the single tracer thread, 8.4 s + of an 8.8 s tracer total across one program start, and is now under 0.1 ms. + `bench/fchdir.py [directory...]` checks the cwd after `fchdir` to plain, bound, symlinked, + renamed and deleted directories and prints the per-call cost. - `0015-lost-fork-events.patch` - works around a problem reported on Xiaomi's msm 4.14 kernel: the kernel sometimes reports a new process or thread but gives its ID as zero. Without that ID, PRoot cannot finish setting it up, which can leave the session stuck. The patch searches `/proc` diff --git a/tools/proot/bench/fchdir.py b/tools/proot/bench/fchdir.py new file mode 100644 index 0000000000..e8d5c9141f --- /dev/null +++ b/tools/proot/bench/fchdir.py @@ -0,0 +1,105 @@ +import errno +import os +import sys +import tempfile +import time + + +def report(label, check): + try: + print(label, check()) + except OSError as error: + print(label, "ERR", errno.errorcode.get(error.errno, error.errno)) + + +def enter(path): + fd = os.open(path, os.O_RDONLY | os.O_DIRECTORY) + try: + os.fchdir(fd) + return os.getcwd(), os.readlink("/proc/self/cwd"), os.path.samefile(".", path) + finally: + os.close(fd) + + +def enter_file(base): + fd = os.open(base + "/real/file", os.O_RDONLY) + try: + os.fchdir(fd) + finally: + os.close(fd) + + +def enter_deleted(base): + os.mkdir(base + "/gone") + fd = os.open(base + "/gone", os.O_RDONLY) + os.rmdir(base + "/gone") + try: + os.fchdir(fd) + return "ok" + finally: + os.close(fd) + os.chdir("/") + + +def enter_renamed(base): + os.mkdir(base + "/before") + fd = os.open(base + "/before", os.O_RDONLY) + os.rename(base + "/before", base + "/after") + try: + os.fchdir(fd) + return os.getcwd() == base + "/after" + finally: + os.close(fd) + os.chdir("/") + os.rmdir(base + "/after") + + +def relative(base): + fd = os.open(base, os.O_RDONLY) + os.fchdir(fd) + os.close(fd) + seen = os.path.exists("real/file"), os.path.exists("link/file") + os.chdir("real") + inside = os.getcwd() == base + "/real" + os.chdir("..") + return seen + (inside, os.getcwd() == base) + + +def cost(path, rounds=300): + fd = os.open(path, os.O_RDONLY) + back = os.open("/", os.O_RDONLY) + start = time.perf_counter() + for _ in range(rounds): + os.fchdir(fd) + os.fchdir(back) + elapsed = time.perf_counter() - start + os.close(fd) + os.close(back) + return round(elapsed / rounds / 2 * 1e6, 1) + + +def main(): + extra = sys.argv[1:] + base = tempfile.mkdtemp(prefix="fchdir-") + os.mkdir(base + "/real") + os.symlink(base + "/real", base + "/link") + os.mkdir(base + "/dot.") + open(base + "/real/file", "w").close() + for path in ["/", "/tmp", "/usr/lib", "/proc/self", "/dev", base + "/real", base + "/link", base + "/dot."] + extra: + report(path, lambda: enter(path)) + report("file", lambda: enter_file(base)) + report("deleted", lambda: enter_deleted(base)) + report("renamed", lambda: enter_renamed(base)) + report("badfd", lambda: os.fchdir(987)) + report("relative", lambda: relative(base)) + os.chdir("/") + for path in ["/usr/lib"] + extra: + print("fchdir_us", path, cost(path)) + os.unlink(base + "/real/file") + os.unlink(base + "/link") + os.rmdir(base + "/dot.") + os.rmdir(base + "/real") + os.rmdir(base) + + +main() diff --git a/tools/proot/fastpath/fastpath.c b/tools/proot/fastpath/fastpath.c index 8d645eddd2..bcc745852a 100644 --- a/tools/proot/fastpath/fastpath.c +++ b/tools/proot/fastpath/fastpath.c @@ -41,7 +41,7 @@ typedef long (*stub_fn)(long nr, long a, long b, long c, long d, long e, long f) static stub_fn fp_sys; static int fp_on; -struct bind { char *host; size_t hlen; char *guest; size_t glen; int canon; int dropped; }; +struct bind { char *host; size_t hlen; char *guest; size_t glen; int canon; int dropped; int fuse; }; static struct bind binds[MAX_BINDS]; static int nbinds; static char root[PATH_MAX]; @@ -59,10 +59,10 @@ static int optional_syscall(long nr) { nr == SYS_openat2 || nr == SYS_renameat2; } static long sc(long nr, long a, long b, long c, long d, long e) { - if (fp_refused) return -ENOSYS; + if (fp_refused && nr != SYS_close) return -ENOSYS; long r = fp_sys(nr, a, b, c, d, e, 0); if (r == -ENOSYS && !optional_syscall(nr)) { - __atomic_store_n(&fp_on, 0, __ATOMIC_RELAXED); + if (fp_sys(nr, -1, -1, -1, -1, -1, 0) == -ENOSYS) __atomic_store_n(&fp_on, 0, __ATOMIC_RELAXED); fp_refused = 1; } return r; @@ -133,7 +133,8 @@ static long tracer; static pthread_mutex_t cache_lock = PTHREAD_MUTEX_INITIALIZER; static pthread_mutex_t bind_lock; static pthread_mutex_t long_lock; -static void after_fork(void) { pthread_mutex_init(&cache_lock, NULL); pthread_mutex_init(&bind_lock, NULL); pthread_mutex_init(&long_lock, NULL); } +static pthread_mutex_t dir_lock = PTHREAD_MUTEX_INITIALIZER; +static void after_fork(void) { pthread_mutex_init(&cache_lock, NULL); pthread_mutex_init(&bind_lock, NULL); pthread_mutex_init(&long_lock, NULL); pthread_mutex_init(&dir_lock, NULL); } static int traced_by_match(const char *key) { static char buf[32768]; @@ -414,6 +415,212 @@ static int host_bind(const char *h) { return -1; } +static unsigned hash_of(const char *s); +static long long now_ns(void); +#define DIRS 64 +#define DIR_FD_FLOOR 1000 +struct dirslot { unsigned hash, epoch; int fd, refs; dev_t dev; ino_t ino; long tag; long long stamp; char path[PATH_MAX]; char seen[PATH_MAX]; }; +static struct dirslot dirs[DIRS]; +static unsigned dir_epoch; +struct near { long fd; int slot, own; const char *name; }; + +static int fuse_bind(const char *h) { + int i = host_bind(h); + if (i < 0) return -1; + int f = __atomic_load_n(&binds[i].fuse, __ATOMIC_ACQUIRE); + if (!f) { + struct statfs fs; + f = sc(SYS_statfs, (long)binds[i].host, (long)&fs, 0, 0, 0) == 0 && fs.f_type == 0x65735546 ? 1 : 2; + __atomic_store_n(&binds[i].fuse, f, __ATOMIC_RELEASE); + } + return f == 1 ? i : -1; +} + +static long fd_path(long fd, char *out) { + char link[40]; + snprintf(link, sizeof link, "/proc/self/fd/%ld", fd); + long n = sc(SYS_readlinkat, AT_FDCWD, (long)link, (long)out, PATH_MAX - 1, 0); + if (n <= 0 || n >= PATH_MAX - 1) return -1; + out[n] = 0; + return 0; +} + +static int fd_id(long fd, dev_t *dev, ino_t *ino) { + struct stat st; + if (sc(SYS_newfstatat, fd, (long)"", (long)&st, AT_EMPTY_PATH, 0) != 0) return -1; + *dev = st.st_dev; + *ino = st.st_ino; + return 0; +} + +static long dir_tag(void) { + static uint64_t state; + uint64_t z = __atomic_add_fetch(&state, 0x9e3779b97f4a7c15ULL, __ATOMIC_RELAXED), seed = 0; + const void *random = (const void *)getauxval(AT_RANDOM); + if (random) memcpy(&seed, random, sizeof seed); + z += seed; + z = (z ^ (z >> 30)) * 0xbf58476d1ce4e5b9ULL; + z = (z ^ (z >> 27)) * 0x94d049bb133111ebULL; + return (long)((z ^ (z >> 31)) & 0xffffffffffULL) + 1; +} + +static int dir_owned(const struct dirslot *e) { + dev_t dev; + ino_t ino; + return e->fd > 0 && sc(SYS_lseek, e->fd, 0, SEEK_CUR, 0, 0) == e->tag + && fd_id(e->fd, &dev, &ino) == 0 && dev == e->dev && ino == e->ino; +} + +static int dir_fresh(struct dirslot *e, const char *dir) { + long long t = now_ns(); + if (t - __atomic_load_n(&e->stamp, __ATOMIC_RELAXED) < ttl_ns) return 1; + struct stat st; + if (sc(SYS_newfstatat, AT_FDCWD, (long)dir, (long)&st, 0, 0) != 0 || st.st_dev != e->dev || st.st_ino != e->ino) { + __atomic_add_fetch(&dir_epoch, 1, __ATOMIC_RELEASE); + return 0; + } + __atomic_store_n(&e->stamp, t, __ATOMIC_RELAXED); + return 1; +} + +static void dirs_drop(const char *host) { + size_t len = strlen(host); + if (pthread_mutex_trylock(&dir_lock) != 0) { + __atomic_add_fetch(&dir_epoch, 1, __ATOMIC_RELEASE); + return; + } + for (int i = 0; i < DIRS; i++) + if (dirs[i].path[0] && under(dirs[i].path, host, len)) dirs[i].path[0] = 0; + pthread_mutex_unlock(&dir_lock); +} + +static void near_put(struct near *n) { + if (n->own) sc(SYS_close, n->fd, 0, 0, 0, 0); + else if (n->slot >= 0) __atomic_sub_fetch(&dirs[n->slot].refs, 1, __ATOMIC_RELEASE); + n->fd = AT_FDCWD; + n->slot = -1; + n->own = 0; +} + +static int dir_cached(const char *dir, struct near *n) { + unsigned h = hash_of(dir); + struct dirslot *e = &dirs[h % DIRS]; + if (pthread_mutex_trylock(&dir_lock) != 0) return 0; + int hit = e->fd >= 0 && e->hash == h && e->path[0] && strcmp(e->path, dir) == 0 + && e->epoch == __atomic_load_n(&dir_epoch, __ATOMIC_ACQUIRE); + if (hit) __atomic_add_fetch(&e->refs, 1, __ATOMIC_ACQUIRE); + pthread_mutex_unlock(&dir_lock); + if (!hit) return 0; + char now[PATH_MAX]; + if (fd_path(e->fd, now) == 0 && strcmp(now, e->seen) == 0 && dir_fresh(e, dir)) { + n->fd = e->fd; + n->slot = (int)(e - dirs); + n->own = 0; + return 1; + } + __atomic_sub_fetch(&e->refs, 1, __ATOMIC_RELEASE); + if (pthread_mutex_trylock(&dir_lock) == 0) { + if (e->hash == h && strcmp(e->path, dir) == 0) e->path[0] = 0; + pthread_mutex_unlock(&dir_lock); + } + return 0; +} + +static int dir_keep(const char *dir, long fd, struct near *n) { + long high = sc(SYS_fcntl, fd, F_DUPFD_CLOEXEC, DIR_FD_FLOOR, 0, 0); + sc(SYS_close, fd, 0, 0, 0, 0); + if (high < 0) return -1; + n->fd = high; + n->slot = -1; + n->own = 1; + char seen[PATH_MAX]; + dev_t dev; + ino_t ino; + long tag = dir_tag(); + struct stat st; + if (fd_id(high, &dev, &ino) < 0 || strlen(dir) >= PATH_MAX + || sc(SYS_newfstatat, AT_FDCWD, (long)dir, (long)&st, 0, 0) != 0 || st.st_dev != dev || st.st_ino != ino) { + near_put(n); + return -1; + } + if (fd_path(high, seen) < 0 || sc(SYS_lseek, high, tag, SEEK_SET, 0, 0) != tag) return 0; + unsigned h = hash_of(dir); + struct dirslot *e = &dirs[h % DIRS]; + if (pthread_mutex_trylock(&dir_lock) != 0) return 0; + if (__atomic_load_n(&e->refs, __ATOMIC_ACQUIRE) == 0) { + if (dir_owned(e)) sc(SYS_close, e->fd, 0, 0, 0, 0); + e->hash = h; + e->epoch = __atomic_load_n(&dir_epoch, __ATOMIC_ACQUIRE); + e->tag = tag; + e->stamp = now_ns(); + e->fd = (int)high; + e->dev = dev; + e->ino = ino; + e->refs = 1; + strcpy(e->path, dir); + strcpy(e->seen, seen); + n->slot = (int)(e - dirs); + n->own = 0; + } + pthread_mutex_unlock(&dir_lock); + return 0; +} + +static int dir_get(char *dir, size_t floor, struct near *n) { + size_t len = strlen(dir), at = len; + while (!dir_cached(dir, n)) { + if (at <= floor) { + long fd = sc(SYS_openat, AT_FDCWD, (long)dir, O_RDONLY | O_DIRECTORY | O_CLOEXEC, 0, 0); + if (fd < 0 || dir_keep(dir, fd, n) < 0) return -1; + break; + } + char *slash = strrchr(dir, '/'); + if (!slash || (size_t)(slash - dir) < floor) return -1; + *slash = 0; + at = slash - dir; + } + while (at < len) { + dir[at] = '/'; + const char *name = dir + at + 1; + size_t next = at + 1 + strlen(name); + long fd = sc(SYS_openat, n->fd, (long)name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC, 0, 0); + near_put(n); + if (fd < 0 || dir_keep(dir, fd, n) < 0) return -1; + at = next; + } + return 0; +} + +static long near_get(const char *host, struct near *n) { + n->fd = AT_FDCWD; + n->slot = -1; + n->own = 0; + n->name = host; + if (ttl_ns <= 0 || host[0] != '/') return n->fd; + int i = fuse_bind(host); + if (i < 0) return n->fd; + const char *slash = strrchr(host, '/'); + size_t plen = slash - host; + if (plen < binds[i].hlen || !slash[1] || plen >= PATH_MAX) return n->fd; + char dir[PATH_MAX]; + memcpy(dir, host, plen); + dir[plen] = 0; + if (dir_get(dir, binds[i].hlen, n) < 0) { + near_put(n); + return n->fd; + } + n->name = slash + 1; + return n->fd; +} + +static long hsc(long nr, const char *host, long a, long b, long c) { + struct near n; + long fd = near_get(host, &n); + long rs = sc(nr, fd, (long)n.name, a, b, c); + near_put(&n); + return rs; +} + static int guest_text(const char *h, char *g) { if (h[0] == '/' && under(h, root, rootlen)) return to_guest(h, g, PATH_MAX); int i = h[0] == '/' ? host_bind(h) : -1; @@ -556,7 +763,7 @@ static long proc_readlink(const struct res *r, char *text, size_t size, int *cha return name[0] == 'e' ? own_exe(text) : own_cwd(text); } char h[PATH_MAX]; - long t = sc(SYS_readlinkat, AT_FDCWD, (long)r->host, (long)h, sizeof h - 1, 0); + long t = hsc(SYS_readlinkat, r->host, (long)h, sizeof h - 1, 0); if (t < 0) return t; if (t >= (long)sizeof h - 1) return FP_SLOW; if (size && (size_t)t > size) t = size; @@ -579,7 +786,7 @@ static long proc_link(struct res *r, char *text, int final) { if (!under(r->host, "/proc", 5)) return FP_SLOW; r->moving = 1; if (!strcmp(r->guest, "/proc/self") || !strcmp(r->guest, "/proc/thread-self")) { - long t = sc(SYS_readlinkat, AT_FDCWD, (long)r->host, (long)text, PATH_MAX - 1, 0); + long t = hsc(SYS_readlinkat, r->host, (long)text, PATH_MAX - 1, 0); if (t <= 0 || t >= PATH_MAX - 1) return FP_SLOW; text[t] = 0; return t; @@ -628,7 +835,7 @@ static long walk(struct res *r, const char *text, int follow, int last) { if (reserved(r->guest)) return FP_SLOW; struct bind *through; if (to_host(r->guest, r->host, &through) < 0) return FP_SLOW; - long s = sc(SYS_newfstatat, AT_FDCWD, (long)r->host, (long)&r->st, AT_SYMLINK_NOFOLLOW, 0); + long s = hsc(SYS_newfstatat, r->host, (long)&r->st, AT_SYMLINK_NOFOLLOW, 0); if (s < 0) { int glue = glue_above_binding(r->guest, glen + n); if (glue < 0) return FP_SLOW; @@ -648,13 +855,13 @@ static long walk(struct res *r, const char *text, int follow, int last) { t = proc_link(r, target, final && last); if (t == FP_SLOW) return FP_SLOW; if (t == 0) { - if (sc(SYS_newfstatat, AT_FDCWD, (long)r->host, (long)&r->st, 0, 0) < 0) return FP_SLOW; + if (hsc(SYS_newfstatat, r->host, (long)&r->st, 0, 0) < 0) return FP_SLOW; r->magic = 1; r->exists = 1; return 0; } } else { - t = sc(SYS_readlinkat, AT_FDCWD, (long)r->host, (long)target, sizeof target - 1, 0); + t = hsc(SYS_readlinkat, r->host, (long)target, sizeof target - 1, 0); if (t <= 0 || t >= (long)sizeof target - 1) return FP_SLOW; target[t] = 0; if (detranslated(target, r->host) == FP_SLOW) return FP_SLOW; @@ -676,7 +883,7 @@ static long walk(struct res *r, const char *text, int follow, int last) { } if (!stated) { if (to_host(r->guest, r->host, NULL) < 0) return FP_SLOW; - long s = sc(SYS_newfstatat, AT_FDCWD, (long)r->host, (long)&r->st, AT_SYMLINK_NOFOLLOW, 0); + long s = hsc(SYS_newfstatat, r->host, (long)&r->st, AT_SYMLINK_NOFOLLOW, 0); if (s < 0 && strcmp(r->guest, "/") != 0 && glue_above_binding(r->guest, strlen(r->guest))) return FP_SLOW; if (s < 0) return s == -ENOENT ? FP_SLOW : s; } @@ -699,7 +906,7 @@ static long bound_literal(const char *literal, struct res *r) { struct bind *bd; if (reserved(literal) || bind_of(literal, &bd) < 0 || !bd || bd->glen != strlen(literal) || bd->glen < 2) return FP_SLOW; if (snprintf(r->host, PATH_MAX, "%s", bd->host) >= PATH_MAX) return FP_SLOW; - if (sc(SYS_newfstatat, AT_FDCWD, (long)r->host, (long)&r->st, AT_SYMLINK_NOFOLLOW, 0) < 0 || S_ISLNK(r->st.st_mode)) return FP_SLOW; + if (hsc(SYS_newfstatat, r->host, (long)&r->st, AT_SYMLINK_NOFOLLOW, 0) < 0 || S_ISLNK(r->st.st_mode)) return FP_SLOW; snprintf(r->guest, PATH_MAX, "%s", literal); r->exists = 1; r->moving = 0; @@ -822,8 +1029,8 @@ static long fp_open(int dirfd, const char *path, int flags, mode_t mode) { long rs = resolve(dirfd, path, follow | MAY_BE_UNSEEN, &r); if (rs < 0) return rs; if (rs == 1 && !(flags & O_CREAT)) return -ENOENT; - if (rs == UNSEEN) return sc(SYS_openat, AT_FDCWD, (long)r.host, flags, (flags & O_CREAT) ? mode : 0, 0); - return sc(SYS_openat, AT_FDCWD, (long)r.host, flags | (follow && !r.magic ? O_NOFOLLOW : 0), (flags & O_CREAT) ? mode : 0, 0); + if (rs == UNSEEN) return hsc(SYS_openat, r.host, flags, (flags & O_CREAT) ? mode : 0, 0); + return hsc(SYS_openat, r.host, flags | (follow && !r.magic ? O_NOFOLLOW : 0), (flags & O_CREAT) ? mode : 0, 0); } static int do_openat(int dirfd, const char *path, int flags, mode_t mode, int (*real)(int, const char *, int, ...)) { @@ -864,7 +1071,7 @@ static long fp_stat(int dirfd, const char *path, int flags, struct stat *st) { long rs = resolve(dirfd, path, (flags & AT_SYMLINK_NOFOLLOW ? 0 : 1) | MAY_BE_UNSEEN, &r); if (rs < 0) return rs; if (rs == 1) return -ENOENT; - if (rs == UNSEEN) return sc(SYS_newfstatat, AT_FDCWD, (long)r.host, (long)st, flags, 0); + if (rs == UNSEEN) return hsc(SYS_newfstatat, r.host, (long)st, flags, 0); *st = r.st; return 0; } @@ -1007,7 +1214,7 @@ static long fp_access(int dirfd, const char *path, int mode, int flags) { ? resolve(dirfd, path, (flags & AT_SYMLINK_NOFOLLOW ? 0 : 1) | MAY_BE_UNSEEN, &r) : FP_SLOW; if (rs == 1) rs = -ENOENT; if (rs == 0 && S_ISLNK(r.st.st_mode)) rs = FP_SLOW; - if (rs == 0 || rs == UNSEEN) rs = sc(SYS_faccessat, AT_FDCWD, (long)r.host, mode, 0, 0); + if (rs == 0 || rs == UNSEEN) rs = hsc(SYS_faccessat, r.host, mode, 0, 0); return rs; } @@ -1030,7 +1237,7 @@ static long link_text(const struct res *r, char *text, size_t size, int *changed *changed = 0; if (in_proc != under(r->host, "/proc", 5)) return FP_SLOW; if (in_proc) return proc_readlink(r, text, size, changed); - long t = sc(SYS_readlinkat, AT_FDCWD, (long)r->host, (long)text, PATH_MAX - 1, 0); + long t = hsc(SYS_readlinkat, r->host, (long)text, PATH_MAX - 1, 0); if (t < 0) return t; if (t >= PATH_MAX - 1) return FP_SLOW; if (size && (size_t)t > size) t = size; @@ -1135,7 +1342,7 @@ char *__getcwd_chk(char *buf, size_t size, size_t room) { static long fp_mkdir(int dirfd, const char *path, mode_t mode) { struct res r; long rs = resolve(dirfd, path, MAY_BE_UNSEEN, &r); - if (rs == 0 || rs == 1 || rs == UNSEEN) rs = sc(SYS_mkdirat, AT_FDCWD, (long)r.host, mode, 0, 0); + if (rs == 0 || rs == 1 || rs == UNSEEN) rs = hsc(SYS_mkdirat, r.host, mode, 0, 0); return rs; } int mkdirat(int dirfd, const char *path, mode_t mode) { @@ -1172,7 +1379,7 @@ static long fp_unlink(int dirfd, const char *path, int flags) { if (rs == 0 && (flags & AT_REMOVEDIR) && strcmp(r.guest, "/") == 0) rs = FP_SLOW; if (rs == 0 || rs == UNSEEN) { int changes_paths = (flags & AT_REMOVEDIR) || rs == UNSEEN || S_ISLNK(r.st.st_mode); - rs = sc(SYS_unlinkat, AT_FDCWD, (long)r.host, flags, 0, 0); + rs = hsc(SYS_unlinkat, r.host, flags, 0, 0); if (rs == 0 && changes_paths) forget(); } return rs; @@ -1196,9 +1403,14 @@ static long fp_rename(int olddirfd, const char *old, int newdirfd, const char *n if (rt < 0) rs = rt; else if (rt == 0 && S_ISDIR(to.st.st_mode)) rs = FP_SLOW; else { - rs = flags ? sc(SYS_renameat2, AT_FDCWD, (long)from.host, AT_FDCWD, (long)to.host, flags) - : sc(SYS_renameat, AT_FDCWD, (long)from.host, AT_FDCWD, (long)to.host, 0); - if (rs == 0) forget(); + struct near a, b; + near_get(from.host, &a); + near_get(to.host, &b); + rs = flags ? sc(SYS_renameat2, a.fd, (long)a.name, b.fd, (long)b.name, flags) + : sc(SYS_renameat, a.fd, (long)a.name, b.fd, (long)b.name, 0); + near_put(&a); + near_put(&b); + if (rs == 0 && (S_ISLNK(from.st.st_mode) || (rt == 0 && S_ISLNK(to.st.st_mode)))) forget(); } } return rs; @@ -1236,7 +1448,10 @@ static long fp_chmod(int dirfd, const char *path, mode_t mode, int flags) { struct res r; long rs = flags ? FP_SLOW : resolve(dirfd, path, 1 | MAY_BE_UNSEEN, &r); if (rs == 1) rs = -ENOENT; - if (rs == 0 || rs == UNSEEN) rs = sc(SYS_fchmodat, AT_FDCWD, (long)r.host, mode, 0, 0); + if (rs == 0 || rs == UNSEEN) { + rs = hsc(SYS_fchmodat, r.host, mode, 0, 0); + if (rs == 0) dirs_drop(r.host); + } return rs; } int fchmodat(int dirfd, const char *path, mode_t mode, int flags) { @@ -1249,7 +1464,10 @@ static long fp_chown(int dirfd, const char *path, uid_t uid, gid_t gid, int flag struct res r; long rs = flags & ~AT_SYMLINK_NOFOLLOW ? FP_SLOW : resolve(dirfd, path, (flags & AT_SYMLINK_NOFOLLOW ? 0 : 1) | MAY_BE_UNSEEN, &r); if (rs == 1) rs = -ENOENT; - if (rs == 0 || rs == UNSEEN) rs = sc(SYS_fchownat, AT_FDCWD, (long)r.host, (long)uid, (long)gid, flags); + if (rs == 0 || rs == UNSEEN) { + rs = hsc(SYS_fchownat, r.host, (long)uid, (long)gid, flags); + if (rs == 0) dirs_drop(r.host); + } return rs; } int fchownat(int dirfd, const char *path, uid_t uid, gid_t gid, int flags) { @@ -1267,7 +1485,7 @@ static long fp_utimens(int dirfd, const char *path, const struct timespec times[ } else { rs = flags & ~AT_SYMLINK_NOFOLLOW ? FP_SLOW : resolve(dirfd, path, (flags & AT_SYMLINK_NOFOLLOW ? 0 : 1) | MAY_BE_UNSEEN, &r); if (rs == 1) rs = -ENOENT; - if (rs == 0 || rs == UNSEEN) rs = sc(SYS_utimensat, AT_FDCWD, (long)r.host, (long)times, flags, 0); + if (rs == 0 || rs == UNSEEN) rs = hsc(SYS_utimensat, r.host, (long)times, flags, 0); } return rs; } @@ -1509,7 +1727,7 @@ static long socket_address(const struct sockaddr *addr, socklen_t len, int follo char *slash = strrchr(r.host, '/'); if (!slash || slash == r.host) return FP_SLOW; *slash = 0; - *dir = sc(SYS_openat, AT_FDCWD, (long)r.host, O_PATH | O_DIRECTORY | O_CLOEXEC, 0, 0); + *dir = hsc(SYS_openat, r.host, O_PATH | O_DIRECTORY | O_CLOEXEC, 0, 0); if (*dir < 0) return FP_SLOW; hlen = snprintf(out->sun_path, room, "/proc/self/fd/%ld/%s", *dir, slash + 1); if (hlen >= room) { sc(SYS_close, *dir, 0, 0, 0, 0); *dir = -1; return FP_SLOW; } diff --git a/tools/proot/patches/0028-fchdir-open-directory.patch b/tools/proot/patches/0028-fchdir-open-directory.patch new file mode 100644 index 0000000000..8e1a494386 --- /dev/null +++ b/tools/proot/patches/0028-fchdir-open-directory.patch @@ -0,0 +1,108 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: maxjivi05 +Date: Thu, 12 Nov 2026 22:00:00 -0500 +Subject: [PATCH] fchdir: take the path of the open directory instead of resolving + it again component by component + +--- +--- a/src/syscall/enter.c ++++ b/src/syscall/enter.c +@@ -46,8 +46,66 @@ + #include "tracee/abi.h" + #include "path/path.h" + #include "path/canon.h" ++#include "path/binding.h" + #include "arch.h" + ++static int translate_open_directory(Tracee *tracee, char path[PATH_MAX], int fd, struct stat *statl) ++{ ++ char guest[PATH_MAX]; ++ char mount[PATH_MAX]; ++ char parent[PATH_MAX]; ++ char link[32]; ++ char *slash; ++ const Binding *binding; ++ size_t length; ++ int status; ++ ++ status = readlink_proc_pid_fd(tracee->pid, fd, path); ++ if (status < 0 || path[0] != '/') ++ return 1; ++ ++ strcpy(guest, path); ++ status = detranslate_path(tracee, guest, NULL); ++ if (status < 0) ++ return 1; ++ ++ binding = get_binding(tracee, GUEST, guest); ++ if (binding == NULL) ++ return 1; ++ ++ strcpy(parent, binding->guest.path); ++ slash = strrchr(parent, '/'); ++ if (slash != NULL && slash != parent) { ++ if ((size_t) (slash - parent) + 3 > PATH_MAX) ++ return 1; ++ ++ strcpy(slash, "/."); ++ strcpy(mount, "/"); ++ status = canonicalize(tracee, parent, true, mount, 0); ++ if (status < 0 || strcmp(mount, parent) != 0) ++ return 1; ++ } ++ ++ status = substitute_binding(tracee, GUEST, guest); ++ if (status < 0 || strcmp(guest, path) != 0) ++ return 1; ++ ++ status = snprintf(link, sizeof(link), "/proc/%d/fd/%d", tracee->pid, fd); ++ if (status < 0 || (size_t) status >= sizeof(link)) ++ return 1; ++ ++ status = stat(link, statl); ++ if (status < 0 || !S_ISDIR(statl->st_mode) || statl->st_nlink == 0) ++ return 1; ++ ++ length = strlen(path); ++ if (length + 2 >= PATH_MAX) ++ return 1; ++ ++ strcpy(path + (length == 1 ? 0 : length), "/."); ++ return 0; ++} ++ + /** + * Translate @path and put the result in the @tracee's memory address + * space pointed to by the @reg argument of the current syscall. See +@@ -193,13 +251,16 @@ + dirfd = peek_reg(tracee, CURRENT, SYSARG_1); + } + +- status = translate_path(tracee, path, dirfd, oldpath, true); +- if (status < 0) +- break; ++ if (syscall_number == PR_chdir ++ || translate_open_directory(tracee, path, dirfd, &statl) != 0) { ++ status = translate_path(tracee, path, dirfd, oldpath, true); ++ if (status < 0) ++ break; + +- status = lstat(path, &statl); +- if (status < 0) +- break; ++ status = lstat(path, &statl); ++ if (status < 0) ++ break; ++ } + + /* Check this directory is accessible. */ + if ((statl.st_mode & S_IXUSR) == 0) +@@ -208,7 +269,7 @@ + + + +- if (getenv("PROOT_FASTPATH") != NULL) { ++ if (syscall_number == PR_chdir && getenv("PROOT_FASTPATH") != NULL) { + int fd = open(path, O_PATH | O_DIRECTORY | O_CLOEXEC); + + diff --git a/tools/release/runtime_inputs.py b/tools/release/runtime_inputs.py index 57fe792465..12ac22eabb 100644 --- a/tools/release/runtime_inputs.py +++ b/tools/release/runtime_inputs.py @@ -23,11 +23,11 @@ PACK_NAMES = ['proot', 'directaudio', 'tracking', 'xbox', 'comet', 'butler', 'po SOURCE_PATHS = ['app/build.gradle', 'app/src/main/cpp/fakeinput_steam.cpp', 'app/src/main/assets/pulseaudio.tzst', 'tools/linuxfs', 'tools/proot', 'tools/aaudio-sink', 'tools/directaudio', 'tools/packs', 'tools/gamescope/release.env', 'tools/droiddeck-esync/release.env', - 'tools/mangoapp', 'tools/msitools', 'tools/pipewire', 'tools/comet', 'tools/xbox', 'tools/dirt-ws2', 'tools/ubisoft-launcher', 'tools/components', 'tools/ci', 'tools/build_local.sh', + 'tools/mangoapp', 'tools/msitools', 'tools/pipewire', 'tools/comet', 'tools/xbox', 'tools/dirt-ws2', 'tools/ubisoft-launcher', 'tools/rockstar-launcher', 'tools/components', 'tools/ci', 'tools/build_local.sh', 'tools/powervr', 'tools/hybris', 'tools/dxvk', 'tools/vulkan-wsi', 'tools/release/runtime_inputs.py', 'app/src/main/assets/desktop-removal', 'tools/quest', 'tools/vr/src', 'tools/vr/driver_droiddeck', 'tools/vr/layer', 'tools/vr/build.sh', - 'tools/gpuload', + 'tools/gpuload', 'app/src/main/resources/rockstar/legacy-cipher.bin', 'app/src/main/cpp/waylandcomp/src/headpose_shm.h', 'app/src/main/cpp/venc/venc_proto.h', 'app/src/main/cpp/waylandcomp/src/spatialpose_shm.h', diff --git a/tools/rockstar-launcher/.gitignore b/tools/rockstar-launcher/.gitignore new file mode 100644 index 0000000000..b83d22266a --- /dev/null +++ b/tools/rockstar-launcher/.gitignore @@ -0,0 +1 @@ +/target/ diff --git a/tools/rockstar-launcher/Cargo.lock b/tools/rockstar-launcher/Cargo.lock new file mode 100644 index 0000000000..f73866571d --- /dev/null +++ b/tools/rockstar-launcher/Cargo.lock @@ -0,0 +1,105 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "droiddeck-rockstar-launcher" +version = "0.1.0" +dependencies = [ + "serde_json", +] + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "syn" +version = "3.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8593e8e72159ed2257d083c7a454a85cbf854f37a0966d8d483aff8c8a3ebcee" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "unicode-ident" +version = "1.0.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954" + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/tools/rockstar-launcher/Cargo.toml b/tools/rockstar-launcher/Cargo.toml new file mode 100644 index 0000000000..4b5ec1f37b --- /dev/null +++ b/tools/rockstar-launcher/Cargo.toml @@ -0,0 +1,19 @@ +[package] +name = "droiddeck-rockstar-launcher" +version = "0.1.0" +edition = "2021" +license = "GPL-3.0-only" +publish = false + +[[bin]] +name = "Launcher" +path = "src/main.rs" + +[dependencies] +serde_json = "1" + +[profile.release] +opt-level = "s" +lto = true +panic = "abort" +strip = true diff --git a/tools/rockstar-launcher/README.md b/tools/rockstar-launcher/README.md new file mode 100644 index 0000000000..2965084713 --- /dev/null +++ b/tools/rockstar-launcher/README.md @@ -0,0 +1,36 @@ +# Rockstar launcher service + +`Launcher.exe` starts the selected installed game and serves its launcher pipes. The Android app obtains title authorization from Rockstar. Refresh credentials stay in Android Keystore-backed storage. + +The handoff is mode 0600, expires after 90 seconds and is deleted before starting the game. Legacy launches carry server-issued launch material. SDK launches also carry a short-lived ROS ticket and account identity; those values are kept in memory after the handoff is consumed and are not logged. Pipes reject remote clients and check the client process against the launched child. No game files are patched. + +GTA III, Vice City and San Andreas use body-length MTLX replies. GTA IV and L.A. Noire use total-length, terminated replies. Titles with installed Social Club metadata or SDK binaries use the SDK IPC adapter, including user-info, login, ticket, initialization and authorized title-state synchronization. The title metadata supplies the ROS identity and principal executable; it is checked against Rockstar's catalog before title authorization. Other titles retain Play and Steam shortcuts and attempt the normal executable launch path. + +The SDK runtime is extracted from the game's own Social-Club-Setup.exe when present. Architecture-specific payloads are staged into the prefix, archive paths and sizes are checked, interrupted copies are retried, and both registry views are registered. The helper discovers launcher identity pipe names in the game executable and answers bounded INIT challenges from the launched process. No vendor executables or runtime files are bundled with this tool. SDK initialization has a 90-second deadline. SDK wire tests and fixture clients do not establish gameplay compatibility for every title; per-title ROS ticket exchange and secondary SDK channels remain unverified. + +GTA III defaults to full x87 precision for FEX before Wine starts, because reduced precision crashed new-game initialization on the test device. San Andreas defaults to WineD3D, because DXVK intermittently corrupted its textures; full precision and conservative memory ordering did not prevent that corruption. These defaults use DroidDeck's per-game settings and preserve explicit per-game overrides. + +Raw launcher identity requests use `INIT::` with a terminating colon. Framed requests carry their payload length. The reply echoes the complete challenge after `TINI:launcher:`; partial reads do not complete a raw request. + +`build.sh` builds 32-bit and 64-bit executables with the GNU Windows targets and stages them as APK resources. `legacy-cipher.bin` contains the fixed client protocol tables, not account credentials or APK signing keys. + +Run the protocol tests with: + +```sh +cargo test --locked --manifest-path tools/rockstar-launcher/Cargo.toml +``` + +The optional `capture` example records a first-party launcher reply to a new local file. Run it on Windows or Wine while launching the corresponding game in Rockstar's launcher: + +```powershell +cargo run --release --example capture --manifest-path tools/rockstar-launcher/Cargo.toml -- --pipe GTA-VC_Pipe --output 'C:\captures\reply.bin' +``` + +On Linux, cross-compile the example and run it in the same Wine prefix as Rockstar's launcher: + +```sh +cargo build --release --locked --example capture --target x86_64-pc-windows-gnu --manifest-path tools/rockstar-launcher/Cargo.toml +WINEPREFIX=/path/to/launcher-prefix wine tools/rockstar-launcher/target/x86_64-pc-windows-gnu/release/examples/capture.exe --pipe GTA-VC_Pipe --output 'Z:\tmp\reply.bin' +``` + +Captures contain live launch material. Keep them outside source control; the tool prints only the message tag and payload length. diff --git a/tools/rockstar-launcher/build.sh b/tools/rockstar-launcher/build.sh new file mode 100644 index 0000000000..1f7360f741 --- /dev/null +++ b/tools/rockstar-launcher/build.sh @@ -0,0 +1,12 @@ +#!/usr/bin/env bash +set -euo pipefail +here=$(cd "$(dirname "$0")" && pwd) +out=${1:-"$here/../../app/src/main/resources/rockstar/helpers"} +mkdir -p "$out" +for target in i686-pc-windows-gnu x86_64-pc-windows-gnu; do + rustup target add "$target" >/dev/null 2>&1 || true + cargo build --manifest-path "$here/Cargo.toml" --release --locked --target "$target" + name=Launcher64.exe + [[ "$target" == i686-* ]] && name=Launcher32.exe + install -m644 "${CARGO_TARGET_DIR:-$here/target}/$target/release/Launcher.exe" "$out/$name" +done diff --git a/tools/rockstar-launcher/examples/capture.rs b/tools/rockstar-launcher/examples/capture.rs new file mode 100644 index 0000000000..8516cbca17 --- /dev/null +++ b/tools/rockstar-launcher/examples/capture.rs @@ -0,0 +1,65 @@ +#[cfg(windows)] +fn main() -> std::io::Result<()> { + use droiddeck_rockstar_launcher::{pipe::Pipe, Frame, Length}; + use std::fs::OpenOptions; + use std::io::{self, Read, Write}; + use std::time::Duration; + + struct Recording<'a> { + source: &'a mut Pipe, + output: &'a mut std::fs::File, + } + + impl Read for Recording<'_> { + fn read(&mut self, buffer: &mut [u8]) -> io::Result { + let size = self.source.read(buffer)?; + self.output.write_all(&buffer[..size])?; + Ok(size) + } + } + + let args: Vec<_> = std::env::args_os().collect(); + let output = args + .windows(2) + .find(|pair| pair[0] == "--output") + .map(|pair| pair[1].clone()) + .map(std::path::PathBuf::from) + .unwrap_or(std::env::current_exe()?.with_file_name("reference-reply.bin")); + let mut file = OpenOptions::new() + .create_new(true) + .write(true) + .open(output)?; + let pipe_name = args + .windows(2) + .find(|pair| pair[0] == "--pipe") + .map(|pair| pair[1].to_string_lossy().into_owned()) + .unwrap_or_else(|| "GTA-VC_Pipe".to_owned()); + let mut pipe = Pipe::connect(&pipe_name, Duration::from_secs(90))?; + Frame { + tag: *b"COLE", + payload: Vec::new(), + nul_terminated: true, + } + .write(&mut pipe, Length::Total)?; + let reply = Frame::read( + &mut Recording { + source: &mut pipe, + output: &mut file, + }, + Length::Body, + ); + file.sync_all()?; + let reply = reply?; + println!( + "Received {} ({} payload bytes)", + String::from_utf8_lossy(&reply.tag), + reply.payload.len() + ); + Ok(()) +} + +#[cfg(not(windows))] +fn main() { + eprintln!("The reference pipe client runs on Windows or Wine."); + std::process::exit(1); +} diff --git a/tools/rockstar-launcher/examples/sdk_probe.rs b/tools/rockstar-launcher/examples/sdk_probe.rs new file mode 100644 index 0000000000..b280ce0409 --- /dev/null +++ b/tools/rockstar-launcher/examples/sdk_probe.rs @@ -0,0 +1,80 @@ +#[cfg(windows)] +fn run() -> Result<(), Box> { + use droiddeck_rockstar_launcher::{pipe::Pipe, sdk::Message, Frame, Length}; + use std::io::{Read, Write}; + for (path, framed) in [ + (b"\\\\.\\pipe\\ProbeLauncherPipe\0".as_slice(), true), + (b"\\\\.\\pipe\\RawProbeLauncher_Pipe\0".as_slice(), false), + ] { + let name = std::str::from_utf8(&path[9..path.len() - 1])?; + let mut pipe = Pipe::connect(name, std::time::Duration::from_secs(10))?; + let request = b"INIT:42:"; + if framed { + let mut bytes = (request.len() as u32).to_le_bytes().to_vec(); + bytes.extend_from_slice(request); + pipe.write_all(&bytes)?; + let response = Frame::read(&mut pipe, Length::Body)?; + if response.tag != *b"TINI" || response.payload != b"launcher:42:" { + return Err("invalid framed launcher identity reply".into()); + } + } else { + pipe.write_all(b"INIT:4")?; + std::thread::sleep(std::time::Duration::from_millis(20)); + pipe.write_all(b"2:")?; + let mut response = vec![0; b"TINI:launcher:42:".len()]; + pipe.read_exact(&mut response)?; + if response != b"TINI:launcher:42:" { + return Err("invalid raw launcher identity reply".into()); + } + } + } + let args: Vec<_> = std::env::args().collect(); + let instance: u32 = args + .iter() + .find_map(|arg| arg.strip_prefix("-processInstance=")) + .ok_or("missing instance")? + .parse()?; + let output = args + .windows(2) + .find(|pair| pair[0] == "--result") + .map(|pair| &pair[1]) + .ok_or("missing result path")?; + let mut pipe = Pipe::connect( + &format!("chrome.rgsc_gameinst_{instance}"), + std::time::Duration::from_secs(10), + )?; + if Message::read(&mut pipe)?.kind != 0xffff { + return Err("missing transport hello".into()); + } + Message { + routing: i32::MAX, + kind: 0x40000, + flags: 2, + payload: 4u32.to_le_bytes().to_vec(), + } + .write(&mut pipe)?; + let expected = [0x30002, 0x30003, 0x30004, 0x30000]; + for kind in expected { + let message = Message::read(&mut pipe)?; + if message.kind != kind || message.routing != i32::MAX || message.flags != 2 { + return Err("unexpected SDK message envelope".into()); + } + if kind == 0x30002 && message.payload != [3, 0, 0, 0, 123, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + { + return Err("unexpected fixture account".into()); + } + if kind == 0x30000 && message.payload != 4u32.to_le_bytes() { + return Err("launcher hello lost its context".into()); + } + } + std::fs::write(output, "SDK handshake accepted")?; + Ok(()) +} + +fn main() { + #[cfg(windows)] + if let Err(error) = run() { + eprintln!("SDK probe failed: {error}"); + std::process::exit(1); + } +} diff --git a/tools/rockstar-launcher/src/identity.rs b/tools/rockstar-launcher/src/identity.rs new file mode 100644 index 0000000000..795d56da1a --- /dev/null +++ b/tools/rockstar-launcher/src/identity.rs @@ -0,0 +1,170 @@ +use std::collections::BTreeSet; +use std::io::{self, Read}; + +const LIMIT: usize = 4096; + +fn invalid() -> io::Error { + io::Error::new( + io::ErrorKind::InvalidData, + "invalid launcher identity request", + ) +} + +fn collect(bytes: &[u8], names: &mut BTreeSet) { + let prefix = br"\\.\pipe\"; + for (index, window) in bytes.windows(prefix.len()).enumerate() { + if window != prefix { + continue; + } + let tail = &bytes[index + prefix.len()..]; + let Some(end) = tail.iter().take(97).position(|byte| *byte == 0) else { + continue; + }; + let name = &tail[..end]; + if !name.is_empty() + && name + .iter() + .all(|byte| byte.is_ascii_alphanumeric() || b"_-".contains(byte)) + { + let name = std::str::from_utf8(name).unwrap(); + if name.ends_with("LauncherPipe") || name.ends_with("Launcher_Pipe") { + names.insert(name.to_owned()); + } + } + } +} + +pub fn pipe_names(reader: &mut impl Read) -> io::Result> { + let mut names = BTreeSet::new(); + let mut carry = Vec::new(); + let mut chunk = [0; 65536]; + let mut total = 0usize; + loop { + let count = reader.read(&mut chunk)?; + if count == 0 { + break; + } + total += count; + if total > 256 * 1024 * 1024 { + return Err(invalid()); + } + carry.extend_from_slice(&chunk[..count]); + collect(&carry, &mut names); + for offset in 0..2 { + let ascii: Vec<_> = carry[offset..] + .chunks_exact(2) + .map(|pair| if pair[1] == 0 { pair[0] } else { 0 }) + .collect(); + collect(&ascii, &mut names); + } + if names.len() > 4 { + return Err(invalid()); + } + carry.drain(..carry.len().saturating_sub(256)); + } + Ok(names.into_iter().collect()) +} + +pub fn exchange(reader: &mut impl Read) -> io::Result> { + let mut header = [0; 4]; + reader.read_exact(&mut header)?; + let framed = header != *b"INIT"; + let mut request = if framed { + let size = u32::from_le_bytes(header) as usize; + if !(6..=LIMIT).contains(&size) { + return Err(invalid()); + } + let mut bytes = vec![0; size]; + reader.read_exact(&mut bytes)?; + bytes + } else { + let mut bytes = header.to_vec(); + let mut byte = [0]; + reader.read_exact(&mut byte)?; + if byte[0] != b':' { + return Err(invalid()); + } + bytes.push(b':'); + loop { + reader.read_exact(&mut byte)?; + if !(32..127).contains(&byte[0]) || bytes.len() >= 261 { + return Err(invalid()); + } + bytes.push(byte[0]); + if byte[0] == b':' { + break; + } + } + bytes + }; + if request.last() == Some(&0) { + request.pop(); + } + let challenge = request.strip_prefix(b"INIT:").ok_or_else(invalid)?; + if challenge.is_empty() + || !framed && challenge == b":" + || challenge.len() > 256 + || !challenge.iter().all(|byte| (32..127).contains(byte)) + { + return Err(invalid()); + } + let mut reply = b"TINI:launcher:".to_vec(); + reply.extend_from_slice(challenge); + if framed { + let mut bytes = (reply.len() as u32).to_le_bytes().to_vec(); + bytes.extend_from_slice(&reply); + Ok(bytes) + } else { + Ok(reply) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::io::Cursor; + + #[test] + fn discovers_ascii_and_wide_pipe_names_across_chunks() { + let mut bytes = vec![0; 65530]; + bytes.extend_from_slice(br"\\.\pipe\GameLauncherPipe"); + bytes.push(0); + for value in "\\\\.\\pipe\\OtherLauncher_Pipe\0".encode_utf16() { + bytes.extend_from_slice(&value.to_le_bytes()); + } + bytes.extend_from_slice(br"\\.\pipe\..\outsideLauncherPipe"); + bytes.push(0); + assert_eq!( + pipe_names(&mut Cursor::new(bytes)).unwrap(), + ["GameLauncherPipe", "OtherLauncher_Pipe"] + ); + } + + #[test] + fn identity_replies_echo_only_a_valid_challenge() { + struct Split(R); + impl Read for Split { + fn read(&mut self, buffer: &mut [u8]) -> io::Result { + let size = buffer.len().min(2); + self.0.read(&mut buffer[..size]) + } + } + assert_eq!( + exchange(&mut Split(Cursor::new(b"INIT:123456789:\0"))).unwrap(), + b"TINI:launcher:123456789:" + ); + let request = b"INIT:nonce:123:"; + let mut bytes = (request.len() as u32).to_le_bytes().to_vec(); + bytes.extend_from_slice(request); + let reply = exchange(&mut Cursor::new(bytes)).unwrap(); + assert_eq!( + u32::from_le_bytes(reply[..4].try_into().unwrap()) as usize, + reply.len() - 4 + ); + assert_eq!(&reply[4..], b"TINI:launcher:nonce:123:"); + assert!(exchange(&mut Cursor::new(b"INIT:")).is_err()); + assert!(exchange(&mut Cursor::new(b"INIT:a\0b")).is_err()); + assert!(exchange(&mut Cursor::new(b"INIT:unterminated")).is_err()); + assert!(exchange(&mut Cursor::new([255; 4])).is_err()); + } +} diff --git a/tools/rockstar-launcher/src/lib.rs b/tools/rockstar-launcher/src/lib.rs new file mode 100644 index 0000000000..e37ff76d85 --- /dev/null +++ b/tools/rockstar-launcher/src/lib.rs @@ -0,0 +1,351 @@ +use std::io::{self, Read, Write}; + +#[cfg(windows)] +pub mod pipe; + +pub mod identity; +pub mod sdk; + +pub const MAX_FRAME_BYTES: usize = 64 * 1024; +const OVERHEAD: usize = 4 + 4 + 1; + +pub fn wait_for_game( + child: &mut std::process::Child, + handshake: std::sync::mpsc::Receiver>, +) -> io::Result { + use std::sync::mpsc::RecvTimeoutError; + loop { + match handshake.recv_timeout(std::time::Duration::from_millis(10)) { + Ok(Ok(())) => return child.wait(), + result @ (Ok(Err(_)) | Err(RecvTimeoutError::Disconnected)) => { + let error = match result { + Ok(Err(error)) => error, + _ => io::Error::new( + io::ErrorKind::BrokenPipe, + "Rockstar handshake worker stopped", + ), + }; + let _ = child.kill(); + child.wait()?; + return Err(error); + } + Err(RecvTimeoutError::Timeout) => { + if let Some(status) = child.try_wait()? { + return Ok(status); + } + } + } + } +} + +#[derive(Clone, Copy)] +pub enum Length { + Total, + Body, +} + +impl Length { + fn header_bytes(self) -> usize { + match self { + Self::Total => 0, + Self::Body => 4, + } + } +} + +#[derive(Debug, PartialEq, Eq)] +pub struct Frame { + pub tag: [u8; 4], + pub payload: Vec, + pub nul_terminated: bool, +} + +fn invalid(message: &'static str) -> io::Error { + io::Error::new(io::ErrorKind::InvalidData, message) +} + +impl Frame { + pub fn read(reader: &mut impl Read, length: Length) -> io::Result { + let mut header = [0; 4]; + reader.read_exact(&mut header)?; + let size = (u32::from_le_bytes(header) as usize) + .checked_add(length.header_bytes()) + .ok_or_else(|| invalid("invalid Rockstar pipe frame length"))?; + if !(OVERHEAD..=MAX_FRAME_BYTES).contains(&size) { + return Err(invalid("invalid Rockstar pipe frame length")); + } + let mut body = vec![0; size - header.len()]; + reader.read_exact(&mut body)?; + let nul_terminated = body.last() == Some(&0); + let end = body.len() - usize::from(nul_terminated); + if body[4] != b':' || body[..4].contains(&b':') || body[..end].contains(&0) { + return Err(invalid("invalid Rockstar pipe frame envelope")); + } + Ok(Self { + tag: body[..4].try_into().unwrap(), + payload: body[5..end].to_vec(), + nul_terminated, + }) + } + + pub fn write(&self, writer: &mut impl Write, length: Length) -> io::Result<()> { + let size = self + .payload + .len() + .checked_add(OVERHEAD + usize::from(self.nul_terminated)) + .filter(|size| *size <= MAX_FRAME_BYTES) + .ok_or_else(|| invalid("Rockstar pipe frame exceeds size limit"))?; + if self.tag.contains(&0) || self.tag.contains(&b':') || self.payload.contains(&0) { + return Err(invalid("Rockstar pipe frame contains a delimiter")); + } + let mut encoded = Vec::with_capacity(size); + encoded.extend_from_slice(&((size - length.header_bytes()) as u32).to_le_bytes()); + encoded.extend_from_slice(&self.tag); + encoded.push(b':'); + encoded.extend_from_slice(&self.payload); + if self.nul_terminated { + encoded.push(0); + } + writer.write_all(&encoded)?; + writer.flush() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn launcher_era_reply_uses_total_length_and_a_terminator() { + let mut bytes = Vec::new(); + Frame { + tag: *b"DUNN", + payload: vec![b'A'; 640], + nul_terminated: true, + } + .write(&mut bytes, Length::Total) + .unwrap(); + assert_eq!(bytes.len(), 650); + assert_eq!(&bytes[..9], &[138, 2, 0, 0, b'D', b'U', b'N', b'N', b':']); + assert_eq!(bytes[649], 0); + } + use std::io::Cursor; + + #[test] + #[ignore] + fn sleeping_game() { + std::thread::sleep(std::time::Duration::from_secs(30)); + } + + fn sleeping_child() -> std::process::Child { + std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "tests::sleeping_game", "--ignored"]) + .stdout(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()) + .spawn() + .unwrap() + } + + #[test] + fn failed_handshake_terminates_and_reaps_the_game() { + let mut child = sleeping_child(); + let (sender, receiver) = std::sync::mpsc::channel(); + sender + .send(Err(io::Error::new(io::ErrorKind::TimedOut, "test timeout"))) + .unwrap(); + let start = std::time::Instant::now(); + assert_eq!( + wait_for_game(&mut child, receiver).unwrap_err().kind(), + io::ErrorKind::TimedOut + ); + assert!(start.elapsed() < std::time::Duration::from_secs(3)); + assert!(child.try_wait().unwrap().is_some()); + } + + #[test] + fn stopped_handshake_worker_terminates_and_reaps_the_game() { + let mut child = sleeping_child(); + let (sender, receiver) = std::sync::mpsc::channel(); + drop(sender); + assert_eq!( + wait_for_game(&mut child, receiver).unwrap_err().kind(), + io::ErrorKind::BrokenPipe + ); + assert!(child.try_wait().unwrap().is_some()); + } + + #[test] + fn an_exited_game_does_not_wait_for_its_handshake() { + let mut child = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "no_test_with_this_name"]) + .stdout(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()) + .spawn() + .unwrap(); + let (_sender, receiver) = std::sync::mpsc::channel(); + assert!(wait_for_game(&mut child, receiver).unwrap().success()); + } + + struct Fragmented(T); + + impl Read for Fragmented { + fn read(&mut self, buffer: &mut [u8]) -> io::Result { + let size = buffer.len().min(1); + self.0.read(&mut buffer[..size]) + } + } + + impl Write for Fragmented { + fn write(&mut self, buffer: &[u8]) -> io::Result { + self.0.write(&buffer[..buffer.len().min(1)]) + } + + fn flush(&mut self) -> io::Result<()> { + self.0.flush() + } + } + + #[test] + fn reads_observed_greeting_across_partial_reads() { + let bytes = b"\x0a\0\0\0COLE:\0"; + assert_eq!( + Frame::read(&mut Fragmented(&bytes[..]), Length::Total).unwrap(), + Frame { + tag: *b"COLE", + payload: Vec::new(), + nul_terminated: true, + } + ); + } + + #[test] + fn writes_the_observed_total_length_even_with_partial_writes() { + let mut bytes = Fragmented(Vec::new()); + Frame { + tag: *b"COLE", + payload: Vec::new(), + nul_terminated: true, + } + .write(&mut bytes, Length::Total) + .unwrap(); + assert_eq!(bytes.0, b"\x0a\0\0\0COLE:\0"); + } + + #[test] + fn keeps_colons_in_payload_and_leaves_the_next_frame_unread() { + let frame = Frame { + tag: *b"DUNN", + payload: b"one:two".to_vec(), + nul_terminated: false, + }; + let mut bytes = Vec::new(); + frame.write(&mut bytes, Length::Total).unwrap(); + bytes.extend_from_slice(b"\x0a\0\0\0COLE:\0"); + let mut reader = Cursor::new(bytes); + assert_eq!(Frame::read(&mut reader, Length::Total).unwrap(), frame); + assert_eq!( + Frame::read(&mut reader, Length::Total).unwrap().tag, + *b"COLE" + ); + } + + #[test] + fn rejects_invalid_lengths_before_reading_a_body() { + for size in [0u32, 4, 8, MAX_FRAME_BYTES as u32 + 1, u32::MAX] { + let mut reader = Cursor::new(size.to_le_bytes()); + assert_eq!( + Frame::read(&mut reader, Length::Total).unwrap_err().kind(), + io::ErrorKind::InvalidData + ); + assert_eq!(reader.position(), 4); + } + } + + #[test] + fn rejects_truncated_or_malformed_frames() { + for bytes in [&b"\x0a\0\0"[..], &b"\x0a\0\0\0COLE:"[..]] { + assert_eq!( + Frame::read(&mut &bytes[..], Length::Total) + .unwrap_err() + .kind(), + io::ErrorKind::UnexpectedEof + ); + } + for bytes in [ + b"\x0a\0\0\0COLE=\0", + b"\x0a\0\0\0CO:E:x", + b"\x0a\0\0\0CO\0E:\0", + ] { + assert_eq!( + Frame::read(&mut &bytes[..], Length::Total) + .unwrap_err() + .kind(), + io::ErrorKind::InvalidData + ); + } + } + + #[test] + fn rejects_invalid_output_before_writing_any_bytes() { + let mut bytes = Vec::new(); + for frame in [ + Frame { + tag: *b"DUNN", + payload: vec![b'x'; MAX_FRAME_BYTES], + nul_terminated: false, + }, + Frame { + tag: *b"DUNN", + payload: b"one\0two".to_vec(), + nul_terminated: false, + }, + Frame { + tag: *b"CO:E", + payload: Vec::new(), + nul_terminated: false, + }, + ] { + assert!(frame.write(&mut bytes, Length::Total).is_err()); + assert!(bytes.is_empty()); + } + } + + #[test] + fn accepts_the_observed_unterminated_launch_reply_shape() { + let payload = vec![b'A'; 640]; + let mut bytes = 645u32.to_le_bytes().to_vec(); + bytes.extend_from_slice(b"DUNN:"); + bytes.extend_from_slice(&payload); + let frame = Frame::read(&mut Fragmented(&bytes[..]), Length::Body).unwrap(); + assert_eq!(bytes.len(), 649); + assert_eq!(frame.tag, *b"DUNN"); + assert_eq!(frame.payload, payload); + assert!(!frame.nul_terminated); + let mut encoded = Vec::new(); + frame.write(&mut encoded, Length::Body).unwrap(); + assert_eq!(encoded, bytes); + } + + #[test] + fn presents_a_complete_reply_to_the_pipe_in_one_write() { + struct Writes(Vec); + impl Write for Writes { + fn write(&mut self, bytes: &[u8]) -> io::Result { + self.0.push(bytes.len()); + Ok(bytes.len()) + } + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } + } + let mut writer = Writes(Vec::new()); + Frame { + tag: *b"DUNN", + payload: vec![b'A'; 640], + nul_terminated: false, + } + .write(&mut writer, Length::Body) + .unwrap(); + assert_eq!(writer.0, vec![649]); + } +} diff --git a/tools/rockstar-launcher/src/main.rs b/tools/rockstar-launcher/src/main.rs new file mode 100644 index 0000000000..0913c6d548 --- /dev/null +++ b/tools/rockstar-launcher/src/main.rs @@ -0,0 +1,275 @@ +#![cfg_attr(windows, windows_subsystem = "windows")] + +#[cfg(windows)] +fn log(message: &str) { + use std::io::Write; + let Ok(exe) = std::env::current_exe() else { + return; + }; + let path = exe.with_file_name("launcher.log"); + if let Ok(metadata) = std::fs::symlink_metadata(&path) { + if !metadata.is_file() || metadata.len() > 65536 { + return; + } + } + if let Ok(mut file) = std::fs::OpenOptions::new() + .create(true) + .append(true) + .open(path) + { + let _ = writeln!(file, "{message}"); + } +} + +#[cfg(windows)] +fn run() -> Result> { + use droiddeck_rockstar_launcher::{ + pipe::Listener, + sdk::{Message, Session}, + wait_for_game, Frame, Length, + }; + use std::io::{Read, Write}; + use std::time::{Duration, SystemTime, UNIX_EPOCH}; + + let config_path = std::env::current_exe()?.with_file_name("launch.json"); + let mut data = Vec::new(); + std::fs::File::open(&config_path)? + .take(65537) + .read_to_end(&mut data)?; + std::fs::remove_file(&config_path)?; + if data.len() > 65536 { + return Err("launch handoff exceeds size limit".into()); + } + let config: serde_json::Value = serde_json::from_slice(&data)?; + let text = |key| { + config + .get(key) + .and_then(|value| value.as_str()) + .ok_or("missing launch field") + }; + let expires = config + .get("expiresAt") + .and_then(|value| value.as_u64()) + .ok_or("missing launch expiry")?; + let now = SystemTime::now().duration_since(UNIX_EPOCH)?.as_millis() as u64; + if expires <= now || expires - now > 120_000 { + return Err("launch handoff expired".into()); + } + let legacy = if config.get("pipe").is_some() { + let pipe_name = text("pipe")?.to_owned(); + if !matches!( + pipe_name.as_str(), + "GTA3_Pipe" | "GTA-VC_Pipe" | "GTA_SA_Pipe" | "GTAIV_Pipe" | "LANOIRE_Pipe" + ) { + return Err("invalid Rockstar launch pipe".into()); + } + let material = text("material")?.as_bytes().to_vec(); + if material.len() != 640 || !material.iter().all(u8::is_ascii_hexdigit) { + return Err("invalid launch material".into()); + } + Some((pipe_name, material)) + } else { + None + }; + let session = config + .get("session") + .map(|value| -> Result> { + let account = value + .get("accountId") + .and_then(|v| v.as_str()) + .ok_or("missing SDK account")? + .parse::()?; + let identity = value + .get("identity") + .and_then(|v| v.as_str()) + .ok_or("missing SDK identity")?; + let ticket = value + .get("ticket") + .and_then(|v| v.as_str()) + .ok_or("missing SDK ticket")?; + let session = Session::new(account, identity.to_owned(), ticket.to_owned())?; + Ok(if let Some(title) = value.get("titleId") { + session.with_title(title.as_str().ok_or("invalid SDK title")?.to_owned())? + } else { + session + }) + }) + .transpose()?; + if legacy.is_none() && session.is_none() { + return Err("missing launch protocol".into()); + } + let root = std::fs::canonicalize(text("folder")?)?; + let exe = std::fs::canonicalize(text("exe")?)?; + let workdir = std::fs::canonicalize(text("workdir")?)?; + if !exe.is_file() + || !exe.starts_with(&root) + || !workdir.starts_with(&root) + || legacy.is_some() + && !root.join("MTLX.dll").is_file() + && !exe.parent().unwrap_or(&root).join("MTLX.dll").is_file() + { + return Err("invalid Rockstar game path".into()); + } + if let Some(index) = + std::env::args().position(|arg| arg.eq_ignore_ascii_case("-launchTitleInFolder")) + { + let folder = std::env::args() + .nth(index + 1) + .ok_or("missing game folder")?; + if std::fs::canonicalize(folder)? != root { + return Err("Rockstar launch folder mismatch".into()); + } + } + let args = config + .get("args") + .and_then(|value| value.as_array()) + .ok_or("missing game arguments")?; + let args: Result, _> = args + .iter() + .map(|value| value.as_str().ok_or("invalid game argument")) + .collect(); + log("launch handoff accepted"); + let legacy = legacy + .map(|(name, material)| { + let terminated = matches!(name.as_str(), "GTAIV_Pipe" | "LANOIRE_Pipe"); + Listener::new(&name, Duration::from_secs(90)) + .map(|listener| (listener, material, terminated)) + }) + .transpose()?; + let instance = std::process::id(); + let sdk_listener = if session.is_some() { + Some(Listener::new( + &format!("chrome.rgsc_gameinst_{instance}"), + Duration::from_secs(90), + )?) + } else { + None + }; + let mut identity_listeners = Vec::new(); + if session.is_some() { + for name in + droiddeck_rockstar_launcher::identity::pipe_names(&mut std::fs::File::open(&exe)?)? + { + identity_listeners.push(Listener::new(&name, Duration::from_secs(90))?); + } + } + log("launcher pipes created"); + let mut command = std::process::Command::new(exe); + command.current_dir(workdir).args(args?); + if session.is_some() { + command.arg(format!("-processInstance={instance}")); + } + let mut child = command.spawn()?; + let pid = child.id(); + log("game process started"); + for listener in identity_listeners { + std::thread::spawn(move || { + let serve = || -> std::io::Result<()> { + let mut pipe = listener.accept()?.with_deadline(Duration::from_secs(90)); + if pipe.client_pid()? != pid { + return Err(std::io::Error::new( + std::io::ErrorKind::PermissionDenied, + "unexpected launcher identity client", + )); + } + let reply = droiddeck_rockstar_launcher::identity::exchange(&mut pipe)?; + pipe.write_all(&reply)?; + log("launcher identity challenge complete"); + pipe = pipe.with_timeout(Duration::from_secs(86400)); + let mut progress = [0; 4096]; + while matches!(pipe.read(&mut progress), Ok(size) if size > 0) {} + Ok(()) + }; + if let Err(error) = serve() { + log(&format!("launcher identity exchange ended: {error}")); + } + }); + } + let (result, handshake) = std::sync::mpsc::sync_channel(1); + std::thread::spawn(move || { + let serve = || -> std::io::Result<()> { + if let Some((listener, material, terminated)) = legacy { + let mut pipe = listener.accept()?; + log("legacy launcher pipe connected"); + if pipe.client_pid()? != pid { + return Err(std::io::Error::new( + std::io::ErrorKind::PermissionDenied, + "unexpected Rockstar pipe client", + )); + } + let request = Frame::read(&mut pipe, Length::Total)?; + if request.tag != *b"COLE" || !request.payload.is_empty() { + return Err(std::io::Error::new( + std::io::ErrorKind::InvalidData, + "unexpected Rockstar greeting", + )); + } + Frame { + tag: *b"DUNN", + payload: material, + nul_terminated: terminated, + } + .write( + &mut pipe, + if terminated { + Length::Total + } else { + Length::Body + }, + )?; + log("legacy launcher handshake complete"); + } + if let (Some(listener), Some(session)) = (sdk_listener, session) { + let mut pipe = listener.accept()?.with_deadline(Duration::from_secs(90)); + if pipe.client_pid()? != pid { + return Err(std::io::Error::new( + std::io::ErrorKind::PermissionDenied, + "unexpected Rockstar SDK client", + )); + } + Message::hello(instance).write(&mut pipe)?; + let mut authenticated = false; + loop { + let request = match Message::read(&mut pipe) { + Ok(request) => request, + Err(_) if authenticated => return Ok(()), + Err(error) => return Err(error), + }; + let responses = session.respond(&request)?; + let sends_login = request.kind == 0x40000; + for response in responses { + response.write(&mut pipe)?; + } + if sends_login && !authenticated { + authenticated = true; + pipe = pipe.with_timeout(Duration::from_secs(86400)); + log("SDK login sent"); + let _ = result.send(Ok(())); + } + } + } + Ok(()) + }; + let outcome = serve(); + if let Err(error) = &outcome { + log(&format!("launcher handshake failed: {error}")); + } + let _ = result.send(outcome); + }); + Ok(wait_for_game(&mut child, handshake)?.code().unwrap_or(1)) +} + +fn main() { + #[cfg(windows)] + let code = match run() { + Ok(code) => code, + Err(error) => { + log(&format!("launch failed: {error}")); + eprintln!("Rockstar launch failed: {error}"); + 1 + } + }; + #[cfg(not(windows))] + let code = 1; + std::process::exit(code); +} diff --git a/tools/rockstar-launcher/src/pipe.rs b/tools/rockstar-launcher/src/pipe.rs new file mode 100644 index 0000000000..9bffedde38 --- /dev/null +++ b/tools/rockstar-launcher/src/pipe.rs @@ -0,0 +1,450 @@ +use std::ffi::c_void; +use std::io::{self, Read, Write}; +use std::os::windows::ffi::OsStrExt; +use std::ptr::{null, null_mut}; +use std::time::{Duration, Instant}; + +type Handle = *mut c_void; +const INVALID_HANDLE: Handle = -1isize as Handle; +const ERROR_IO_PENDING: i32 = 997; +const ERROR_MORE_DATA: i32 = 234; + +#[repr(C)] +struct Overlapped { + internal: usize, + internal_high: usize, + offset: u32, + offset_high: u32, + event: Handle, +} + +#[link(name = "kernel32")] +extern "system" { + fn CreateNamedPipeW( + name: *const u16, + open: u32, + mode: u32, + max: u32, + output: u32, + input: u32, + timeout: u32, + security: *const c_void, + ) -> Handle; + fn ConnectNamedPipe(handle: Handle, overlapped: *mut Overlapped) -> i32; + fn GetNamedPipeClientProcessId(handle: Handle, pid: *mut u32) -> i32; + fn CreateFileW( + name: *const u16, + access: u32, + share: u32, + security: *const c_void, + creation: u32, + flags: u32, + template: Handle, + ) -> Handle; + fn WaitNamedPipeW(name: *const u16, timeout: u32) -> i32; + fn CreateEventW(security: *const c_void, manual: i32, initial: i32, name: *const u16) + -> Handle; + fn CloseHandle(handle: Handle) -> i32; + fn ReadFile( + handle: Handle, + buffer: *mut u8, + size: u32, + read: *mut u32, + overlapped: *mut Overlapped, + ) -> i32; + fn WriteFile( + handle: Handle, + buffer: *const u8, + size: u32, + written: *mut u32, + overlapped: *mut Overlapped, + ) -> i32; + fn WaitForSingleObject(handle: Handle, timeout: u32) -> u32; + fn CancelIoEx(handle: Handle, overlapped: *mut Overlapped) -> i32; + fn GetOverlappedResult( + handle: Handle, + overlapped: *mut Overlapped, + transferred: *mut u32, + wait: i32, + ) -> i32; +} + +struct OwnedHandle(Handle); + +unsafe impl Send for OwnedHandle {} + +impl Drop for OwnedHandle { + fn drop(&mut self) { + unsafe { + CloseHandle(self.0); + } + } +} + +pub struct Pipe { + handle: OwnedHandle, + timeout: Duration, + deadline: Option, +} + +pub struct Listener(Pipe); + +impl Listener { + pub fn new(name: &str, timeout: Duration) -> io::Result { + if name.is_empty() || name.contains(['\\', '/', '\0']) { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "invalid pipe name", + )); + } + let path = format!(r"\\.\pipe\{name}"); + let wide: Vec<_> = std::ffi::OsStr::new(&path) + .encode_wide() + .chain(Some(0)) + .collect(); + let handle = unsafe { + CreateNamedPipeW( + wide.as_ptr(), + 3 | 0x4000_0000 | 0x0008_0000, + 8, + 1, + 65536, + 65536, + 0, + null(), + ) + }; + if handle == INVALID_HANDLE { + return Err(io::Error::last_os_error()); + } + Ok(Self(Pipe { + handle: OwnedHandle(handle), + timeout, + deadline: None, + })) + } + + pub fn accept(self) -> io::Result { + let event = unsafe { CreateEventW(null(), 1, 0, null()) }; + if event.is_null() { + return Err(io::Error::last_os_error()); + } + let event = OwnedHandle(event); + let mut overlapped = Overlapped { + internal: 0, + internal_high: 0, + offset: 0, + offset_high: 0, + event: event.0, + }; + if unsafe { ConnectNamedPipe(self.0.handle.0, &mut overlapped) } != 0 { + return Ok(self.0); + } + let error = io::Error::last_os_error(); + if error.raw_os_error() == Some(535) { + return Ok(self.0); + } + if error.raw_os_error() != Some(ERROR_IO_PENDING) { + return Err(error); + } + let wait = unsafe { + WaitForSingleObject( + event.0, + self.0.timeout.as_millis().min(u32::MAX as u128 - 1) as u32, + ) + }; + let mut transferred = 0; + if wait != 0 { + let error = if wait == 258 { + io::Error::new(io::ErrorKind::TimedOut, "waiting for Rockstar game") + } else { + io::Error::last_os_error() + }; + unsafe { + CancelIoEx(self.0.handle.0, &mut overlapped); + GetOverlappedResult(self.0.handle.0, &mut overlapped, &mut transferred, 1); + } + return Err(error); + } + if unsafe { GetOverlappedResult(self.0.handle.0, &mut overlapped, &mut transferred, 0) } + == 0 + { + return Err(io::Error::last_os_error()); + } + Ok(self.0) + } +} + +impl Pipe { + pub fn with_timeout(mut self, timeout: Duration) -> Self { + self.timeout = timeout; + self.deadline = None; + self + } + + pub fn with_deadline(mut self, timeout: Duration) -> Self { + self.timeout = timeout; + self.deadline = Some(Instant::now() + timeout); + self + } + + pub fn client_pid(&self) -> io::Result { + let mut pid = 0; + if unsafe { GetNamedPipeClientProcessId(self.handle.0, &mut pid) } == 0 || pid == 0 { + return Err(io::Error::last_os_error()); + } + Ok(pid) + } + pub fn connect(name: &str, timeout: Duration) -> io::Result { + if name.is_empty() || name.contains(['\\', '/', '\0']) { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "invalid pipe name", + )); + } + let path = format!(r"\\.\pipe\{name}"); + let wide: Vec<_> = std::ffi::OsStr::new(&path) + .encode_wide() + .chain(Some(0)) + .collect(); + let deadline = Instant::now() + timeout; + loop { + let handle = unsafe { + CreateFileW( + wide.as_ptr(), + 0xc000_0000, + 0, + null(), + 3, + 0x4000_0000, + null_mut(), + ) + }; + if handle != INVALID_HANDLE { + return Ok(Self { + handle: OwnedHandle(handle), + timeout, + deadline: None, + }); + } + let error = io::Error::last_os_error(); + if !matches!(error.raw_os_error(), Some(2 | 231)) { + return Err(error); + } + let remaining = deadline.saturating_duration_since(Instant::now()); + if remaining.is_zero() { + return Err(io::Error::new( + io::ErrorKind::TimedOut, + "waiting for Rockstar pipe", + )); + } + unsafe { + WaitNamedPipeW(wide.as_ptr(), remaining.as_millis().min(50) as u32); + } + std::thread::sleep(remaining.min(Duration::from_millis(2))); + } + } + + fn transfer(&self, buffer: *mut u8, size: usize, writing: bool) -> io::Result { + if size == 0 { + return Ok(0); + } + let timeout = self + .deadline + .map(|deadline| deadline.saturating_duration_since(Instant::now())) + .unwrap_or(self.timeout); + if timeout.is_zero() { + return Err(io::Error::new( + io::ErrorKind::TimedOut, + "Rockstar pipe deadline exceeded", + )); + } + let event = unsafe { CreateEventW(null(), 1, 0, null()) }; + if event.is_null() { + return Err(io::Error::last_os_error()); + } + let event = OwnedHandle(event); + let mut overlapped = Overlapped { + internal: 0, + internal_high: 0, + offset: 0, + offset_high: 0, + event: event.0, + }; + let mut transferred = 0; + let size = size.min(u32::MAX as usize) as u32; + let ok = unsafe { + if writing { + WriteFile( + self.handle.0, + buffer, + size, + &mut transferred, + &mut overlapped, + ) + } else { + ReadFile( + self.handle.0, + buffer, + size, + &mut transferred, + &mut overlapped, + ) + } + }; + if ok != 0 { + return Ok(transferred as usize); + } + let error = io::Error::last_os_error(); + if error.raw_os_error() == Some(ERROR_MORE_DATA) && !writing && transferred > 0 { + return Ok(transferred as usize); + } + if error.raw_os_error() != Some(ERROR_IO_PENDING) { + return Err(error); + } + let wait = unsafe { + WaitForSingleObject( + event.0, + timeout.as_millis().min(u32::MAX as u128 - 1) as u32, + ) + }; + if wait != 0 { + let error = if wait == 258 { + io::Error::new(io::ErrorKind::TimedOut, "Rockstar pipe operation timed out") + } else { + io::Error::last_os_error() + }; + unsafe { + CancelIoEx(self.handle.0, &mut overlapped); + GetOverlappedResult(self.handle.0, &mut overlapped, &mut transferred, 1); + } + return Err(error); + } + let ok = + unsafe { GetOverlappedResult(self.handle.0, &mut overlapped, &mut transferred, 0) }; + if ok != 0 { + return Ok(transferred as usize); + } + let error = io::Error::last_os_error(); + if error.raw_os_error() == Some(ERROR_MORE_DATA) && !writing && transferred > 0 { + return Ok(transferred as usize); + } + Err(error) + } +} + +impl Read for Pipe { + fn read(&mut self, buffer: &mut [u8]) -> io::Result { + self.transfer(buffer.as_mut_ptr(), buffer.len(), false) + } +} + +impl Write for Pipe { + fn write(&mut self, buffer: &[u8]) -> io::Result { + self.transfer(buffer.as_ptr() as *mut u8, buffer.len(), true) + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{Frame, Length}; + use std::sync::mpsc; + use std::time::{SystemTime, UNIX_EPOCH}; + + fn name() -> String { + format!( + "dd-rockstar-test-{}-{}", + std::process::id(), + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_nanos() + ) + } + + #[test] + fn initialization_deadline_survives_partial_reads() { + let name = name(); + let listener = Listener::new(&name, Duration::from_secs(2)).unwrap(); + let worker = std::thread::spawn(move || { + let mut server = listener + .accept() + .unwrap() + .with_deadline(Duration::from_millis(150)); + let mut byte = [0]; + server.read_exact(&mut byte).unwrap(); + std::thread::sleep(Duration::from_millis(180)); + assert_eq!( + server.read(&mut byte).unwrap_err().kind(), + io::ErrorKind::TimedOut + ); + }); + let mut client = Pipe::connect(&name, Duration::from_secs(2)).unwrap(); + client.write_all(&[1]).unwrap(); + worker.join().unwrap(); + } + + #[test] + fn real_pipe_exchanges_both_framing_modes_and_identifies_the_client() { + let name = name(); + let listener = Listener::new(&name, Duration::from_secs(2)).unwrap(); + let worker = std::thread::spawn(move || { + let mut server = listener.accept().unwrap(); + assert_eq!(server.client_pid().unwrap(), std::process::id()); + assert_eq!( + Frame::read(&mut server, Length::Total).unwrap().tag, + *b"COLE" + ); + Frame { + tag: *b"DUNN", + payload: vec![b'A'; 640], + nul_terminated: false, + } + .write(&mut server, Length::Body) + .unwrap(); + }); + let mut client = Pipe::connect(&name, Duration::from_secs(2)).unwrap(); + Frame { + tag: *b"COLE", + payload: Vec::new(), + nul_terminated: true, + } + .write(&mut client, Length::Total) + .unwrap(); + let response = Frame::read(&mut client, Length::Body).unwrap(); + assert_eq!(response.payload.len(), 640); + assert!(!response.nul_terminated); + worker.join().unwrap(); + } + + #[test] + fn timed_out_accept_releases_the_first_pipe_instance() { + let name = name(); + let listener = Listener::new(&name, Duration::from_millis(20)).unwrap(); + assert!(matches!(listener.accept(), Err(error) if error.kind() == io::ErrorKind::TimedOut)); + assert!(Listener::new(&name, Duration::from_millis(20)).is_ok()); + } + + #[test] + fn timed_out_read_cancels_the_pending_operation() { + let name = name(); + let listener = Listener::new(&name, Duration::from_secs(2)).unwrap(); + let (done, wait) = mpsc::channel(); + let worker = std::thread::spawn(move || { + let _server = listener.accept().unwrap(); + wait.recv_timeout(Duration::from_secs(2)).unwrap(); + }); + let mut client = Pipe::connect(&name, Duration::from_millis(30)).unwrap(); + assert_eq!( + client.read(&mut [0u8; 4]).unwrap_err().kind(), + io::ErrorKind::TimedOut + ); + done.send(()).unwrap(); + worker.join().unwrap(); + } +} diff --git a/tools/rockstar-launcher/src/sdk.rs b/tools/rockstar-launcher/src/sdk.rs new file mode 100644 index 0000000000..9361ad54c2 --- /dev/null +++ b/tools/rockstar-launcher/src/sdk.rs @@ -0,0 +1,328 @@ +use std::io::{self, Read, Write}; + +const HEADER: usize = 16; +const MAX_BYTES: usize = 64 * 1024; +const CONTROL: i32 = i32::MAX; + +#[derive(PartialEq, Eq)] +pub struct Message { + pub routing: i32, + pub kind: u32, + pub flags: u32, + pub payload: Vec, +} + +impl std::fmt::Debug for Message { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter + .debug_struct("Message") + .field("routing", &self.routing) + .field("kind", &self.kind) + .field("flags", &self.flags) + .field("payload_bytes", &self.payload.len()) + .finish() + } +} + +fn invalid() -> io::Error { + io::Error::new(io::ErrorKind::InvalidData, "invalid Rockstar SDK message") +} + +impl Message { + pub fn read(reader: &mut impl Read) -> io::Result { + let mut header = [0; HEADER]; + reader.read_exact(&mut header)?; + let size = u32::from_le_bytes(header[..4].try_into().unwrap()) as usize; + if size > MAX_BYTES - HEADER { + return Err(invalid()); + } + let mut payload = vec![0; size]; + reader.read_exact(&mut payload)?; + Ok(Self { + routing: i32::from_le_bytes(header[4..8].try_into().unwrap()), + kind: u32::from_le_bytes(header[8..12].try_into().unwrap()), + flags: u32::from_le_bytes(header[12..16].try_into().unwrap()), + payload, + }) + } + + pub fn write(&self, writer: &mut impl Write) -> io::Result<()> { + if self.payload.len() > MAX_BYTES - HEADER { + return Err(invalid()); + } + let mut bytes = Vec::with_capacity(HEADER + self.payload.len()); + bytes.extend_from_slice(&(self.payload.len() as u32).to_le_bytes()); + bytes.extend_from_slice(&self.routing.to_le_bytes()); + bytes.extend_from_slice(&self.kind.to_le_bytes()); + bytes.extend_from_slice(&self.flags.to_le_bytes()); + bytes.extend_from_slice(&self.payload); + writer.write_all(&bytes) + } + + fn control(kind: u32, payload: Payload) -> Self { + Self { + routing: CONTROL, + kind, + flags: 2, + payload: payload.0, + } + } + + pub fn hello(pid: u32) -> Self { + Self { + routing: -2, + kind: 0xffff, + flags: 2, + payload: pid.to_le_bytes().to_vec(), + } + } +} + +#[derive(Default)] +struct Payload(Vec); + +impl Payload { + fn raw(mut self, bytes: &[u8]) -> Self { + self.0.resize((self.0.len() + 3) & !3, 0); + self.0.extend_from_slice(bytes); + self + } + + fn u32(self, value: u32) -> Self { + self.raw(&value.to_le_bytes()) + } + fn u64(self, value: u64) -> Self { + self.raw(&value.to_le_bytes()) + } + fn string(self, value: &str) -> Self { + self.u32(value.len() as u32).raw(value.as_bytes()) + } +} + +pub struct Session { + account: u64, + identity: String, + ticket: String, + title: Option, + api: std::cell::Cell, +} + +impl Session { + pub fn new(account: u64, identity: String, ticket: String) -> io::Result { + if account == 0 + || identity.is_empty() + || identity.len() > 512 + || ticket.is_empty() + || ticket.len() > 48 * 1024 + || identity.contains('\0') + || ticket.contains('\0') + { + return Err(invalid()); + } + Ok(Self { + account, + identity, + ticket, + title: None, + api: std::cell::Cell::new(3), + }) + } + + pub fn with_title(mut self, title: String) -> io::Result { + if title.is_empty() + || title.len() > 64 + || !title.as_bytes()[0].is_ascii_lowercase() + || !title + .bytes() + .all(|value| value.is_ascii_lowercase() || value.is_ascii_digit() || value == b'_') + { + return Err(invalid()); + } + self.title = Some(title); + Ok(self) + } + + fn app_sync(&self, challenge: u64) -> io::Result { + let mut payload = Payload::default().u32(u32::from(self.title.is_some())); + if let Some(title) = &self.title { + payload = payload + .u64(u64::MAX) + .u64(0) + .u64(0) + .string(title) + .u32(1) + .u32(1) + .string(""); + } + let mut inner = Vec::new(); + Message::control(0x80006, payload).write(&mut inner)?; + Ok(Message::control( + 0x80002, + Payload::default().u64(challenge).string(&base64(&inner)), + )) + } + + pub fn login(&self) -> Vec { + let offset = u32::from(self.api.get() >= 4); + vec![ + Message::control( + 0x30001 + offset, + Payload::default().u32(3).u64(self.account).u32(0), + ), + Message::control( + 0x30002 + offset, + Payload::default() + .u64(self.account) + .u32(0) + .string(&self.identity), + ), + Message::control( + 0x30003 + offset, + Payload::default() + .string(&self.identity) + .string(&self.ticket), + ), + ] + } + + pub fn respond(&self, message: &Message) -> io::Result> { + match message.kind { + 0x80000 => { + if message.payload.len() != 8 { + return Err(invalid()); + } + let challenge = u64::from_le_bytes(message.payload[..8].try_into().unwrap()); + Ok(vec![self.app_sync(challenge)?]) + } + 0x40000 => { + if message.payload.len() < 4 { + return Err(invalid()); + } + let context = u32::from_le_bytes(message.payload[..4].try_into().unwrap()); + self.api.set(context); + let mut result = self.login(); + result.push(Message::control(0x30000, Payload::default().u32(context))); + Ok(result) + } + 0x40005 | 0x40007 => Ok(vec![Message::control( + 0x30004 + u32::from(self.api.get() >= 4), + Payload::default(), + )]), + _ => Ok(Vec::new()), + } + } +} + +fn base64(bytes: &[u8]) -> String { + const ALPHABET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + let mut output = String::with_capacity(bytes.len().div_ceil(3) * 4); + for part in bytes.chunks(3) { + let value = ((part[0] as u32) << 16) + | ((part.get(1).copied().unwrap_or(0) as u32) << 8) + | part.get(2).copied().unwrap_or(0) as u32; + output.push(ALPHABET[(value >> 18) as usize] as char); + output.push(ALPHABET[((value >> 12) & 63) as usize] as char); + output.push(if part.len() > 1 { + ALPHABET[((value >> 6) & 63) as usize] as char + } else { + '=' + }); + output.push(if part.len() > 2 { + ALPHABET[(value & 63) as usize] as char + } else { + '=' + }); + } + output +} + +#[cfg(test)] +mod tests { + use super::*; + use std::io::Cursor; + + #[test] + fn app_sync_echoes_challenge_without_inventing_owned_titles() { + let session = Session::new(123, "name".into(), "ticket".into()).unwrap(); + let request = Message::control(0x80000, Payload::default().u64(42)); + let response = session.respond(&request).unwrap().remove(0); + assert_eq!(response.kind, 0x80002); + assert_eq!(&response.payload[..8], &42u64.to_le_bytes()); + assert_eq!(&response.payload[12..], b"BAAAAP///38GAAgAAgAAAAAAAAA="); + assert_eq!(base64(b"f"), "Zg=="); + assert_eq!(base64(b"fo"), "Zm8="); + assert_eq!(base64(b"foo"), "Zm9v"); + assert!(session.with_title("../game".into()).is_err()); + } + + #[test] + fn transport_hello_matches_wire_layout() { + let mut bytes = Vec::new(); + Message::hello(0x1234).write(&mut bytes).unwrap(); + assert_eq!( + bytes, + [4, 0, 0, 0, 254, 255, 255, 255, 255, 255, 0, 0, 2, 0, 0, 0, 52, 18, 0, 0] + ); + } + + #[test] + fn login_preserves_string_lengths_and_alignment() { + let session = Session::new(0x1122334455667788, "a@b".into(), "ticket".into()).unwrap(); + let login = session.login(); + assert_eq!( + login[0].payload, + [3, 0, 0, 0, 136, 119, 102, 85, 68, 51, 34, 17, 0, 0, 0, 0] + ); + assert_eq!( + login[1].payload, + [136, 119, 102, 85, 68, 51, 34, 17, 0, 0, 0, 0, 3, 0, 0, 0, 97, 64, 98] + ); + assert_eq!( + login[2].payload, + [3, 0, 0, 0, 97, 64, 98, 0, 6, 0, 0, 0, 116, 105, 99, 107, 101, 116] + ); + } + + #[test] + fn init_sends_authenticated_state_before_launcher_hello() { + let session = Session::new(123, "name".into(), "ticket".into()).unwrap(); + for (api, expected) in [ + (3, [0x30001, 0x30002, 0x30003, 0x30000]), + (4, [0x30002, 0x30003, 0x30004, 0x30000]), + ] { + let request = Message::control(0x40000, Payload::default().u32(api)); + let result = session.respond(&request).unwrap(); + assert_eq!(result.iter().map(|m| m.kind).collect::>(), expected); + assert_eq!( + result[0].payload, + [3, 0, 0, 0, 123, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + ); + assert_eq!(result[3].payload, api.to_le_bytes()); + } + } + + #[test] + fn malformed_frames_and_sessions_are_rejected() { + assert!(Session::new(0, "name".into(), "ticket".into()).is_err()); + assert!(Session::new(123, "name".into(), "".into()).is_err()); + let session = Session::new(123, "name".into(), "ticket".into()).unwrap(); + assert!(session + .respond(&Message::control(0x40000, Payload::default())) + .is_err()); + assert!(Message::read(&mut Cursor::new(vec![255; 16])).is_err()); + assert!(Message::read(&mut Cursor::new(vec![0; 15])).is_err()); + } + + #[test] + fn concatenated_messages_remain_separate() { + let session = Session::new(123, "name".into(), "ticket".into()).unwrap(); + let mut bytes = Vec::new(); + for message in session.login() { + message.write(&mut bytes).unwrap(); + } + let mut reader = Cursor::new(bytes); + for message in session.login() { + assert_eq!(Message::read(&mut reader).unwrap(), message); + } + } +} diff --git a/tools/tests/test_battlenet.py b/tools/tests/test_battlenet.py index 5f3d72c1b6..ec20e81777 100644 --- a/tools/tests/test_battlenet.py +++ b/tools/tests/test_battlenet.py @@ -198,6 +198,155 @@ class ConfigAndMenuTest(Temp): self.assertEqual(path.stat().st_mtime_ns, mtime) +class DriveTest(Temp): + def setUp(self): + super().setUp() + self.root = str(self.tmp / "Steam") + self.devices = Path(BNET["dosdevices"](self.root)) + self.card = self.tmp / "card" + self.library = self.card / "Games/Battle.net" + self.library.mkdir(parents=True) + self.running = [] + patcher = mock.patch.dict(BNET, {"say": lambda message: None, "wine_processes": lambda pfx, proc="/proc": list(self.running), + "volume_root": lambda path: str(self.card) if BNET["inside"](path, str(self.card)) else "/"}) + patcher.start() + self.addCleanup(patcher.stop) + + def test_a_volume_ends_where_the_device_changes(self): + devices = {"/": 1, "/mnt": 1, "/mnt/card": 7, "/mnt/card/Games": 7, "/mnt/card/Games/Battle.net": 7, "/root": 1, "/root/Games": 1} + with mock.patch.object(os, "stat", lambda path: mock.Mock(st_dev=devices[path])): + volume_root = runpy.run_path(str(BIN / "droiddeck-battlenet"))["volume_root"] + self.assertEqual(volume_root("/mnt/card/Games/Battle.net"), "/mnt/card") + self.assertEqual(volume_root("/mnt/card"), "/mnt/card") + self.assertEqual(volume_root("/root/Games"), "/") + self.assertEqual(volume_root("/"), "/") + + def test_a_library_on_the_root_volume_keeps_its_path_and_gets_no_drive(self): + library = self.tmp / "root/Games/Battle.net" + library.mkdir(parents=True) + self.assertEqual(BNET["install_path"](self.root, str(library) + "/"), "Z:" + str(library)) + self.assertFalse(self.devices.exists()) + + def test_a_library_on_another_volume_gets_a_drive_at_the_volume_root(self): + self.assertEqual(BNET["install_path"](self.root, str(self.library)), "D:\\Games\\Battle.net") + self.assertEqual(os.readlink(self.devices / "d:"), str(self.card)) + self.assertEqual(BNET["install_path"](self.root, str(self.library / "World of Warcraft")), "D:\\Games\\Battle.net\\World of Warcraft") + self.assertEqual(BNET["install_path"](self.root, str(self.card)), "D:\\") + self.assertEqual(sorted(os.listdir(self.devices)), ["d:"]) + + def test_drives_in_use_and_the_ones_proton_owns_are_left_alone(self): + self.devices.mkdir(parents=True) + os.symlink("/somewhere/else", self.devices / "d:") + os.symlink(str(self.card), self.devices / "s:") + self.assertEqual(BNET["install_path"](self.root, str(self.library)), "E:\\Games\\Battle.net") + self.assertEqual(os.readlink(self.devices / "d:"), "/somewhere/else") + for letter in BNET["DRIVES"]: + if not os.path.lexists(self.devices / (letter + ":")): + os.symlink("/somewhere/else", self.devices / (letter + ":")) + os.unlink(self.devices / "e:") + os.symlink("/somewhere/else", self.devices / "e:") + self.assertEqual(BNET["install_path"](self.root, str(self.library)), "Z:" + str(self.library)) + self.assertNotIn("s", BNET["DRIVES"]) + self.assertNotIn("t", BNET["DRIVES"]) + + def test_a_running_prefix_gets_no_new_drive_but_uses_the_ones_it_started_with(self): + self.running = [(5, ["C:\\Program Files (x86)\\Battle.net\\Battle.net.exe"])] + self.assertEqual(BNET["install_path"](self.root, str(self.library)), "Z:" + str(self.library)) + self.assertFalse(self.devices.exists()) + self.running = [] + self.assertEqual(BNET["install_path"](self.root, str(self.library)), "D:\\Games\\Battle.net") + self.running = [(5, ["C:\\Program Files (x86)\\Battle.net\\Battle.net.exe"])] + self.assertEqual(BNET["install_path"](self.root, str(self.library)), "D:\\Games\\Battle.net") + + def test_a_drive_mapped_inside_the_volume_is_reused(self): + self.devices.mkdir(parents=True) + os.symlink(str(self.card / "Games"), self.devices / "g:") + self.assertEqual(BNET["install_path"](self.root, str(self.library)), "G:\\Battle.net") + self.assertEqual(sorted(os.listdir(self.devices)), ["g:"]) + + def test_the_config_stores_the_drive_path_once(self): + path = self.tmp / ("Steam/steamapps/compatdata/%s/pfx/drive_c/users/steamuser/AppData/Roaming/Battle.net/Battle.net.config" + % BNET["APP_ID"]) + BNET["write_config"](self.root) + self.assertEqual(BNET["write_config"](self.root, str(self.library)), "library") + self.assertEqual(json.loads(path.read_text())["Client"]["Install"]["DefaultInstallPath"], "D:\\Games\\Battle.net") + self.assertIsNone(BNET["write_config"](self.root, str(self.library))) + + def test_registered_paths_resolve_through_their_drive(self): + BNET["install_path"](self.root, str(self.library)) + self.assertEqual(BNET["windows_path"](self.root, "D:/Games/Battle.net/World of Warcraft"), + str(self.library / "World of Warcraft")) + self.assertEqual(BNET["windows_path"](self.root, "Z:\\mnt\\card\\World of Warcraft"), "/mnt/card/World of Warcraft") + self.assertEqual(BNET["windows_path"](self.root, "C:/Program Files (x86)/World of Warcraft"), + os.path.join(BNET["drive_c"](self.root), "Program Files (x86)/World of Warcraft")) + self.assertIsNone(BNET["windows_path"](self.root, "E:/Games/X")) + self.assertIsNone(BNET["windows_path"](self.root, "D:/../etc")) + self.assertEqual(BNET["windows_path"](self.root, "D:\\"), str(self.library.parent.parent)) + + def field(self, number, value): + varint = BNET["encode_varint"] + return varint(number << 3 | 2) + varint(len(value)) + value + + def product(self, uid, folder, filler=b""): + settings = self.field(1, folder.encode()) + self.field(2, b"us") + b"\x18\x02" + filler + return self.field(1, self.field(1, uid.encode()) + self.field(2, uid.encode()) + self.field(3, settings) + + b"\x21" + bytes(8) + b"\x2d" + bytes(4)) + + def database(self, *products): + path = Path(BNET["drive_c"](self.root)) / "ProgramData/Battle.net/Agent/product.db" + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(b"".join(products) + self.field(7, b"tail")) + path.chmod(0o600) + return path + + def test_games_registered_through_the_root_drive_move_to_their_volume_drive(self): + game = self.library / "World of Warcraft" + game.mkdir() + other = self.tmp / "root/Games/Other" + other.mkdir(parents=True) + client = self.product("battle.net", "C:/Program Files (x86)/Battle.net") + local = self.product("other", "Z:" + str(other)) + gone = self.product("gone", "Z:" + str(self.card / "Missing")) + path = self.database(client, self.product("wow", "Z:" + str(game), bytes(200)), local, gone) + self.assertTrue(BNET["move_installs"](self.root)) + self.assertEqual(path.read_bytes(), client + self.product("wow", "D:/Games/Battle.net/World of Warcraft", bytes(200)) + + local + gone + self.field(7, b"tail")) + self.assertEqual(path.stat().st_mode & 0o777, 0o600) + self.assertEqual(os.readlink(self.devices / "d:"), str(self.card)) + self.assertFalse(BNET["move_installs"](self.root)) + + def test_registrations_stay_while_the_prefix_runs_or_the_database_is_unreadable(self): + game = self.library / "World of Warcraft" + game.mkdir() + path = self.database(self.product("wow", "Z:" + str(game))) + before = path.read_bytes() + self.running = [(5, ["C:\\ProgramData\\Battle.net\\Agent\\Agent.exe"])] + self.assertFalse(BNET["move_installs"](self.root)) + self.assertEqual(path.read_bytes(), before) + self.running = [] + for broken in (before[:-3], b"\x0a\xff", b"\x0b\x01"): + path.write_bytes(broken) + self.assertFalse(BNET["move_installs"](self.root)) + self.assertEqual(path.read_bytes(), broken) + os.unlink(path) + self.assertFalse(BNET["move_installs"](self.root)) + + def test_a_database_written_while_it_was_being_read_is_left_as_written(self): + game = self.library / "World of Warcraft" + game.mkdir() + path = self.database(self.product("wow", "Z:" + str(game))) + newer = path.read_bytes() + self.field(7, b"newer") + + def processes(pfx, proc="/proc"): + path.write_bytes(newer) + return [] + + with mock.patch.dict(BNET, {"wine_processes": processes}): + self.assertFalse(BNET["move_installs"](self.root)) + self.assertEqual(path.read_bytes(), newer) + self.assertTrue(BNET["move_installs"](self.root)) + + class GamepadTest(Temp): def registry(self, *entries): rows = ["WINE REGISTRY Version 2"] @@ -772,7 +921,7 @@ class Harness(Temp): "stop": lambda processes, wait=0: self.calls.append(("stop", sorted(pid for pid, _ in processes))), "start": lambda exe, verb=None: self.calls.append(("start", os.path.basename(exe), verb)) or self.Proton(), "spawn": lambda program, verb, args=(): self.calls.append(("spawn", os.path.basename(program), verb, list(args))), - "acquire": lambda folder=None: self.lock, + "acquire": lambda folder=None: self.lock, "volume_root": lambda path: "/", "POLL": 0, "READY_SETTLE": 0, "GAME_GRACE": 0, "CLIENT_WAIT": 0, }) patcher.start() @@ -1170,6 +1319,7 @@ class AgentTest(Temp): script = BNET["AGENT_SCRIPT"] self.assertIn("port = a(0), action = a(1), uid = a(2), product = a(3), dir = a(4)", script) self.assertIn("lang = a(5), country = a(6), region = a(7), out = a(8)", script) + self.assertIn(r'''"game_dir":"' + dir.replace(/\\/g, "\\\\").replace(/"/g, '\\"') + '","geo''', script) self.assertIn('"--internalclienttools"', (BIN / "droiddeck-battlenet").read_text()) def test_the_driver_asks_blizzards_chinese_repository_for_chinese_installs(self): @@ -1230,6 +1380,40 @@ class AgentJobTest(Harness): self.assertEqual([kind for kind, _ in self.lines], ["STATE", "PROGRESS", "DONE"]) self.assertEqual(json.loads(self.lines[-1][1]), {"install_dir": "Z:" + folder, "exe": "WarcraftRumble.exe", "version": "16.1.2.119725"}) + def test_an_install_on_another_volume_is_handed_over_by_its_drive_once_the_prefix_is_stopped(self): + self.install() + card = self.tmp / "card" + folder = str(card / "Games/Battle.net/Warcraft Rumble") + self.files = {".json": json.dumps({"progress": 1.0, "download_complete": True, "state": 1004}), + ".game": json.dumps({"installed": True, "install_dir": "D:/Games/Battle.net/Warcraft Rumble", "local_version": "1", + "binaries": {"game": {"relative_path": "WarcraftRumble.exe"}}})} + self.states = [[(7, self.AGENT)]] + events = [] + real_map = BNET["map_drive"] + + def acquire(folder=None): + events.append("lock") + return self.lock + + def stop(pfx): + events.append(("stop", not self.lock.closed)) + self.states = [[]] + return True + + def map_drive(root, volume): + events.append(("map", not self.lock.closed)) + return real_map(root, volume) + + with mock.patch.dict(BNET, {"volume_root": lambda path: str(card), "stop_leftovers": stop, "map_drive": map_drive, + "acquire": acquire}): + code = BNET["agent_job"](self.root, "install", "gryphon", "gryphon", folder, "enUS", "USA", "US", poll=0) + self.assertEqual(code, 0) + self.assertEqual(events, ["lock", ("stop", True), ("map", True)]) + self.assertTrue(self.lock.closed) + cmd = self.started[0] + self.assertEqual(cmd[cmd.index("--") + 6], "D:\\Games\\Battle.net\\Warcraft Rumble") + self.assertEqual(os.readlink(os.path.join(BNET["dosdevices"](self.root), "d:")), str(card)) + def test_an_agent_error_is_reported_with_its_code(self): self.install() self.files = {".json": json.dumps({"error": 2421, "progress": 0.0})} diff --git a/tools/tests/test_client_zram_focus.py b/tools/tests/test_client_zram_focus.py index 5cd7d3cd4a..db2d3f80e1 100644 --- a/tools/tests/test_client_zram_focus.py +++ b/tools/tests/test_client_zram_focus.py @@ -121,6 +121,7 @@ step() { :; } bl_zram_scan() { :; } bl_memory_read() { :; } bl_client_pressure() { :; } +bl_client_pressure_finish() { :; } bl_session_pressure() { :; } bl_client_can_pageout() { return 0; } bl_client_can_readback() { [ "${readback:-1}" = 1 ]; } diff --git a/tools/tests/test_clock_pause_preload.py b/tools/tests/test_clock_pause_preload.py index 6523811125..06ddd65a49 100644 --- a/tools/tests/test_clock_pause_preload.py +++ b/tools/tests/test_clock_pause_preload.py @@ -1,19 +1,34 @@ import os from pathlib import Path +import queue +import re +import shlex import shutil import struct import subprocess import tempfile +import threading import unittest PRELOAD = Path(__file__).resolve().parents[1] / "linuxfs/preload" + +def clock_reset_command(control): + script = (PRELOAD.parent / "overlay/usr/local/bin/droiddeck-session").read_text() + start = script.index('if [ -z "${BL_INSIDE:-}" ]; then\n if [ "${BL_ZRAM:-0}"') + end = script.index("\nfi", start) + len("\nfi") + paths = {"/tmp/.bl-clock": shlex.quote(str(control)), + "/tmp/.bl-zram": shlex.quote(str(control.parent / "zram"))} + pattern = "|".join(re.escape(token) for token in paths) + return 'BL_INSIDE=; BL_ZRAM=0; ' + re.sub(pattern, lambda match: paths[match.group(0)], script[start:end]) + PROGRAM = r""" #define _GNU_SOURCE #include #include #include #include +#include #include #include #include @@ -36,12 +51,26 @@ static int64_t start; static void begin(void) { start = ns(CLOCK_BOOTTIME); } static void end(const char *name) { printf("%s %lld\n", name, (long long)((ns(CLOCK_BOOTTIME) - start) / 1000000LL)); } +static unsigned long long memory_probe(void) { + static volatile unsigned char memory[4 * 1024 * 1024]; + unsigned long long checksum = 0; + for (size_t i = 0; i < sizeof(memory); i += 4096) memory[i] = (unsigned char)(i / 4096 + 1); + for (size_t i = 0; i < sizeof(memory); i += 4096) checksum += memory[i]; + return checksum; +} + int main(void) { const int64_t wait = 60000000LL; printf("gap %lld\n", (long long)((ns(CLOCK_BOOTTIME) - ns(CLOCK_MONOTONIC)) / 1000000LL)); struct timespec raw; syscall(SYS_clock_gettime, CLOCK_MONOTONIC, &raw); printf("rawgap %lld\n", (long long)((ns(CLOCK_BOOTTIME) - ((int64_t)raw.tv_sec * 1000000000LL + raw.tv_nsec)) / 1000000LL)); + printf("memory %llu\n", memory_probe()); + if (getenv("CLOCK_PAUSE_WAIT")) { puts("ready"); fflush(stdout); getchar(); } + if (getenv("CLOCK_PAUSE_WAIT")) { + printf("livegap %lld\n", (long long)((ns(CLOCK_BOOTTIME) - ns(CLOCK_MONOTONIC)) / 1000000LL)); + printf("livememory %llu\n", memory_probe()); + } pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_condattr_t attr; @@ -124,14 +153,124 @@ class ClockPausePreloadTest(unittest.TestCase): self.assertGreaterEqual(paused[name], 50, name) self.assertLess(paused[name], 1000, name) - def test_other_programs_keep_the_real_clock(self): + def test_program_without_preload_keeps_the_real_clock(self): plain = self.run_program(self.other, 0, preload=False) - paused = self.run_program(self.other, SHIFT_MS) + paused = self.run_program(self.other, SHIFT_MS, preload=False) self.assertAlmostEqual(paused["gap"], plain["gap"], delta=50) for name in ("cond_mono", "clockwait", "sem", "nanosleep", "timerfd", "futex"): self.assertGreaterEqual(paused[name], 50, name) self.assertLess(paused[name], 1000, name) + def test_every_session_program_stops_monotonic_clock_and_keeps_memory_access(self): + plain = self.run_program(self.other, 0) + paused = self.run_program(self.other, SHIFT_MS) + self.assertAlmostEqual(paused["gap"] - plain["gap"], SHIFT_MS, delta=50) + self.assertAlmostEqual(paused["rawgap"] - plain["rawgap"], SHIFT_MS, delta=50) + self.assertEqual(plain["memory"], 130560) + self.assertEqual(paused["memory"], 130560) + + def test_running_session_program_observes_pause_offset_update(self): + self.check_running_offset_update(False) + + def test_session_reset_preserves_live_guest_mapping(self): + self.check_running_offset_update(True) + + def check_running_offset_update(self, reset): + self.control.write_bytes(struct.pack(" "$HOME/selected-package"\nexit 1\n') + for tool in bin_dir.iterdir(): + tool.chmod(0o755) + env.pop('DROIDDECK_PACKAGE') + env['DD_LAB_DETACHED'] = '1' + env['PATH'] = str(bin_dir) + os.pathsep + env['PATH'] + result = subprocess.run(['bash', str(SCRIPT), *payload['args']], env=env, + capture_output=True, text=True, timeout=10, cwd=SCRIPT.parents[2]) + self.assertNotEqual(0, result.returncode) + self.assertIn('could not read DroidDeck', result.stderr) + self.assertEqual('com.example.target', (root / 'selected-package').read_text()) + + def test_invalid_packages_are_rejected_before_handoff(self): + with tempfile.TemporaryDirectory() as tmp: + inbox = Path(tmp) / 'agent' + inbox.mkdir() + for package in ('bad;touch injected', '../other', '', 'com.example/other'): + with self.subTest(package=package): + env = {**os.environ, 'HOME': tmp, 'DD_AGENT': '1', 'DD_AGENT_INBOX': str(inbox)} + result = subprocess.run(['bash', str(SCRIPT), '--package=' + package], env=env, + capture_output=True, text=True, timeout=10) + self.assertNotEqual(0, result.returncode) + self.assertIn('invalid Android package', result.stderr) + self.assertFalse((inbox / 'lab-request').exists()) diff --git a/tools/tests/test_descriptor_preload.py b/tools/tests/test_descriptor_preload.py new file mode 100644 index 0000000000..f83df2e9b2 --- /dev/null +++ b/tools/tests/test_descriptor_preload.py @@ -0,0 +1,245 @@ +import os +from pathlib import Path +import shutil +import subprocess +import tempfile +import unittest + +PRELOAD = Path(__file__).resolve().parents[1] / "linuxfs/preload" + +FAKE = r""" +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include + +static int answer(int fd) { + char link[32], path[4096]; + snprintf(link, sizeof(link), "/proc/self/fd/%d", fd); + long n = syscall(SYS_readlinkat, AT_FDCWD, link, path, sizeof(path) - 1); + path[n > 0 ? n : 0] = '\0'; + if (strstr(path, "/card/")) return ENOTSUP; + if (strstr(path, "/denied/")) return EACCES; + return ENODATA; +} + +ssize_t fgetxattr(int fd, const char *name, void *value, size_t size) { + (void)name; (void)value; (void)size; + errno = answer(fd); + return -1; +} + +int fsetxattr(int fd, const char *name, const void *value, size_t size, int flags) { + (void)name; (void)value; (void)size; (void)flags; + int error = answer(fd); + if (error == ENODATA) return 0; + errno = error; + return -1; +} + +int fremovexattr(int fd, const char *name) { + (void)name; + errno = answer(fd); + return -1; +} +""" + +PROGRAM = r""" +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include + +static const char *error(void) { + return errno == ENOTSUP ? "unsupported" : errno == ENODATA ? "none" : errno == ERANGE ? "range" : + errno == EACCES ? "denied" : "other"; +} + +int main(int argc, char **argv) { + for (int i = 1; i < argc; i++) { + const char *op = argv[i]; + if (!strcmp(op, "unlink") || !strcmp(op, "rmdir")) { + const char *path = argv[++i]; + printf("%s\n", (op[0] == 'u' ? unlink(path) : rmdir(path)) == 0 ? "ok" : "failed"); + continue; + } + if (!strcmp(op, "remove-path")) { + printf("%s\n", remove(argv[++i]) == 0 ? "ok" : "failed"); + continue; + } + if (!strcmp(op, "rename")) { + const char *from = argv[++i], *to = argv[++i]; + printf("%s\n", rename(from, to) == 0 ? "ok" : "failed"); + continue; + } + int fd = open(argv[++i], O_RDONLY); + char value[64]; + if (!strcmp(op, "set")) { + const char *text = argv[++i]; + errno = 1234; + int result = fsetxattr(fd, "user.wine.sd", text, strlen(text), 0); + printf("%s\n", result == 0 ? errno == 1234 ? "ok" : "errno" : error()); + } else if (!strcmp(op, "get")) { + ssize_t n = fgetxattr(fd, "user.wine.sd", value, sizeof(value)); + if (n < 0) printf("%s\n", error()); + else printf("=%.*s\n", (int)n, value); + } else if (!strcmp(op, "size")) { + ssize_t n = fgetxattr(fd, "user.wine.sd", NULL, 0); + if (n < 0) printf("%s\n", error()); + else printf("%d\n", (int)n); + } else if (!strcmp(op, "short")) { + ssize_t n = fgetxattr(fd, "user.wine.sd", value, 2); + printf("%s\n", n < 0 ? error() : "read"); + } else if (!strcmp(op, "remove")) { + errno = 1234; + int result = fremovexattr(fd, "user.wine.sd"); + printf("%s\n", result == 0 ? errno == 1234 ? "ok" : "errno" : error()); + } else if (!strcmp(op, "other")) { + ssize_t n = fgetxattr(fd, "user.other", value, sizeof(value)); + printf("%s\n", n < 0 ? error() : "read"); + } + close(fd); + } + return 0; +} +""" + + +@unittest.skipUnless(shutil.which("cc"), "needs a C compiler") +class DescriptorPreloadTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.build_dir = tempfile.TemporaryDirectory() + build = Path(cls.build_dir.name) + (build / "fake.c").write_text(FAKE) + (build / "program.c").write_text(PROGRAM) + cls.preload = build / "libblsession.so" + cls.fake = build / "fake.so" + subprocess.run(["cc", "-shared", "-fPIC", "-O2", "-Wall", "-pthread", "-o", str(cls.preload), + *map(str, sorted(PRELOAD.glob("*.c"))), "-ldl"], check=True) + subprocess.run(["cc", "-shared", "-fPIC", "-O2", "-o", str(cls.fake), str(build / "fake.c")], check=True) + cls.wineserver = build / "wineserver" + subprocess.run(["cc", "-O2", "-o", str(cls.wineserver), str(build / "program.c")], check=True) + cls.other = build / "wine64-preloader" + shutil.copy(cls.wineserver, cls.other) + + @classmethod + def tearDownClass(cls): + cls.build_dir.cleanup() + + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.dir = Path(os.path.realpath(self.temp.name)) + self.prefix = self.dir / "prefix" + self.prefix.mkdir() + self.store = self.prefix / ".droiddeck-descriptors" + for kind in ("card", "disk", "denied"): + (self.dir / kind / "game").mkdir(parents=True) + (self.dir / kind / "game" / "file").write_text("x") + + def tearDown(self): + self.temp.cleanup() + + def path(self, *parts): + return str(self.dir.joinpath(*parts)) + + def run_as(self, program, *args, prefix=True): + env = dict(os.environ, LD_PRELOAD="%s:%s" % (self.preload, self.fake)) + env.pop("WINEPREFIX", None) + if prefix: + env["WINEPREFIX"] = str(self.prefix) + result = subprocess.run([str(program), *args], env=env, capture_output=True, text=True, check=True) + return result.stdout.split() + + def server(self, *args, **kwargs): + return self.run_as(self.wineserver, *args, **kwargs) + + def test_a_descriptor_is_kept_where_the_volume_cannot_store_it(self): + file, folder = self.path("card", "game", "file"), self.path("card", "game") + self.assertEqual(["none", "ok", "ok"], self.server("get", file, "set", file, "one", "set", folder, "two")) + self.assertEqual(["=one", "3", "=two"], self.server("get", file, "size", file, "get", folder)) + + def test_a_descriptor_is_replaced_and_removed(self): + file = self.path("card", "game", "file") + self.assertEqual(["ok", "ok", "=longer"], self.server("set", file, "one", "set", file, "longer", "get", file)) + self.assertEqual(["range", "ok", "none", "none"], self.server("short", file, "remove", file, "get", file, "remove", file)) + + def test_a_volume_that_stores_descriptors_is_left_alone(self): + file = self.path("disk", "game", "file") + self.assertEqual(["ok", "none", "none"], self.server("set", file, "one", "get", file, "remove", file)) + self.assertFalse(self.store.exists()) + + def test_other_failures_keep_their_error(self): + file = self.path("denied", "game", "file") + self.assertEqual(["denied", "denied", "denied"], self.server("set", file, "one", "get", file, "remove", file)) + self.assertFalse(self.store.exists()) + + def test_other_programs_and_other_attributes_are_unchanged(self): + file = self.path("card", "game", "file") + self.assertEqual(["unsupported", "unsupported", "unsupported"], + self.run_as(self.other, "set", file, "one", "get", file, "remove", file)) + self.assertEqual(["ok", "unsupported"], self.server("set", file, "one", "other", file)) + self.assertEqual(["unsupported"], self.run_as(self.other, "get", file)) + + def test_nothing_is_kept_without_a_prefix(self): + file = self.path("card", "game", "file") + self.assertEqual(["unsupported", "unsupported", "unsupported"], + self.server("set", file, "one", "get", file, "remove", file, prefix=False)) + + def test_a_deleted_file_loses_its_descriptor(self): + file, folder = self.path("card", "game", "file"), self.path("card", "game") + self.assertEqual(["ok", "ok", "ok"], self.server("set", file, "one", "set", folder, "two", "unlink", file)) + Path(file).write_text("x") + self.assertEqual(["none", "ok", "ok"], self.server("get", file, "unlink", file, "rmdir", folder)) + Path(folder).mkdir() + self.assertEqual(["none"], self.server("get", folder)) + + def test_a_removed_file_or_folder_loses_its_descriptor(self): + file, folder = self.path("card", "game", "file"), self.path("card", "game") + self.assertEqual(["ok", "ok", "ok", "ok"], + self.server("set", file, "one", "set", folder, "two", "remove-path", file, "remove-path", folder)) + Path(folder).mkdir() + Path(file).write_text("x") + self.assertEqual(["none", "none"], self.server("get", folder, "get", file)) + + def test_a_file_deleted_through_a_link_loses_its_descriptor(self): + file = self.path("card", "game", "file") + os.symlink(self.path("card"), self.path("drive")) + self.assertEqual(["ok", "ok"], self.server("set", file, "one", "unlink", self.path("drive", "game", "file"))) + Path(file).write_text("x") + self.assertEqual(["none"], self.server("get", file)) + + def test_a_descriptor_follows_a_rename(self): + file, moved = self.path("card", "game", "file"), self.path("card", "game", "moved") + self.assertEqual(["ok", "ok", "=one"], self.server("set", file, "one", "rename", file, moved, "get", moved)) + Path(file).write_text("x") + self.assertEqual(["none", "ok", "none"], self.server("get", file, "rename", file, moved, "get", moved)) + + def test_descriptors_follow_a_renamed_folder(self): + file, folder, moved = self.path("card", "game", "file"), self.path("card", "game"), self.path("card", "moved") + self.assertEqual(["ok", "ok", "ok"], self.server("set", file, "one", "set", folder, "two", "rename", folder, moved)) + self.assertEqual(["=two", "=one"], self.server("get", moved, "get", self.path("card", "moved", "file"))) + Path(folder).mkdir() + (Path(folder) / "file").write_text("x") + self.assertEqual(["none", "none"], self.server("get", folder, "get", file)) + + def test_deletes_outside_the_store_cost_nothing_before_it_exists(self): + file = self.path("disk", "game", "file") + self.assertEqual(["ok"], self.server("unlink", file)) + self.assertFalse(self.store.exists()) + + def test_a_name_too_long_to_keep_reports_no_support(self): + long_file = self.path("card", "game", "n" * 254) + Path(long_file).write_text("x") + self.assertEqual(["unsupported", "unsupported"], self.server("set", long_file, "one", "get", long_file)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_desktop_open.py b/tools/tests/test_desktop_open.py index c32baf71a6..a7840cfa53 100644 --- a/tools/tests/test_desktop_open.py +++ b/tools/tests/test_desktop_open.py @@ -136,6 +136,30 @@ class CommandTest(Temp): self.assertEqual(OPEN["command"](script, [], "x86 script")[0], [OPEN["FEX"], "run", "--mode", "on", "--for", str(self.tmp), "--", "/bin/sh", script]) + def test_a_store_games_exe_runs_through_its_launcher(self): + exe, launcher = str(self.tmp / "game.exe"), str(self.tmp / "launch.bat") + with mock.patch.dict(OPEN, {"store_launcher": lambda path: launcher if path == exe else None, + "exe_prefix": lambda path: ["--prefix", "4242", "--compatdata", "/c/4242"]}): + keep = ["--prefix", "4242", "--compatdata", "/c/4242"] + self.assertEqual(OPEN["command"](exe, [], "windows")[0], [OPEN["PROTON_RUN"]] + keep + [launcher]) + self.assertEqual(OPEN["command"](exe, [], "windows", True)[0], + [OPEN["PROTON_RUN"], "--window"] + keep + [launcher]) + self.assertEqual(OPEN["command"](exe, ["-x"], "windows")[0], [OPEN["PROTON_RUN"], exe, "-x"]) + other = str(self.tmp / "other.exe") + self.assertEqual(OPEN["command"](other, [], "windows")[0], [OPEN["PROTON_RUN"], other]) + + def test_a_store_games_launcher_keeps_the_exes_prefix(self): + exe = self.tmp / "game.exe" + exe.write_text("x") + root = str(self.tmp / "steam") + with mock.patch.dict(os.environ, {"STEAM_COMPAT_CLIENT_INSTALL_PATH": root}), \ + mock.patch.dict(OPEN, {"PROTON_RUN": str(BIN / "droiddeck-proton-run"), + "store_launcher": lambda path: str(self.tmp / "launch.bat")}): + command = OPEN["command"](str(exe), [], "windows")[0] + located = RUN["locate"](str(exe), root) + self.assertEqual(command[1:5], ["--prefix", located.appid, "--compatdata", located.compatdata]) + self.assertEqual(str(RUN["own_id"](str(exe))), str(RUN["locate"](str(exe), root).appid)) + def test_a_native_program_on_noexec_storage_runs_from_a_copy(self): program = self.write("storage/tool", elf(183)) x86 = self.write("storage/game.x86_64", elf(62)) @@ -737,6 +761,20 @@ class ProtonRunTest(Temp): self.assertEqual(env["STEAM_COMPAT_DATA_PATH"], str(signed)) self.assertFalse((self.root / "steamapps/compatdata/2733369024").exists()) + def test_a_launcher_run_keeps_the_resolved_compatdata_folder(self): + bat = self.write("Games/Epic/Game/.droiddeck-launch.bat", b"@echo off") + signed = self.root / "steamapps/compatdata/-1561598272" + signed.mkdir(parents=True) + other = self.tmp / "Library2/steamapps/compatdata/555" + other.mkdir(parents=True) + for compatdata, appid in ((signed, "2733369024"), (other, "555")): + with self.subTest(compatdata=str(compatdata)): + code, calls, dirs = self.run_main(["--prefix", appid, "--compatdata", str(compatdata), str(bat)]) + self.assertIsNone(code) + self.assertEqual(calls[0][2]["STEAM_COMPAT_DATA_PATH"], str(compatdata)) + code, calls, dirs = self.run_main(["--prefix", "555", str(bat)]) + self.assertEqual(calls[0][2]["STEAM_COMPAT_DATA_PATH"], str(self.root / "steamapps/compatdata/555")) + def test_prefix_folder_prefers_initialized_unsigned_over_empty_signed(self): signed = self.root / "steamapps/compatdata/-1561598272" signed.mkdir(parents=True) diff --git a/tools/tests/test_dircache_preload.py b/tools/tests/test_dircache_preload.py index 42db6817ce..f7b2d9008a 100644 --- a/tools/tests/test_dircache_preload.py +++ b/tools/tests/test_dircache_preload.py @@ -83,9 +83,25 @@ int inotify_add_watch(int fd, const char *path, uint32_t mask) { errno = ENOSPC; return -1; } + if (getenv("NESTED") && (mask & IN_ONLYDIR)) { + static DIR *(*uncounted)(const char *); + if (!uncounted) uncounted = dlsym(RTLD_NEXT, "opendir"); + mkdir(path, 0755); + DIR *d = uncounted("/proc/self/fd"); + while (d && readdir(d)) {} + if (d) closedir(d); + } return next(fd, path, mask); } +int remove(const char *path) { + static int (*next)(const char *); + if (!next) next = dlsym(RTLD_NEXT, "remove"); + if (!getenv("NESTED")) return next(path); + if (unlink(path) == 0) return 0; + return errno == EISDIR ? rmdir(path) : -1; +} + int statfs(const char *path, struct statfs *out) { static int (*next)(const char *, struct statfs *); if (!next) next = dlsym(RTLD_NEXT, "statfs"); @@ -337,9 +353,9 @@ class DirCachePreloadTest(unittest.TestCase): environment.update(env or {}) return environment - def run_program(self, *args, program=None, env=None): + def run_program(self, *args, program=None, env=None, timeout=60): result = subprocess.run([str(program or self.steam), *map(str, args)], env=self.environment(env), - capture_output=True, text=True, check=True, timeout=60) + capture_output=True, text=True, check=True, timeout=timeout) return result.stdout.splitlines() def run_paused(self, *args, between, env=None): @@ -675,6 +691,20 @@ class DirCachePreloadTest(unittest.TestCase): env={"BL_NO_DIR_CACHE": "1"}) self.assertEqual(["-1 2", "-1 2", "2"], out[1:]) + def test_a_preload_below_calling_back_while_a_folder_is_watched_does_not_hang(self): + common = self.lib / "common/Game" + common.mkdir(parents=True) + (common / "game.exe").touch() + out = self.run_program("list", self.staging, "list", common, "list", common, "opens", + env={"NESTED": "1"}, timeout=20) + self.assertEqual(["a.bundle,b.bundle", "game.exe", "game.exe", "2"], out) + + def test_a_preload_below_removing_through_unlink_does_not_hang(self): + s = self.staging + out = self.run_program("list", s, "remove", s / "a.bundle", "list", s, "raw", s, "opens", + env={"NESTED": "1"}, timeout=20) + self.assertEqual(["a.bundle,b.bundle", "b.bundle", "b.bundle", "1"], out) + def test_can_be_turned_off(self): out = self.run_program("list", self.staging, "list", self.staging, "opens", env={"BL_NO_DIR_CACHE": "1"}) self.assertEqual("2", out[-1]) diff --git a/tools/tests/test_droiddeckctl.py b/tools/tests/test_droiddeckctl.py index ab929de931..1f7e32cdff 100644 --- a/tools/tests/test_droiddeckctl.py +++ b/tools/tests/test_droiddeckctl.py @@ -303,7 +303,7 @@ class DroiddeckctlTest(FakeAdbTest): code, out = self.run_ctl("run", "/usr/bin/sh", "--", "-c", "true") self.assertEqual(7, code) self.assertEqual("AGENT_COMMANDS_DISABLED", out["error"]["code"]) - self.assertIn("Setup > Diagnostics > Debugging tools", out["error"]["message"]) + self.assertIn("Setup > Developer > Debugging tools", out["error"]["message"]) self.assertEqual(["access"], [c.get("method") for c in self.calls()]) def test_override_checks_names_before_pushing_any_file(self): diff --git a/tools/tests/test_fastpath_fuse_dirs.py b/tools/tests/test_fastpath_fuse_dirs.py new file mode 100644 index 0000000000..b8b45f851a --- /dev/null +++ b/tools/tests/test_fastpath_fuse_dirs.py @@ -0,0 +1,314 @@ +import os +from pathlib import Path +import shutil +import subprocess +import tempfile +import unittest + +USERNS = shutil.which("unshare") is not None and subprocess.run(["unshare", "-Urm", "true"], capture_output=True).returncode == 0 + +FASTPATH = Path(__file__).resolve().parents[1] / "proot/fastpath/fastpath.c" + +PROGRAM = r""" +#include "FASTPATH" +#include + +static const char *race_from, *race_to; +static dev_t race_dev; +static ino_t race_ino; + +static long trapped_nr = -1, unsupported_nr = -1; + +static long host_sys(long nr, long a, long b, long c, long d, long e, long f) { + if (nr == trapped_nr || (nr == unsupported_nr && a != -1)) return -ENOSYS; + long r = syscall(nr, a, b, c, d, e, f); + struct stat fs; + if (r >= 0 && nr == SYS_fcntl && b == F_DUPFD_CLOEXEC && c == DIR_FD_FLOOR && race_from + && syscall(SYS_fstat, a, &fs) == 0 && fs.st_dev == race_dev && fs.st_ino == race_ino) { + syscall(SYS_renameat, AT_FDCWD, race_from, AT_FDCWD, race_to); + race_from = NULL; + } + return r < 0 ? -errno : r; +} + +static void show(long r) { + if (r == FP_SLOW) puts("SLOW"); + else if (r < 0) printf("E%ld\n", -r); + else puts("ok"); +} + +static int high_fds(void) { + int n = 0; + for (int fd = DIR_FD_FLOOR; fd < DIR_FD_FLOOR + 4 * DIRS; fd++) + if (fcntl(fd, F_GETFD) >= 0) n++; + return n; +} + +int main(int argc, char **argv) { + static char hosts[MAX_BINDS][PATH_MAX], guests[MAX_BINDS][512]; + static int taken[DIRS]; + int ntaken = 0; + fp_sys = host_sys; + snprintf(root, sizeof root, "%s", argv[1]); + rootlen = strlen(root); + int i = 2; + for (; i + 1 < argc && strcmp(argv[i], "--"); i += 2) { + struct bind *bd = &binds[nbinds]; + bd->host = hosts[nbinds]; + bd->guest = guests[nbinds]; + snprintf(bd->host, PATH_MAX, "%s", argv[i]); + snprintf(bd->guest, sizeof guests[0], "%s", argv[i + 1]); + bd->hlen = strlen(bd->host); + bd->glen = strlen(bd->guest); + nbinds++; + } + pthread_once(&init_once, fp_init); + fp_on = 1; + for (i++; i < argc; i++) { + const char *op = argv[i]; + if (!strcmp(op, "fuse")) { + for (int b = 0; b < nbinds; b++) binds[b].fuse = 1; + } else if (!strcmp(op, "touch")) { + long fd = fp_open(AT_FDCWD, argv[++i], O_CREAT | O_WRONLY | O_CLOEXEC, 0644); + if (fd >= 0) close((int)fd); + show(fd); + } else if (!strcmp(op, "stat")) { + struct stat st; + show(fp_stat(AT_FDCWD, argv[++i], AT_SYMLINK_NOFOLLOW, &st)); + } else if (!strcmp(op, "symlink")) { + long r = fp_symlink("target", AT_FDCWD, argv[++i]); + if (refused()) puts("REFUSED"); + else show(r); + } else if (!strcmp(op, "trap-symlink")) { + trapped_nr = SYS_symlinkat; + } else if (!strcmp(op, "no-symlinks")) { + unsupported_nr = SYS_symlinkat; + } else if (!strcmp(op, "on")) { + printf("%d\n", fp_ready()); + } else if (!strcmp(op, "no-folders")) { + unsupported_nr = SYS_mkdirat; + } else if (!strcmp(op, "busy-cache")) { + pthread_mutex_lock(&dir_lock); + } else if (!strcmp(op, "mkdir")) { + long r = fp_mkdir(AT_FDCWD, argv[++i], 0755); + if (refused()) puts("REFUSED"); + else show(r); + } else if (!strcmp(op, "mv")) { + show(fp_rename(AT_FDCWD, argv[i + 1], AT_FDCWD, argv[i + 2], 0)); + i += 2; + } else if (!strcmp(op, "rm")) { + show(fp_unlink(AT_FDCWD, argv[++i], 0)); + } else if (!strcmp(op, "host-mv")) { + show(host_sys(SYS_renameat, AT_FDCWD, (long)argv[i + 1], AT_FDCWD, (long)argv[i + 2], 0, 0)); + i += 2; + } else if (!strcmp(op, "race-mv")) { + struct stat rs; + race_from = argv[i + 1]; + race_to = argv[i + 2]; + i += 2; + show(host_sys(SYS_newfstatat, AT_FDCWD, (long)race_from, (long)&rs, 0, 0, 0)); + race_dev = rs.st_dev; + race_ino = rs.st_ino; + } else if (!strcmp(op, "host-rmdir")) { + show(host_sys(SYS_unlinkat, AT_FDCWD, (long)argv[++i], AT_REMOVEDIR, 0, 0, 0)); + } else if (!strcmp(op, "host-mkdir")) { + show(host_sys(SYS_mkdirat, AT_FDCWD, (long)argv[++i], 0755, 0, 0, 0)); + } else if (!strcmp(op, "clobber")) { + long null = host_sys(SYS_openat, AT_FDCWD, (long)"/dev/null", O_RDONLY, 0, 0, 0); + for (int fd = DIR_FD_FLOOR; fd < DIR_FD_FLOOR + DIRS; fd++) host_sys(SYS_dup3, null, fd, 0, 0, 0, 0); + host_sys(SYS_close, null, 0, 0, 0, 0, 0); + puts("ok"); + } else if (!strcmp(op, "first-fd")) { + char link[40], out[PATH_MAX]; + snprintf(link, sizeof link, "/proc/self/fd/%d", DIR_FD_FLOOR); + long n = host_sys(SYS_readlinkat, AT_FDCWD, (long)link, (long)out, sizeof out - 1, 0, 0); + out[n > 0 ? n : 0] = 0; + puts(out); + } else if (!strcmp(op, "fds")) { + printf("%d\n", high_fds()); + } else if (!strcmp(op, "ttl")) { + ttl_ns = atoll(argv[++i]) * 1000000LL; + } else if (!strcmp(op, "sleep")) { + usleep(atoi(argv[++i]) * 1000); + } else if (!strcmp(op, "chmod")) { + show(fp_chmod(AT_FDCWD, argv[i + 1], strtol(argv[i + 2], NULL, 8), 0)); + i += 2; + } else if (!strcmp(op, "host-mount")) { + show(mount("tmpfs", argv[++i], "tmpfs", 0, NULL) == 0 ? 0 : -errno); + } else if (!strcmp(op, "take-over")) { + for (int fd = DIR_FD_FLOOR; fd < DIR_FD_FLOOR + DIRS; fd++) { + char link[40], out[PATH_MAX]; + snprintf(link, sizeof link, "/proc/self/fd/%d", fd); + long n = host_sys(SYS_readlinkat, AT_FDCWD, (long)link, (long)out, sizeof out - 1, 0, 0); + if (n <= 0) continue; + out[n] = 0; + long mine = host_sys(SYS_openat, AT_FDCWD, (long)out, O_RDONLY | O_DIRECTORY, 0, 0, 0); + host_sys(SYS_dup3, mine, fd, 0, 0, 0, 0); + host_sys(SYS_close, mine, 0, 0, 0, 0, 0); + taken[ntaken++] = fd; + } + puts("ok"); + } else if (!strcmp(op, "taken")) { + int open_fds = 0; + for (int t = 0; t < ntaken; t++) + if (lseek(taken[t], 0, SEEK_CUR) == 0) open_fds++; + printf("%d/%d\n", open_fds, ntaken); + } + } + return 0; +} +""" + + +class FastPathFuseDirsTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + if shutil.which("gcc") is None: + raise unittest.SkipTest("gcc is not available") + cls.build = tempfile.TemporaryDirectory() + source = Path(cls.build.name) / "fuse_dirs.c" + source.write_text(PROGRAM.replace("FASTPATH", str(FASTPATH))) + cls.program = Path(cls.build.name) / "fuse_dirs" + subprocess.run(["gcc", "-O1", "-Wall", "-Wextra", "-Werror", "-Wno-format-truncation", "-pthread", "-o", str(cls.program), str(source), "-ldl"], check=True) + + @classmethod + def tearDownClass(cls): + cls.build.cleanup() + + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + base = Path(self.temp.name) + self.root = base / "root" + (self.root / "mnt").mkdir(parents=True) + self.card = base / "card" + (self.card / "Games/steamapps/common/Game/Data").mkdir(parents=True) + + def ask(self, *ops, wrap=()): + argv = [*wrap, str(self.program), str(self.root), str(self.card), "/mnt/card", "--", *ops] + return subprocess.run(argv, capture_output=True, text=True, timeout=20, check=True).stdout.split() + + def test_files_deep_in_a_fuse_library_are_created_renamed_and_removed(self): + data = "/mnt/card/Games/steamapps/common/Game/Data" + out = self.ask("fuse", "touch", f"{data}/a.tmp", "mv", f"{data}/a.tmp", f"{data}/a.idx", + "stat", f"{data}/a.idx", "stat", f"{data}/a.tmp", "rm", f"{data}/a.idx", + "stat", f"{data}/a.idx", "fds") + self.assertEqual(["ok", "ok", "ok", "E2", "ok", "E2"], out[:-1]) + self.assertGreater(int(out[-1]), 0) + self.assertEqual([], list((self.card / "Games/steamapps/common/Game/Data").iterdir())) + + def test_a_folder_renamed_behind_the_cache_is_not_reused(self): + game = self.card / "Games/steamapps/common/Game" + (game / "Data/keep").write_text("x") + out = self.ask("fuse", "stat", "/mnt/card/Games/steamapps/common/Game/Data/keep", + "host-mv", str(game), str(game.parent / "Moved"), + "stat", "/mnt/card/Games/steamapps/common/Game/Data/keep", + "stat", "/mnt/card/Games/steamapps/common/Moved/Data/keep") + self.assertEqual(["ok", "ok", "E2", "ok"], out) + + def test_a_folder_renamed_while_it_is_opened_is_not_used_under_its_old_name(self): + game = self.card / "Games/steamapps/common/Game" + (game / "Data/keep").write_text("x") + out = self.ask("fuse", "race-mv", str(game / "Data"), str(game / "Moved"), + "stat", "/mnt/card/Games/steamapps/common/Game/Data/keep", + "touch", "/mnt/card/Games/steamapps/common/Game/Data/new", "fds") + self.assertEqual(["ok", "E2", "E2"], out[:3]) + self.assertEqual(["keep"], [p.name for p in (game / "Moved").iterdir()]) + self.assertLessEqual(int(out[-1]), 64) + + def test_a_folder_deleted_and_made_again_is_looked_up_fresh(self): + data = self.card / "Games/steamapps/common/Game/Data" + out = self.ask("fuse", "touch", "/mnt/card/Games/steamapps/common/Game/Data/old", + "rm", "/mnt/card/Games/steamapps/common/Game/Data/old", + "host-rmdir", str(data), "host-mkdir", str(data), + "touch", "/mnt/card/Games/steamapps/common/Game/Data/new") + self.assertEqual(["ok"] * 5, out) + self.assertEqual(["new"], [p.name for p in data.iterdir()]) + + def test_folders_deleted_and_made_again_many_times_keep_descriptors_bounded(self): + data = self.card / "Games/steamapps/common/Game/Data" + ops = ["fuse"] + for _ in range(200): + ops += ["touch", "/mnt/card/Games/steamapps/common/Game/Data/x", + "rm", "/mnt/card/Games/steamapps/common/Game/Data/x", + "host-rmdir", str(data), "host-mkdir", str(data)] + out = self.ask(*ops, "fds") + self.assertEqual(["ok"] * 800, out[:-1]) + self.assertLessEqual(int(out[-1]), 64) + + def test_descriptors_the_program_takes_over_are_left_alone(self): + data = "/mnt/card/Games/steamapps/common/Game/Data" + out = self.ask("fuse", "touch", f"{data}/a", "clobber", "touch", f"{data}/b", + "stat", f"{data}/a", "first-fd") + self.assertEqual(["ok", "ok", "ok", "ok", "/dev/null"], out) + self.assertEqual({"a", "b"}, {p.name for p in (self.card / "Games/steamapps/common/Game/Data").iterdir()}) + + def test_a_folder_the_program_opened_itself_stays_open_when_the_cache_moves_on(self): + data = self.card / "Games/steamapps/common/Game/Data" + ops = ["fuse", "touch", "/mnt/card/Games/steamapps/common/Game/Data/a", "take-over"] + for n in range(200): + (data / f"d{n}").mkdir() + ops += ["touch", f"/mnt/card/Games/steamapps/common/Game/Data/d{n}/x"] + out = self.ask(*ops, "taken") + self.assertEqual(["ok"] * 202, out[:-1]) + opened, total = map(int, out[-1].split("/")) + self.assertGreater(total, 0) + self.assertEqual(total, opened) + self.assertEqual(200, len(list(data.glob("d*/x")))) + + @unittest.skipIf(os.geteuid() == 0, "root passes folder permissions") + def test_a_parent_folder_closed_by_the_program_stops_cached_access_at_once(self): + game = self.card / "Games/steamapps/common/Game" + (game / "Data/keep").write_text("x") + self.addCleanup(os.chmod, game, 0o755) + out = self.ask("fuse", "stat", "/mnt/card/Games/steamapps/common/Game/Data/keep", + "chmod", "/mnt/card/Games/steamapps/common/Game", "000", + "stat", "/mnt/card/Games/steamapps/common/Game/Data/keep", + "touch", "/mnt/card/Games/steamapps/common/Game/Data/new") + self.assertEqual(["ok", "ok"], out[:2]) + self.assertNotIn("ok", out[2:]) + os.chmod(game, 0o755) + self.assertEqual(["keep"], [p.name for p in (game / "Data").iterdir()]) + + @unittest.skipUnless(USERNS, "mount namespaces are not available") + def test_a_mount_placed_over_a_cached_folder_receives_later_writes(self): + data = self.card / "Games/steamapps/common/Game/Data" + out = self.ask("fuse", "ttl", "1", "touch", "/mnt/card/Games/steamapps/common/Game/Data/under", + "host-mount", str(data), "sleep", "20", + "touch", "/mnt/card/Games/steamapps/common/Game/Data/over", + "stat", "/mnt/card/Games/steamapps/common/Game/Data/under", wrap=("unshare", "-Urm")) + self.assertEqual(["ok", "ok", "ok", "E2"], out) + self.assertEqual(["under"], [p.name for p in data.iterdir()]) + + def test_a_call_the_filesystem_does_not_implement_leaves_the_fast_path_on(self): + data = "/mnt/card/Games/steamapps/common/Game/Data" + out = self.ask("fuse", "no-symlinks", "touch", f"{data}/a", "symlink", f"{data}/link", "on", + "stat", f"{data}/a", "symlink", f"{data}/link", "on", "touch", f"{data}/b") + self.assertEqual(["ok", "REFUSED", "1", "ok", "REFUSED", "1", "ok"], out) + self.assertEqual(["a", "b"], sorted(p.name for p in (self.card / "Games/steamapps/common/Game/Data").iterdir())) + + def test_repeated_unsupported_calls_close_the_folders_they_opened(self): + data = "/mnt/card/Games/steamapps/common/Game/Data" + ops = [op for n in range(40) for op in ("mkdir", f"{data}/new{n}")] + out = self.ask("fuse", "no-folders", "busy-cache", *ops, "on", "fds") + self.assertEqual(["REFUSED"] * 40 + ["1", "0"], out) + + def test_a_trapped_call_still_stops_the_fast_path_for_the_process(self): + data = "/mnt/card/Games/steamapps/common/Game/Data" + out = self.ask("fuse", "trap-symlink", "symlink", f"{data}/link", "on") + self.assertEqual(["REFUSED", "0"], out) + + def test_a_symlink_is_made_where_the_filesystem_allows_it(self): + data = "/mnt/card/Games/steamapps/common/Game/Data" + out = self.ask("fuse", "symlink", f"{data}/link", "on") + self.assertEqual(["ok", "1"], out) + self.assertEqual("target", os.readlink(self.card / "Games/steamapps/common/Game/Data/link")) + + def test_other_filesystems_keep_absolute_paths_and_open_no_folders(self): + data = "/mnt/card/Games/steamapps/common/Game/Data" + out = self.ask("touch", f"{data}/a", "mv", f"{data}/a", f"{data}/b", "rm", f"{data}/b", "fds") + self.assertEqual(["ok", "ok", "ok", "0"], out) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_game_environment.py b/tools/tests/test_game_environment.py index d6cb49582e..5f7b4af087 100644 --- a/tools/tests/test_game_environment.py +++ b/tools/tests/test_game_environment.py @@ -993,8 +993,10 @@ class GameEnvironmentTest(unittest.TestCase): def test_the_vram_cap_comes_before_the_games_own_dxvk_settings(self): cap = MODULE["vram_cap"] self.assertEqual(cap({"BL_VRAM_MB": "4096"})["DXVK_CONFIG"], "dxgi.maxDeviceMemory = 4096") + self.assertEqual(cap({"BL_VRAM_MB": "8192"})["DXVK_CONFIG"], "dxgi.maxDeviceMemory = 8192") + self.assertEqual(cap({"BL_VRAM_MB": "4095"})["DXVK_CONFIG"], "dxgi.maxDeviceMemory = 4095; d3d9.maxAvailableMemory = 4095") self.assertEqual(cap({"BL_VRAM_MB": "2048", "DXVK_CONFIG": "dxvk.maxFrameRate = 60;"})["DXVK_CONFIG"], - "dxgi.maxDeviceMemory = 2048; dxvk.maxFrameRate = 60") + "dxgi.maxDeviceMemory = 2048; d3d9.maxAvailableMemory = 2048; dxvk.maxFrameRate = 60") for off in ({}, {"BL_VRAM_MB": "0"}, {"BL_VRAM_MB": "lots"}, {"BL_VRAM_MB": "ยฒ"}, {"BL_VRAM_MB": "-1"}): self.assertNotIn("DXVK_CONFIG", cap(off)) self.assertNotIn("DROIDDECK_VRAM_CAP", cap(off)) @@ -1520,6 +1522,19 @@ class GameEnvironmentTest(unittest.TestCase): config = {"version": 1, "shared": {}, "games": {"42": values}} self.assertEqual(MODULE["apply_config"]({}, config, "42", env), values, name) + def test_ff7_rebirth_runs_at_feature_level_12_2_unless_the_game_overrides_it(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) / "FINAL FANTASY VII REBIRTH" + game = root / "End/Binaries/Win64/ff7rebirth_.exe" + game.parent.mkdir(parents=True) + for exe in (root / "ff7rebirth.exe", game): + exe.touch() + env, extra, notes = MODULE["engine_fixes"](str(exe), []) + self.assertEqual(env, {"VKD3D_FEATURE_LEVEL": "12_2"}, exe.name) + self.assertTrue(notes) + config = {"version": 1, "shared": {}, "games": {"42": {"VKD3D_FEATURE_LEVEL": "12_1"}}} + self.assertEqual(MODULE["apply_config"]({}, config, "42", env), {"VKD3D_FEATURE_LEVEL": "12_1"}) + def test_unity_players_keep_tso_over_the_preset(self): with tempfile.TemporaryDirectory() as tmp: def game(*names): diff --git a/tools/tests/test_game_resolution.py b/tools/tests/test_game_resolution.py new file mode 100644 index 0000000000..78c5fb3d98 --- /dev/null +++ b/tools/tests/test_game_resolution.py @@ -0,0 +1,53 @@ +import os +from pathlib import Path +import subprocess +import tempfile +import unittest + + +SESSION = Path(__file__).resolve().parents[1] / 'linuxfs/overlay/usr/local/bin/droiddeck-session' + + +class GameResolutionTest(unittest.TestCase): + def launch(self, mode, **overrides): + source = SESSION.read_text() + start = source.index(' width=${BL_WIDTH:-1280}') + end = source.index('\nfi\n\nbl_displays()', start) + block = source[start:end].replace('/usr/local/bin/droiddeck-pipewire', 'pipewire_stub') + with tempfile.TemporaryDirectory() as directory: + env = dict(os.environ, XDG_RUNTIME_DIR=directory, BL_REFRESH='60', BL_MANGOAPP='0', + BL_WIDTH='2560', BL_HEIGHT='1600') + for name in ('BL_GAME_WIDTH', 'BL_GAME_HEIGHT', 'BL_FOLLOW_OUTPUT', 'BL_GAMESCOPE_STRETCH_16X9'): + env.pop(name, None) + env.update(overrides) + fake = Path(directory) / 'gamescope' + fake.write_text('#!/bin/bash\nprintf "ARG:%s\\n" "$@"\n') + fake.chmod(0o755) + env['PATH'] = directory + os.pathsep + env['PATH'] + script = f''' +set -u +mode={mode} +pipewire_stub() {{ return 1; }} +run_gamescope() {{ printf 'ARG:%s\n' "$@"; }} +''' + block + result = subprocess.run(['bash', '-c', script], env=env, capture_output=True, text=True, timeout=5) + self.assertEqual(0, result.returncode, result.stderr) + return [line.removeprefix('ARG:') for line in result.stdout.splitlines() if line.startswith('ARG:')] + + def test_a_game_started_without_steam_runs_at_its_resolution_with_proportions_kept(self): + args = self.launch('run', BL_GAME_WIDTH='1280', BL_GAME_HEIGHT='720') + self.assertEqual(['2560', '1600'], [args[args.index('-W') + 1], args[args.index('-H') + 1]]) + self.assertEqual(['1280', '720'], [args[args.index('-w') + 1], args[args.index('-h') + 1]]) + self.assertNotIn('-S', args) + + def test_without_a_game_resolution_the_game_matches_the_output(self): + args = self.launch('run') + self.assertEqual(['2560', '1600'], [args[args.index('-w') + 1], args[args.index('-h') + 1]]) + + def test_steam_ignores_the_game_resolution(self): + args = self.launch('steam', BL_GAME_WIDTH='1280', BL_GAME_HEIGHT='720') + self.assertEqual(['2560', '1600'], [args[args.index('-w') + 1], args[args.index('-h') + 1]]) + + +if __name__ == '__main__': + unittest.main() diff --git a/tools/tests/test_memory_pressure.py b/tools/tests/test_memory_pressure.py index 13f9e2f8d3..01c32c3f82 100644 --- a/tools/tests/test_memory_pressure.py +++ b/tools/tests/test_memory_pressure.py @@ -2,7 +2,7 @@ from pathlib import Path import tempfile import unittest -from tools.tests.test_client_zram_focus import function_source, run_bash +from tools.tests.test_client_zram_focus import SCRIPT, function_source, run_bash class MemoryPressureTest(unittest.TestCase): @@ -20,8 +20,8 @@ class MemoryPressureTest(unittest.TestCase): def run_policy(self, body): functions = '\n'.join(function_source(name) for name in ( - 'bl_memory_read', 'bl_memory_tight', 'bl_client_can_pageout', - 'bl_client_can_readback', 'bl_client_pressure')) + 'bl_memory_read', 'bl_memory_tight', 'bl_memory_critical', 'bl_client_can_pageout', + 'bl_client_can_readback', 'bl_client_pressure', 'bl_client_pressure_result', 'bl_zram_has_room')) functions = functions.replace('/proc/meminfo', str(self.root / 'meminfo')) functions = functions.replace('/proc/pressure/memory', str(self.root / 'pressure')) harness = ''' @@ -29,7 +29,7 @@ set -u _bl_pids=(123) _bl_game=1 _bl_packed=-1 _bl_pressure_at=-1 _bl_pressure_backoff=30 rss=$((384 * 1024)) client_swap=$((512 * 1024)) reclaimed=$((128 * 1024)) step() { :; } -bl_zram_usage() { _bl_rss=$rss _bl_swap=$client_swap; } +bl_zram_usage() { _bl_rss=$rss _bl_anon=${anon:-$rss} _bl_swap=$client_swap; } bl_zram_send() { echo "send:$1:$3"; rss=$((rss - reclaimed)); _bl_pageout_complete=${pageout_complete:-1}; } ''' + functions + '\nbl_memory_read\n' + body result = run_bash('NOW=0\n' + harness.replace('SECONDS', 'NOW')) @@ -80,6 +80,13 @@ if bl_client_can_readback; then echo yes; else echo no; fi self.assertEqual(['no'], self.run_policy(''' bl_client_pressure if bl_client_can_pageout; then echo yes; else echo no; fi +''')) + + def test_client_swap_budget_excludes_file_backed_memory(self): + self.memory(swap_free=1536) + self.assertEqual(['send:1:client'], self.run_policy(''' +rss=$((2048 * 1024)) anon=$((256 * 1024)) +bl_client_pressure ''')) def test_without_swap_automatic_pageout_is_disabled(self): @@ -152,20 +159,20 @@ class SessionPressureTest(unittest.TestCase): def run_policy(self, body): functions = '\n'.join(function_source(name) for name in ( - 'bl_memory_read', 'bl_memory_tight', 'bl_memory_critical', 'bl_low_ram', - 'bl_session_pressure', 'bl_watch_nap', 'bl_zram_pick', 'bl_tier_note', 'bl_tier_readback')) + 'bl_memory_read', 'bl_memory_tight', 'bl_memory_critical', + 'bl_session_pressure', 'bl_zram_has_room', 'bl_watch_nap', 'bl_zram_pick', 'bl_tier_note', 'bl_tier_readback')) functions = functions.replace('/proc/meminfo', str(self.root / 'meminfo')) functions = functions.replace('/proc/pressure/memory', str(self.root / 'pressure')) harness = ''' set -u _bl_game=1 _bl_tier_at=-1 _bl_tier_backoff=30 _bl_tier_pushed=0 _bl_tier_back=0 _bl_tier_targets=() _bl_tier_swaps=() _bl_tier_starts=() _bl_pids=(999) _bl_pressure_at=-1 _bl_packed=-1 -rss=$((1536 * 1024)) swap=0 pushed=$((1024 * 1024)) alive=999 started=100 complete=1 +rss=$((1536 * 1024)) swap=0 pushed=$((1024 * 1024)) alive="999 321 654" started=100 complete=1 step() { :; } bl_proc_start() { _bl_start=; case " $alive " in *" $1 "*) _bl_start=$started; return 0 ;; esac; return 1; } nap() { echo "nap:$1"; } bl_session_others() { _bl_session=(321 654); } -bl_zram_usage() { _bl_rss=$rss _bl_swap=$swap; } +bl_zram_usage() { _bl_rss=$rss _bl_anon=${anon:-$rss} _bl_swap=$swap; } bl_zram_send() { echo "send:$1:$3"; rss=$((rss - pushed)); swap=$((swap + pushed)); _bl_pageout_complete=$complete; } ''' + functions + '\nbl_memory_read\n' + body result = run_bash('NOW=0\n' + harness.replace('SECONDS', 'NOW')) @@ -174,19 +181,27 @@ bl_zram_send() { echo "send:$1:$3"; rss=$((rss - pushed)); swap=$((swap + pushed return result.stdout.splitlines() def test_low_headroom_compresses_the_game_session_at_most_every_30_seconds(self): - self.assertEqual(['send:1:game', 'send:1:game'], self.run_policy(''' + self.assertEqual(['send:1:session', 'send:1:session'], self.run_policy(''' SECONDS=0; bl_session_pressure SECONDS=10; bl_session_pressure SECONDS=29; bl_session_pressure SECONDS=30; bl_session_pressure ''')) - def test_twelve_gigabyte_devices_are_included_and_larger_ones_are_not(self): - for total, expected in ((11264, ['send:1:game']), (12288, ['send:1:game']), (15360, [])): + def test_pressure_policy_is_independent_of_ram_size(self): + for total, expected in ((11264, ['send:1:session']), (12288, ['send:1:session']), (16384, ['send:1:session'])): with self.subTest(total=total): self.memory(total=total) self.assertEqual(expected, self.run_policy('bl_session_pressure')) + def test_large_device_with_real_headroom_does_not_reclaim(self): + self.memory(total=16384, available=5120, psi='12.34') + self.assertEqual([], self.run_policy('bl_session_pressure')) + + def test_large_device_with_psi_and_moderate_headroom_reclaims(self): + self.memory(total=16384, available=3072, psi='1.23') + self.assertEqual(['send:1:session'], self.run_policy('bl_session_pressure')) + def test_no_game_does_not_compress_the_session(self): self.assertEqual([], self.run_policy('_bl_game=0; bl_session_pressure')) @@ -196,15 +211,26 @@ SECONDS=30; bl_session_pressure def test_stalls_with_moderate_headroom_compress_before_the_hard_limit(self): self.memory(available=2048, psi='1.50') - self.assertEqual(['send:1:game'], self.run_policy('bl_session_pressure')) + self.assertEqual(['send:1:session'], self.run_policy('bl_session_pressure')) def test_moderate_headroom_without_stalls_waits(self): self.memory(available=2048) self.assertEqual([], self.run_policy('bl_session_pressure')) + def test_same_second_memory_read_preserves_the_pressure_baseline(self): + self.memory(available=2048) + meminfo = self.root / 'meminfo' + self.assertEqual(['1048576:524288:2097152'], self.run_policy(f''' +SECONDS=100 +_bl_sample_at=100 _bl_sample_available=2097152 _bl_growth=0 _bl_fall=524288 +sed -i 's/MemAvailable: 2097152 kB/MemAvailable: 1048576 kB/' {meminfo} +bl_memory_read +echo "$_bl_available:$_bl_fall:$_bl_sample_available" +''')) + def test_game_reading_back_most_of_a_pageout_skips_and_doubles_the_wait(self): - self.assertEqual(['send:1:game', 'backoff:60', 'send:1:game', 'backoff:60', - 'send:1:game', 'backoff:30'], self.run_policy(''' + self.assertEqual(['send:1:session', 'backoff:60', 'send:1:session', 'backoff:60', + 'send:1:session', 'backoff:30'], self.run_policy(''' pushed=$((512 * 1024)) SECONDS=0; bl_session_pressure swap=$((swap / 4)) @@ -226,7 +252,7 @@ echo "backoff:$_bl_tier_backoff" def test_nearly_out_of_memory_ignores_the_backoff_but_keeps_30_seconds(self): self.memory(available=512) - self.assertEqual(['send:1:game', 'send:1:game'], self.run_policy(''' + self.assertEqual(['send:1:session', 'send:1:session'], self.run_policy(''' _bl_tier_backoff=300 SECONDS=0; bl_session_pressure SECONDS=20; bl_session_pressure @@ -235,7 +261,7 @@ SECONDS=30; bl_session_pressure def test_nearly_out_of_memory_still_backs_off_when_the_game_reads_its_pageout_back(self): self.memory(available=512) - self.assertEqual(['send:1:game', 'backoff:60', 'send:1:game'], self.run_policy(''' + self.assertEqual(['send:1:session', 'backoff:60', 'send:1:session'], self.run_policy(''' SECONDS=0; bl_session_pressure swap=0 SECONDS=30; bl_session_pressure @@ -247,7 +273,7 @@ SECONDS=90; bl_session_pressure def test_nearly_out_of_memory_retries_a_skipped_pageout_after_30_seconds(self): self.memory(available=512) - self.assertEqual(['send:1:game', 'send:1:game'], self.run_policy(''' + self.assertEqual(['send:1:session', 'send:1:session'], self.run_policy(''' SECONDS=0; bl_session_pressure swap=0 SECONDS=30; bl_session_pressure @@ -263,6 +289,24 @@ SECONDS=360; bl_session_pressure self.memory(swap_free=1536, swap_total=2048) self.assertEqual([], self.run_policy('bl_session_pressure')) + def test_file_backed_resident_memory_does_not_consume_the_swap_budget(self): + self.memory(swap_free=3088, swap_total=6144) + self.assertEqual(['send:1:session'], self.run_policy(''' +rss=$((4096 * 1024)) anon=$((1024 * 1024)) +bl_session_pressure +''')) + + def test_anonymous_memory_and_pending_client_still_need_the_full_swap_reserve(self): + self.memory(swap_free=3088, swap_total=6144) + self.assertEqual([], self.run_policy(''' +rss=$((4096 * 1024)) anon=$((2048 * 1024)) +bl_session_pressure +''')) + self.assertEqual([], self.run_policy(''' +rss=$((4096 * 1024)) anon=$((1536 * 1024)) _bl_client_reserve=$((512 * 1024)) +bl_session_pressure +''')) + def test_small_session_is_left_alone(self): self.assertEqual([], self.run_policy('rss=$((128 * 1024)); bl_session_pressure')) @@ -275,10 +319,10 @@ SECONDS=360; bl_session_pressure self.assertEqual(['nap:5'], self.run_policy('bl_watch_nap')) self.assertEqual(['nap:5'], self.run_policy('_bl_game=0; bl_watch_nap')) - def test_one_push_compresses_the_game_and_the_launcher_and_restarts_the_launcher_wait(self): - self.assertEqual(['send:1:game', 'pids:321 654 999', 'client:0:0'], self.run_policy(''' + def test_session_push_preserves_client_timestamps(self): + self.assertEqual(['send:1:session', 'pids:321 654', 'client:-1:-1'], self.run_policy(''' SECONDS=0; bl_session_pressure -bl_zram_pick game; echo "pids:${_pids[*]}" +bl_zram_pick session; echo "pids:${_pids[*]}" echo "client:$_bl_pressure_at:$_bl_packed" ''')) @@ -286,19 +330,19 @@ echo "client:$_bl_pressure_at:$_bl_packed" self.assertEqual(['pids:321 654', 'client:-1:-1'], self.run_policy(''' BL_ZRAM_CLIENT=0 SECONDS=0; bl_session_pressure -bl_zram_pick game; echo "pids:${_pids[*]}" +bl_zram_pick session; echo "pids:${_pids[*]}" echo "client:$_bl_pressure_at:$_bl_packed" ''')[1:]) def test_low_ram_devices_compress_with_a_quarter_of_memory_left(self): self.memory(available=1700) - self.assertEqual(['send:1:game'], self.run_policy('bl_session_pressure')) + self.assertEqual(['send:1:session'], self.run_policy('bl_session_pressure')) self.memory(available=1900) self.assertEqual([], self.run_policy('bl_session_pressure')) def test_a_compressed_process_that_exits_is_not_counted_as_read_back(self): - self.assertEqual(['send:1:game', 'send:1:game', 'backoff:30'], self.run_policy(''' + self.assertEqual(['send:1:session', 'send:1:session', 'backoff:30'], self.run_policy(''' SECONDS=0; bl_session_pressure alive=""; swap=0 SECONDS=30; bl_session_pressure @@ -306,7 +350,7 @@ echo "backoff:$_bl_tier_backoff" ''')) def test_a_process_that_starts_after_a_pageout_is_not_in_its_read_back(self): - self.assertEqual(['send:1:game', 'targets:999', 'send:1:game', 'backoff:30'], self.run_policy(''' + self.assertEqual(['send:1:session', 'targets:321 654', 'send:1:session', 'backoff:30'], self.run_policy(''' SECONDS=0; bl_session_pressure echo "targets:${_bl_tier_targets[*]}" alive="999 1234" @@ -315,7 +359,7 @@ echo "backoff:$_bl_tier_backoff" ''')) def test_an_incomplete_pageout_does_not_restart_the_launcher_wait(self): - self.assertEqual(['send:1:game', 'client:-1:-1'], self.run_policy(''' + self.assertEqual(['send:1:session', 'client:-1:-1'], self.run_policy(''' complete=0 SECONDS=0; bl_session_pressure echo "client:$_bl_pressure_at:$_bl_packed" @@ -323,7 +367,7 @@ echo "client:$_bl_pressure_at:$_bl_packed" def test_a_reused_process_id_is_not_counted_as_read_back(self): - self.assertEqual(['send:1:game', 'send:1:game', 'backoff:30'], self.run_policy(''' + self.assertEqual(['send:1:session', 'send:1:session', 'backoff:30'], self.run_policy(''' SECONDS=0; bl_session_pressure started=200; swap=0 SECONDS=30; bl_session_pressure @@ -344,5 +388,112 @@ echo "backoff:$_bl_tier_backoff" self.assertEqual(['gone'], result.stdout.split()) +class ReclaimDispatchTest(unittest.TestCase): + def run_cycle(self, client=1, game=1, anonymous=384, complete=1, reclaimed=128, body=None, available=1024, fall=0, tick=0): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + (root / 'meminfo').write_text( + f'MemTotal: 7340032 kB\nMemAvailable: {available * 1024} kB\n' + 'SwapTotal: 6291456 kB\nSwapFree: 4194304 kB\n') + (root / 'pressure').write_text('some avg10=0.00 avg60=0.00 avg300=0.00 total=0\n') + names = ('bl_memory_read', 'bl_memory_tight', 'bl_memory_critical', + 'bl_zram_has_room', 'bl_client_can_pageout', 'bl_client_pressure', + 'bl_client_pressure_result', 'bl_client_pressure_finish', + 'bl_session_pressure', 'bl_zram_send', 'bl_zram_finish', 'bl_zram_pick') + source = '\n'.join(function_source(name) for name in names) + source = source.replace('/proc/meminfo', str(root / 'meminfo')) + source = source.replace('/proc/pressure/memory', str(root / 'pressure')) + source = source.replace('/tmp/.bl-zram', str(root / 'ctl')) + monitor = SCRIPT.read_text() + start = monitor.index(' _bl_preserved_growth=$_bl_growth', monitor.index('while kill -0 $$')) + stop = monitor.index(' if [ "$_bl_game" = 1 ] && bl_game_focused', start) + cycle = monitor[start:stop] if body is None else body + script = f''' +set -u +BL_ZRAM_CLIENT={client} _bl_game={game} _bl_pids=(123) _bl_others=(321) +_bl_pressure_at=-1 _bl_pressure_backoff=30 _bl_packed=-1 +_bl_tier_at=-1 _bl_tier_backoff=30 _bl_tier_pushed=0 +_bl_client_reserve=0 client_rss=393216 client_anon={anonymous * 1024} +step() {{ :; }} +bl_session_others() {{ _bl_session=(321); }} +bl_zram_scan() {{ _bl_pids=(456); }} +nap() {{ echo "nap:$*:at:$NOW"; }} +bl_zram_usage() {{ + if [ "$1" = 123 ]; then + _bl_rss=$client_rss _bl_anon=$client_anon _bl_swap=0 + else + _bl_rss=3145728 _bl_anon=1572864 _bl_swap=0 + fi +}} +kill() {{ echo "signal:$*:at:$NOW"; NOW=$((NOW + {tick})); }} +bl_zram_wait() {{ + echo "wait:$*:at:$NOW" + NOW=$((NOW + 12)) + _bl_pageout_complete={complete} + [ "$1" != 123 ] || client_rss=$((client_rss - {reclaimed * 1024})) +}} +bl_tier_note() {{ :; }} +''' + source + f''' +bl_memory_read +_bl_fall={fall * 1024} +''' + cycle + ''' +echo "client:$_bl_pressure_backoff:${_bl_client_reserve:-0}:${_bl_client_pending:-0}" +''' + result = run_bash('NOW=0\n' + script.replace('SECONDS', 'NOW')) + self.assertEqual(0, result.returncode, result.stderr) + self.assertEqual('', result.stderr) + return result.stdout.splitlines() + + def test_both_requests_are_sent_before_either_wait(self): + self.assertEqual(['signal:-URG 123:at:0', 'signal:-URG 321:at:0', + 'wait:321:at:0', 'wait:123:at:12', 'client:30:0:0'], self.run_cycle()) + + def test_disabled_client_is_never_signalled_or_waited_for(self): + self.assertEqual(['signal:-URG 321:at:0', 'wait:321:at:0', 'client:30:0:0'], + self.run_cycle(client=0)) + + def test_no_game_requests_nothing(self): + self.assertEqual(['client:30:0:0'], self.run_cycle(game=0)) + + def test_a_client_with_no_anonymous_pages_still_finishes_its_request(self): + self.assertEqual(['signal:-URG 123:at:0', 'signal:-URG 321:at:0', + 'wait:321:at:0', 'wait:123:at:12', 'client:30:0:0'], + self.run_cycle(anonymous=0)) + + def test_falling_headroom_survives_a_tick_between_requests(self): + self.assertEqual(['signal:-URG 123:at:0', 'signal:-URG 321:at:1', + 'wait:321:at:2', 'wait:123:at:14', 'client:30:0:0'], + self.run_cycle(available=2304, fall=512, tick=1)) + + def test_deferred_ineffective_reclaim_still_doubles_the_backoff(self): + self.assertEqual('client:60:0:0', self.run_cycle(reclaimed=0)[-1]) + + def test_deferred_incomplete_reclaim_does_not_double_the_backoff(self): + self.assertEqual('client:30:0:0', self.run_cycle(reclaimed=0, complete=0)[-1]) + + def test_explicit_combined_send_keeps_its_synchronous_wait(self): + self.assertEqual(['signal:-URG 321 123:at:0', 'wait:321 123:at:0', 'client:30:0:0'], + self.run_cycle(body='bl_zram_send 1 cap game\n')) + self.assertEqual(['signal:-URG 321:at:0', 'wait:321:at:0', 'client:30:0:0'], + self.run_cycle(client=0, body='bl_zram_send 1 cap game\n')) + + def test_readback_keeps_its_synchronous_delay(self): + self.assertEqual(['signal:-URG 123:at:0', 'nap:5:at:0', 'client:30:0:0'], + self.run_cycle(body='bl_zram_send 0 readback client\n')) + + def test_usage_sums_anonymous_rss_and_falls_back_per_process(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + for pid, contents in ((123, 'VmRSS: 2000 kB\nRssAnon: 300 kB\nVmSwap: 100 kB\n'), + (321, 'VmRSS: 4000 kB\nVmSwap: 200 kB\n'), + (654, 'VmRSS: 1000 kB\nRssAnon: 0 kB\n')): + (root / str(pid)).mkdir() + (root / str(pid) / 'status').write_text(contents) + source = function_source('bl_zram_usage').replace('/proc/', str(root) + '/') + result = run_bash(source + '\nbl_zram_usage 123 321 654 > /dev/null; echo "$_bl_rss:$_bl_anon:$_bl_swap"') + self.assertEqual(0, result.returncode, result.stderr) + self.assertEqual('7000:4300:300', result.stdout.strip()) + + if __name__ == '__main__': unittest.main() diff --git a/tools/tests/test_seed_redists.py b/tools/tests/test_seed_redists.py index 1440b41b0f..f00dc1ae26 100644 --- a/tools/tests/test_seed_redists.py +++ b/tools/tests/test_seed_redists.py @@ -2,6 +2,7 @@ import os import shutil import subprocess import tempfile +import time import unittest from pathlib import Path @@ -128,6 +129,67 @@ class SeedRedistsTest(unittest.TestCase): self.run_seed(str(sd)) self.assertIn('"VCRedist2022"=dword:00000001', self.reg.read_text()) + def manifest(self, name, build): + path = self.steam / "steamapps/appmanifest_77.acf" + path.write_text('"AppState"\n{\n\t"installdir"\t\t"%s"\n\t"buildid"\t\t"%s"\n}\n' % (name, build)) + return path + + def test_a_game_is_searched_again_only_when_its_build_changes(self): + late = self.steam / "steamapps/common/Late Game/installscript.vdf" + late.parent.mkdir(parents=True) + manifest = self.manifest("Late Game", "1") + self.run_seed() + late.write_text(GAME_SCRIPT) + manifest.write_text(manifest.read_text() + "\n") + self.run_seed() + self.assertNotIn("VCRedist2022", self.reg.read_text()) + self.manifest("Late Game", "2") + self.run_seed() + self.assertIn('"VCRedist2022"=dword:00000001', self.reg.read_text()) + + def test_one_changed_game_leaves_the_other_games_unsearched(self): + other = self.game("Other Game").parent / "installscript_extra.vdf" + self.manifest("Late Game", "1") + self.run_seed() + other.write_text(GAME_SCRIPT.replace("VCRedist2022", "Unsearched")) + self.manifest("Late Game", "2") + self.run_seed() + self.assertNotIn("Unsearched", self.reg.read_text()) + + def test_a_call_that_names_its_scripts_does_not_search_the_libraries(self): + script = self.game() + named = self.tmp / "legacycompat/evaluatorscript_1.vdf" + named.parent.mkdir(parents=True) + named.write_text(GAME_SCRIPT.replace("VCRedist2022", "Named")) + env = dict(os.environ, DROIDDECK_LIBRARIES="", DROIDDECK_SEED_SCRIPTS=str(named)) + subprocess.run(["bash", str(SCRIPT), str(self.steam)], env=env, capture_output=True, text=True, check=True) + reg = self.reg.read_text() + self.assertIn('"Named"=dword:00000001', reg) + self.assertNotIn("VCRedist2022", reg) + self.run_seed() + self.assertIn('"VCRedist2022"=dword:00000001', self.reg.read_text()) + self.assertIn(str(script), (self.steam / ".droiddeck-game-scripts").read_text()) + + def test_a_removed_game_leaves_the_list(self): + script = self.game() + self.run_seed() + cache = self.steam / ".droiddeck-game-scripts" + self.assertIn(str(script), cache.read_text()) + for manifest in (self.steam / "steamapps").glob("appmanifest_*.acf"): + manifest.unlink() + self.run_seed() + self.assertEqual("", cache.read_text()) + + def test_a_list_from_an_earlier_version_is_taken_over_without_a_search(self): + script = self.steam / "steamapps/common/Old Game/a/b/c/d/e/installscript.vdf" + script.parent.mkdir(parents=True) + script.write_text(GAME_SCRIPT) + self.manifest("Old Game", "1") + (self.steam / ".droiddeck-game-scripts").write_text("123 456\n%s\n" % script) + self.run_seed() + self.assertIn('"VCRedist2022"=dword:00000001', self.reg.read_text()) + self.assertIn("\t%s\n" % script, (self.steam / ".droiddeck-game-scripts").read_text()) + def test_current_user_and_machine_markers_go_to_their_own_registries(self): self.game(script=GAME_SCRIPT + GAME_SCRIPT.replace("HKEY_LOCAL_MACHINE", "HKEY_CURRENT_USER").replace("VCRedist2022", "UserRedist")) with self.reg.open("a") as out: @@ -398,6 +460,62 @@ class SeedRedistsTest(unittest.TestCase): self.assertEqual(self.reg.read_text().count('"Vulkan111080"'), 2) + def test_a_session_start_leaves_the_library_search_to_a_later_run(self): + self.game(script=GAME_SCRIPT.replace("Software\\\\Valve\\\\Steam\\\\Apps\\\\CommonRedist\\\\vcredist\\\\2022", "SOFTWARE\\\\AGEIA Technologies").replace("VCRedist2022", "PhysX Version")) + shim = self.tmp / "bin" + shim.mkdir() + go = self.tmp / "go" + (shim / "find").write_text('#!/bin/sh\ncase "$*" in *"installscript*"*) n=0; while [ ! -e "%s" ] && [ $n -lt 600 ]; do sleep 0.1; n=$((n + 1)); done;; esac\nexec %s "$@"\n' % (go, shutil.which("find"))) + (shim / "find").chmod(0o755) + env = dict(os.environ, DROIDDECK_LIBRARIES="", DROIDDECK_SEED_LATER="1", PATH="%s:%s" % (shim, os.environ["PATH"])) + marker = '"PhysX Version"=dword:00000001' + subprocess.run(["bash", str(SCRIPT), str(self.steam)], env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True) + self.assertNotIn(marker, self.reg.read_text()) + go.touch() + deadline = time.monotonic() + 30 + while marker not in self.reg.read_text() and time.monotonic() < deadline: + time.sleep(0.2) + self.assertIn(marker, self.reg.read_text()) + before = self.reg.read_text() + subprocess.run(["bash", str(SCRIPT), str(self.steam)], env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True) + time.sleep(0.5) + self.assertEqual(before, self.reg.read_text()) + + def test_a_game_whose_search_failed_is_searched_again(self): + self.game() + broken = self.tmp / "broken" + broken.touch() + shim = self.tmp / "bin" + shim.mkdir() + (shim / "find").write_text('#!/bin/sh\n%s "$@"\n[ ! -e "%s" ]\n' % (shutil.which("find"), broken)) + (shim / "find").chmod(0o755) + env = dict(os.environ, DROIDDECK_LIBRARIES="", PATH="%s:%s" % (shim, os.environ["PATH"])) + subprocess.run(["bash", str(SCRIPT), str(self.steam)], env=env, capture_output=True, check=True) + self.assertNotIn("VCRedist2022", self.reg.read_text()) + broken.unlink() + subprocess.run(["bash", str(SCRIPT), str(self.steam)], env=env, capture_output=True, check=True) + self.assertIn('"VCRedist2022"=dword:00000001', self.reg.read_text()) + + def test_a_later_run_leaves_the_registry_alone_while_a_wine_server_runs(self): + self.game(script=GAME_SCRIPT.replace("Software\\\\Valve\\\\Steam\\\\Apps\\\\CommonRedist\\\\vcredist\\\\2022", "SOFTWARE\\\\AGEIA Technologies").replace("VCRedist2022", "PhysX Version")) + shim = self.tmp / "bin" + shim.mkdir() + (shim / "pgrep").write_text("#!/bin/sh\nexit 0\n") + (shim / "pgrep").chmod(0o755) + env = dict(os.environ, DROIDDECK_LIBRARIES="", DROIDDECK_SEED_LATER="1", PATH="%s:%s" % (shim, os.environ["PATH"])) + subprocess.run(["bash", str(SCRIPT), str(self.steam)], env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True) + cache = self.steam / ".droiddeck-game-scripts" + deadline = time.monotonic() + 30 + while not (cache.exists() and "installscript" in cache.read_text().lower()) and time.monotonic() < deadline: + time.sleep(0.2) + self.assertIn("installscript", cache.read_text().lower()) + time.sleep(1) + self.assertNotIn("PhysX Version", self.reg.read_text()) + env.pop("DROIDDECK_SEED_LATER") + env["PATH"] = os.environ["PATH"] + subprocess.run(["bash", str(SCRIPT), str(self.steam)], env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True) + self.assertIn('"PhysX Version"=dword:00000001', self.reg.read_text()) + def evaluator(self, appid, install_script): script = self.tmp / ("legacycompat/evaluatorscript_%s.vdf" % appid) script.parent.mkdir(parents=True) diff --git a/tools/tests/test_steam_compat_x64.py b/tools/tests/test_steam_compat_x64.py index 9f9abc478a..9d9bf109e0 100644 --- a/tools/tests/test_steam_compat_x64.py +++ b/tools/tests/test_steam_compat_x64.py @@ -99,6 +99,31 @@ class X64RepointTest(unittest.TestCase): self.assertEqual(COMPAT["x64_repoint"](str(self.root), None), []) self.assertEqual((self.root / "config" / "config.vdf").read_text(), before) + def test_new_owned_shortcut_gets_the_x64_default_and_explicit_choice_stays(self): + app = "2350879490" + chosen = "proton-cachyos-a64" + config = self.root / "config" / "config.vdf" + state = self.root / "droiddeck-compat" + self.assertEqual(COMPAT["register_default"]( + str(config), apps=[app], protect={chosen: "proton-cachyos-a64"}, + default="GE-Proton11-7-a64", directory=str(state), + linux_tool="droiddeck-direct", owned=[app]), "GE-Proton11-7-a64") + self.assertEqual(self.mapping()[app], "GE-Proton11-7-a64") + self.assertEqual(COMPAT["register_default"]( + str(config), apps=[app], protect={chosen: "proton-cachyos-a64"}, + default="GE-Proton11-7-a64", directory=str(state), + linux_tool="droiddeck-direct", owned=[app]), "GE-Proton11-7-a64") + self.assertEqual(self.mapping()[app], "GE-Proton11-7-a64") + tokens = COMPAT["tokenize"](config.read_text()) + mapping = COMPAT["mapping_block"](tokens) + COMPAT["set_mapping"](tokens, mapping, app, chosen) + config.write_text(COMPAT["serialize"](tokens)) + COMPAT["register_default"]( + str(config), apps=[app], protect={chosen: "proton-cachyos-a64"}, + default="GE-Proton11-7-a64", directory=str(state), + linux_tool="droiddeck-direct", owned=[app]) + self.assertEqual(self.mapping()[app], chosen) + if __name__ == "__main__": unittest.main() diff --git a/tools/tests/test_steam_games.py b/tools/tests/test_steam_games.py index 16c08e142f..13235e68b4 100644 --- a/tools/tests/test_steam_games.py +++ b/tools/tests/test_steam_games.py @@ -3,6 +3,7 @@ import importlib.util import json import os from pathlib import Path +import shutil import subprocess import tempfile import unittest @@ -56,6 +57,171 @@ class ImportsTest(unittest.TestCase): self.assertEqual(self.folder, (self.steam / 'steamapps/common/DroidDeck-42').resolve()) self.assertEqual(b'game', self.exe.read_bytes()) + def steam_install(self, appid=42): + library = self.root / 'Library' + folder = library / 'steamapps/common/Example' + folder.mkdir(parents=True) + (folder / 'Example.exe').write_bytes(b'game') + (library / f'steamapps/appmanifest_{appid}.acf').write_text(f'"AppState"\n{{\n"appid" "{appid}"\n"installdir" "Example"\n}}\n') + saves = library / f'steamapps/compatdata/{appid}/pfx/drive_c/users/steamuser' + saves.mkdir(parents=True) + (saves / 'save.dat').write_bytes(b'cloud') + return dict(self.game, folder=str(folder), exe=str(folder / 'Example.exe'), dir=str(folder)), library + + def shortcut_prefix(self): + return self.steam / 'steamapps/compatdata' / str(self.game['appid'] & 0xFFFFFFFF) + + def link_shortcut_prefix(self, target, owned=True): + (self.steam / 'steamapps/compatdata').mkdir(parents=True, exist_ok=True) + self.shortcut_prefix().symlink_to(target) + if owned: + imports.save_json(self.steam / 'steamapps' / imports.PREFIX_LINKS, + {str(self.shortcut_prefix()): str(target)}) + + def test_shortcut_of_a_steam_install_shares_the_steam_apps_prefix(self): + game, library = self.steam_install() + (self.steam / 'steamapps').mkdir(parents=True) + (self.steam / 'steamapps/libraryfolders.vdf').write_text(f'"libraryfolders"\n{{\n"1" {{ "path" "{library}" }}\n}}\n') + games, routes = imports.route(self.steam, self.acct, [game]) + self.assertEqual(([game], {}), (games, routes)) + self.assertEqual(library / 'steamapps/compatdata/42', self.shortcut_prefix().resolve()) + self.assertEqual(b'cloud', (self.shortcut_prefix() / 'pfx/drive_c/users/steamuser/save.dat').read_bytes()) + + def test_matching_install_prefix_precedes_an_older_prefix_in_another_library(self): + game, library = self.steam_install() + (self.steam / 'steamapps').mkdir(parents=True) + (self.steam / 'steamapps/libraryfolders.vdf').write_text(f'"libraryfolders"\n{{\n"1" {{ "path" "{library}" }}\n}}\n') + older = self.steam / 'steamapps/compatdata/42/pfx/drive_c/users/steamuser' + older.mkdir(parents=True) + (older / 'save.dat').write_bytes(b'old') + imports.route(self.steam, self.acct, [game]) + self.assertEqual(library / 'steamapps/compatdata/42', self.shortcut_prefix().resolve()) + self.assertEqual(b'cloud', (self.shortcut_prefix() / 'pfx/drive_c/users/steamuser/save.dat').read_bytes()) + self.assertEqual(b'old', (older / 'save.dat').read_bytes()) + + def test_an_existing_shortcut_prefix_is_never_replaced(self): + game, library = self.steam_install() + (self.steam / 'steamapps').mkdir(parents=True, exist_ok=True) + (self.steam / 'steamapps/libraryfolders.vdf').write_text(f'"libraryfolders"\n{{\n"1" {{ "path" "{library}" }}\n}}\n') + local = self.shortcut_prefix() / 'pfx/drive_c' + local.mkdir(parents=True) + (local / 'local.dat').write_bytes(b'local') + imports.route(self.steam, self.acct, [game]) + self.assertFalse(self.shortcut_prefix().is_symlink()) + self.assertEqual(b'local', (local / 'local.dat').read_bytes()) + self.assertEqual(b'cloud', (library / 'steamapps/compatdata/42/pfx/drive_c/users/steamuser/save.dat').read_bytes()) + + def test_shortcuts_without_a_manifest_identity_keep_their_own_prefix(self): + game, library = self.steam_install() + (self.steam / 'steamapps').mkdir(parents=True, exist_ok=True) + (self.steam / 'steamapps/libraryfolders.vdf').write_text(f'"libraryfolders"\n{{\n"1" {{ "path" "{library}" }}\n}}\n') + imports.route(self.steam, self.acct, [self.game, dict(game, folder=str(self.folder.parent / 'Other'))]) + self.assertFalse(os.path.lexists(self.shortcut_prefix())) + + def test_a_manifest_without_a_steam_prefix_links_nothing(self): + game, library = self.steam_install() + shutil.rmtree(library / 'steamapps/compatdata/42') + (self.steam / 'steamapps').mkdir(parents=True, exist_ok=True) + (self.steam / 'steamapps/libraryfolders.vdf').write_text(f'"libraryfolders"\n{{\n"1" {{ "path" "{library}" }}\n}}\n') + imports.route(self.steam, self.acct, [game]) + self.assertFalse(os.path.lexists(self.shortcut_prefix())) + + def test_an_older_prefix_in_another_library_is_not_linked_for_a_steam_install(self): + game, library = self.steam_install() + shutil.rmtree(library / 'steamapps/compatdata/42') + (self.steam / 'steamapps').mkdir(parents=True, exist_ok=True) + (self.steam / 'steamapps/libraryfolders.vdf').write_text(f'"libraryfolders"\n{{\n"1" {{ "path" "{library}" }}\n}}\n') + (self.steam / 'steamapps/compatdata/42/pfx/drive_c').mkdir(parents=True) + imports.route(self.steam, self.acct, [game]) + self.assertFalse(os.path.lexists(self.shortcut_prefix())) + + def test_a_dangling_shortcut_prefix_link_is_replaced(self): + game, library = self.steam_install() + self.link_shortcut_prefix(self.root / 'moved') + imports.route(self.steam, self.acct, [game]) + self.assertEqual(library / 'steamapps/compatdata/42', self.shortcut_prefix().resolve()) + + def test_a_dangling_shortcut_prefix_link_is_removed_without_a_replacement(self): + game, library = self.steam_install() + shutil.rmtree(library / 'steamapps/compatdata/42') + self.link_shortcut_prefix(self.root / 'moved') + imports.route(self.steam, self.acct, [game]) + self.assertFalse(os.path.lexists(self.shortcut_prefix())) + + def test_a_link_the_user_made_is_never_changed(self): + game, library = self.steam_install() + for target in (self.root / 'moved', library / 'steamapps/compatdata/42', self.folder): + if os.path.lexists(self.shortcut_prefix()): + self.shortcut_prefix().unlink() + self.link_shortcut_prefix(target, owned=False) + imports.route(self.steam, self.acct, [game]) + self.assertEqual(str(target), os.readlink(self.shortcut_prefix())) + + def test_a_user_link_to_the_matching_prefix_is_never_recorded_or_removed(self): + game, library = self.steam_install() + target = library / 'steamapps/compatdata/42' + self.link_shortcut_prefix(target, owned=False) + imports.route(self.steam, self.acct, [game]) + self.assertEqual(str(target), os.readlink(self.shortcut_prefix())) + self.assertNotIn(str(self.shortcut_prefix()), imports.read_json(self.steam / 'steamapps' / imports.PREFIX_LINKS, {})) + shutil.rmtree(target) + imports.route(self.steam, self.acct, [game]) + self.assertTrue(os.path.islink(self.shortcut_prefix())) + self.assertEqual(str(target), os.readlink(self.shortcut_prefix())) + + def test_our_link_survives_a_library_that_is_temporarily_missing(self): + game, library = self.steam_install() + imports.route(self.steam, self.acct, [game]) + hidden = self.root / 'Hidden' + library.rename(hidden) + imports.route(self.steam, self.acct, [game]) + self.assertTrue(os.path.islink(self.shortcut_prefix())) + hidden.rename(library) + imports.route(self.steam, self.acct, [game]) + self.assertEqual(library / 'steamapps/compatdata/42', self.shortcut_prefix().resolve()) + self.assertEqual(b'cloud', (self.shortcut_prefix() / 'pfx/drive_c/users/steamuser/save.dat').read_bytes()) + + def test_our_link_is_dropped_once_its_prefix_is_deleted(self): + game, library = self.steam_install() + imports.route(self.steam, self.acct, [game]) + shutil.rmtree(library / 'steamapps/compatdata/42') + imports.route(self.steam, self.acct, [game]) + self.assertFalse(os.path.lexists(self.shortcut_prefix())) + self.assertEqual({}, imports.read_json(self.steam / 'steamapps' / imports.PREFIX_LINKS, None)) + + def test_a_replaced_link_record_is_forgotten_when_the_user_makes_a_real_prefix(self): + game, library = self.steam_install() + imports.route(self.steam, self.acct, [game]) + self.shortcut_prefix().unlink() + (self.shortcut_prefix() / 'pfx/drive_c').mkdir(parents=True) + imports.route(self.steam, self.acct, [game]) + self.assertFalse(self.shortcut_prefix().is_symlink()) + self.assertEqual({}, imports.read_json(self.steam / 'steamapps' / imports.PREFIX_LINKS, None)) + + def test_a_shortcut_prefix_with_its_own_saves_is_reported_and_kept(self): + game, library = self.steam_install() + local = self.shortcut_prefix() / 'pfx/drive_c' + local.mkdir(parents=True) + with patch('builtins.print') as printed: + imports.route(self.steam, self.acct, [game]) + self.assertTrue(local.is_dir()) + self.assertIn('keeps its own prefix', printed.call_args_list[-1][0][0]) + + def test_a_winnative_game_shares_the_prefix_the_steam_client_uses(self): + self.winnative_manifest() + (self.steam / 'steamapps/libraryfolders.vdf').parent.mkdir(parents=True, exist_ok=True) + saves = self.steam / 'steamapps/compatdata/42/pfx/drive_c/users/steamuser' + saves.mkdir(parents=True) + (saves / 'save.dat').write_bytes(b'cloud') + imports.share_prefix(self.steam, self.game) + self.assertEqual(self.steam / 'steamapps/compatdata/42', self.shortcut_prefix().resolve()) + + def test_an_unreadable_library_does_not_stop_the_routing(self): + with patch.object(Path, 'glob', side_effect=PermissionError): + games, routes = imports.route(self.steam, self.acct, [self.game]) + self.assertEqual([self.game], games) + self.assertFalse(os.path.lexists(self.shortcut_prefix())) + def test_store_installs_stay_shortcuts_even_when_owned_on_steam(self): self.snapshot() game = dict(self.game, store='amazon') diff --git a/tools/tests/test_steam_x64_runtime_libs.py b/tools/tests/test_steam_x64_runtime_libs.py new file mode 100644 index 0000000000..6f3f71c3f4 --- /dev/null +++ b/tools/tests/test_steam_x64_runtime_libs.py @@ -0,0 +1,67 @@ +import os +from pathlib import Path +import re +import subprocess +import tempfile +import unittest + + +SCRIPT = Path(__file__).resolve().parents[1] / 'linuxfs/overlay/usr/local/bin/droiddeck-steam-x64' +SOURCE = SCRIPT.read_text() +LIBRARY_LOOP = re.search(r'^for d in "\$STEAM_X64"/steamrt64/.*?^done\nFEX_ROOTFS=', SOURCE, re.M | re.S).group() +LIBRARY_LOOP = LIBRARY_LOOP[:LIBRARY_LOOP.rfind('\nFEX_ROOTFS=')] + + +class SteamX64RuntimeLibsTest(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + self.root = Path(self.temp.name) + self.steam = self.root / 'Steam' + self.runtime = self.steam / 'steamrt64/pv-runtime/steam-runtime-steamrt' + self.lib = self.runtime / 'steamrt3c_platform_a/files/lib/x86_64-linux-gnu' + self.usr_lib = self.runtime / 'steamrt3c_platform_a/files/usr/lib/x86_64-linux-gnu' + self.lib.mkdir(parents=True) + self.usr_lib.mkdir(parents=True) + self.dest = self.root / 'steamrt-libs' + self.dest.mkdir() + + def run_loop(self): + shell = 'srt_libs="$DEST"\n' + LIBRARY_LOOP + env = dict(os.environ, STEAM_X64=str(self.steam), DEST=str(self.dest)) + return subprocess.run(['bash', '-eu', '-c', shell], env=env, capture_output=True, text=True, timeout=10) + + def test_empty_library_directory_is_skipped(self): + (self.usr_lib / 'libexample.so.1').touch() + result = self.run_loop() + self.assertEqual(0, result.returncode, result.stderr) + self.assertTrue((self.dest / 'libexample.so.1').is_symlink()) + + def test_two_platform_versions_with_empty_lib_dirs_use_usr_lib(self): + platform_b = self.runtime / 'steamrt3c_platform_b' + (platform_b / 'files/lib/x86_64-linux-gnu').mkdir(parents=True) + usr_lib_b = platform_b / 'files/usr/lib/x86_64-linux-gnu' + usr_lib_b.mkdir(parents=True) + (self.usr_lib / 'libexample.so.1').touch() + (usr_lib_b / 'libother.so.1').touch() + result = self.run_loop() + self.assertEqual(0, result.returncode, result.stderr) + self.assertTrue((self.dest / 'libexample.so.1').is_symlink()) + self.assertTrue((self.dest / 'libother.so.1').is_symlink()) + + def test_stale_literal_glob_link_does_not_abort(self): + (self.dest / '*.so*').symlink_to('/missing/*.so*') + result = self.run_loop() + self.assertEqual(0, result.returncode, result.stderr) + self.assertTrue((self.dest / '*.so*').is_symlink()) + + def test_existing_dangling_library_link_is_not_recreated(self): + (self.lib / 'libexample.so.1').touch() + (self.dest / 'libexample.so.1').symlink_to('/missing/libexample.so.1') + result = self.run_loop() + self.assertEqual(0, result.returncode, result.stderr) + self.assertEqual('/missing/libexample.so.1', os.readlink(self.dest / 'libexample.so.1')) + + +if __name__ == '__main__': + unittest.main() diff --git a/tools/tests/test_store_launch_ea.py b/tools/tests/test_store_launch_ea.py index 2dd72b324b..9096d2d3c8 100644 --- a/tools/tests/test_store_launch_ea.py +++ b/tools/tests/test_store_launch_ea.py @@ -35,6 +35,52 @@ class EaHook(unittest.TestCase): self.assertIn((r'HKEY_LOCAL_MACHINE\SOFTWARE\EA Games\Game', 'DisplayName', 'Mass Effect 3'), entries) self.assertIn((r'HKEY_LOCAL_MACHINE\SOFTWARE\Respawn\Titanfall2', 'DisplayName', 'Mass Effect 3'), entries) + def test_the_games_exe_maps_to_its_launcher_only(self): + with tempfile.TemporaryDirectory() as tmp: + folder = Path(tmp) / 'Game' + (folder / 'bin').mkdir(parents=True) + for name in ('bin/Game.exe', 'bin/Other.exe', store.LAUNCHER): + (folder / name).write_text('x') + sidecar = {'store': 'ea', 'id': 'Origin.OFR.50.1', 'exe': 'bin/Game.exe', 'launcher': store.LAUNCHER} + (folder / store.SIDECAR).write_text(json.dumps(sidecar)) + self.assertEqual(store.store_launcher(str(folder / 'bin/Game.exe')), str(folder / store.LAUNCHER)) + self.assertEqual(store.store_launcher(str(folder / 'bin/game.exe')), str(folder / store.LAUNCHER)) + self.assertIsNone(store.store_launcher(str(folder / 'bin/Other.exe'))) + self.assertIsNone(store.store_launcher(str(Path(tmp) / 'Elsewhere.exe'))) + (folder / store.SIDECAR).write_text(json.dumps(dict(sidecar, launcher=''))) + self.assertIsNone(store.store_launcher(str(folder / 'bin/Game.exe'))) + + def test_a_symlinked_or_deep_exe_still_finds_its_launcher(self): + with tempfile.TemporaryDirectory() as tmp: + folder = Path(tmp) / 'Game' + deep = folder / 'a/b/c/d/e/f' + deep.mkdir(parents=True) + (deep / 'Game.exe').write_text('x') + (folder / store.LAUNCHER).write_text('x') + sidecar = {'store': 'ea', 'id': 'Origin.OFR.50.1', 'exe': 'a/b/c/d/e/f/Game.exe', 'launcher': store.LAUNCHER} + (folder / store.SIDECAR).write_text(json.dumps(sidecar)) + link = Path(tmp) / 'x/y/z/Link.exe' + link.parent.mkdir(parents=True) + link.symlink_to(deep / 'Game.exe') + expected = str(folder.resolve() / store.LAUNCHER) + self.assertEqual(store.store_launcher(str(deep / 'Game.exe')), expected) + self.assertEqual(store.store_launcher(str(link)), expected) + self.assertIsNone(store.find_store_game([str(deep / 'Game.exe')])) + + def test_a_symlinked_exe_finds_the_sidecar_beside_the_link(self): + with tempfile.TemporaryDirectory() as tmp: + outside = Path(tmp) / 'Real/Game.exe' + outside.parent.mkdir() + outside.write_text('x') + folder = Path(tmp) / 'Game' + folder.mkdir() + (folder / store.LAUNCHER).write_text('x') + (folder / 'Game.exe').symlink_to(outside) + sidecar = {'store': 'ea', 'id': 'Origin.OFR.50.1', 'exe': 'Game.exe', 'launcher': store.LAUNCHER} + (folder / store.SIDECAR).write_text(json.dumps(sidecar)) + self.assertEqual(store.store_launcher(str(folder / 'Game.exe')), str(folder / store.LAUNCHER)) + self.assertIsNone(store.store_launcher(str(outside))) + def test_legacy_games_are_registered_by_content_id(self): sidecar = {'id': 'Origin.OFR.50.0005237', 'title': 'Mass Effect 3 (2012)', 'extra': {'contentIds': '71073,71183, bad id', 'displayName': 'Mass Effect 3', 'locale': 'fr_FR'}} diff --git a/tools/tests/test_store_launch_rockstar.py b/tools/tests/test_store_launch_rockstar.py new file mode 100644 index 0000000000..23cd6ae632 --- /dev/null +++ b/tools/tests/test_store_launch_rockstar.py @@ -0,0 +1,197 @@ +import json +import os +from pathlib import Path +import tempfile +import time +import unittest +from unittest.mock import patch + +from test_store_launch import store + + +class RockstarLaunch(unittest.TestCase): + def test_service_directory_cannot_export_sessions_outside_the_prefix(self): + with tempfile.TemporaryDirectory() as root: + folder, sidecar, prefix, _, _ = self.setup_game(root) + outside = Path(root) / 'outside' + outside.mkdir() + target = prefix / 'pfx' / store.ROCKSTAR_FOLDER + target.parent.mkdir(parents=True) + target.symlink_to(outside, target_is_directory=True) + sentinel = outside / 'launch.json' + sentinel.write_text('keep') + with patch.object(store, 'ask') as ask: + self.assertEqual('invalid-service-path', store.prepare_rockstar(folder, sidecar, prefix, 'channel')) + ask.assert_not_called() + self.assertEqual('keep', sentinel.read_text()) + + def test_sdk_registration_does_not_use_an_untrusted_display_name_as_a_key(self): + with tempfile.TemporaryDirectory() as root: + folder, _, prefix, _, _ = self.setup_game(root) + with patch.object(store, 'wait_for_server', return_value=True): + self.assertTrue(store.rockstar_registry(folder, None, prefix, '', sdk_arch='x64')) + text = (prefix / 'pfx/system.reg').read_text() + self.assertIn(r'[Software\\Rockstar Games\\Rockstar Games Social Club]', text) + self.assertNotIn('Grand Theft Auto', text) + + def test_root_metadata_is_found_after_many_assets(self): + with tempfile.TemporaryDirectory() as root: + folder = Path(root) + for index in range(300): + (folder / ('asset-%s.dat' % index)).write_bytes(b'asset') + (folder / 'title.rgl').write_bytes(b'RGLM' + bytes(108)) + self.assertTrue(store.rockstar_sdk(folder, {'id': 'future_title', 'exe': 'Game.exe'})) + (folder / 'title.rgl').unlink() + (folder / 'Title.RGL').write_bytes(b'RGLM' + bytes(108)) + self.assertTrue(store.rockstar_sdk(folder, {'id': 'future_title', 'exe': 'Game.exe'})) + + def test_sdk_titles_receive_only_their_short_lived_game_session(self): + with tempfile.TemporaryDirectory() as root: + def change(values): + folder, sidecar, _, _, answer = values + sidecar['id'] = 'future_title' + (folder / 'socialclub.dll').write_bytes(b'game-runtime') + answer['session'] = {'accountId': '123', 'identity': 'player@example.invalid', 'ticket': 'game-session', + 'ScAuthToken': 'never-export-refresh-token'} + result, path, _ = self.prepare(root, change) + self.assertEqual('ready', result) + data = json.loads(path.read_text()) + self.assertEqual({'accountId', 'identity', 'ticket'}, set(data['session'])) + self.assertNotIn('pipe', data) + self.assertNotIn('material', data) + self.assertNotIn('never-export-refresh-token', path.read_text()) + self.assertEqual(0o600, path.stat().st_mode & 0o777) + + def test_invalid_sdk_sessions_cannot_reuse_an_old_handoff(self): + for session in (None, {'accountId': '0', 'identity': 'player', 'ticket': 'session'}, + {'accountId': '123', 'identity': 'player', 'ticket': 'bad\0session'}): + with self.subTest(session=session), tempfile.TemporaryDirectory() as root: + def change(values): + folder, sidecar, _, _, answer = values + sidecar['id'] = 'future_title' + (folder / 'socialclub.dll').write_bytes(b'game-runtime') + answer['session'] = session + result, path, _ = self.prepare(root, change) + self.assertEqual('invalid-sdk-session', result) + self.assertFalse(path.exists()) + + def test_sdk_detection_does_not_follow_external_metadata(self): + with tempfile.TemporaryDirectory() as root: + folder = Path(root) / 'game' + folder.mkdir() + metadata = Path(root) / 'outside.rgl' + metadata.write_bytes(b'RGLM' + bytes(108)) + (folder / 'title.rgl').symlink_to(metadata) + self.assertFalse(store.rockstar_sdk(folder, {'id': 'future_title', 'exe': 'Game.exe'})) + + def test_sdk_installer_cannot_escape_its_architecture_folder(self): + with tempfile.TemporaryDirectory() as root: + folder = Path(root) / 'game' + installer = folder / 'Installers/Social-Club-Setup.exe' + installer.parent.mkdir(parents=True) + installer.write_bytes(b'installer') + listing = type('Listing', (), {'returncode': 0, 'stdout': b'Path = x64/../../outside.dll\nSize = 1\n'})() + with patch.object(store.shutil, 'which', return_value='/bin/7z'), patch.object(store.subprocess, 'run', return_value=listing): + with self.assertRaises(ValueError): + store.rockstar_runtime(folder, folder / 'Game.exe', str(Path(root) / 'prefix'), 'x64') + self.assertFalse((Path(root) / 'outside.dll').exists()) + + def test_other_titles_can_launch_without_the_classic_pipe_service(self): + with tempfile.TemporaryDirectory() as root: + folder = Path(root) + sidecar = {'store': 'rockstar', 'id': 'rdr2', 'exe': 'RDR2.exe'} + with patch.object(store, 'find_store_game', return_value=(folder, sidecar)), \ + patch.object(store, 'prepare_rockstar') as prepare, \ + patch.object(store, 'ask') as ask, patch.dict(os.environ, {}, clear=True): + self.assertEqual(store.STORE_GAME, store.main([str(folder / 'RDR2.exe')])) + prepare.assert_not_called() + ask.assert_not_called() + + def test_classic_authentication_failure_still_stops_launch(self): + with tempfile.TemporaryDirectory() as root: + folder = Path(root) + sidecar = {'store': 'rockstar', 'id': 'gtavc', 'exe': 'gta-vc.exe'} + with patch.object(store, 'find_store_game', return_value=(folder, sidecar)), \ + patch.object(store, 'prepare_rockstar', return_value='session-not-owned'), \ + patch.dict(os.environ, {}, clear=True): + self.assertEqual(store.RAN_FAILED, store.main([str(folder / 'gta-vc.exe')])) + + def setup_game(self, root): + folder = Path(root) / 'game' + folder.mkdir() + exe = bytearray(128) + exe[:2] = b'MZ' + exe[0x3c:0x40] = (64).to_bytes(4, 'little') + exe[64:70] = b'PE\0\0\x4c\x01' + (folder / 'gta-vc.exe').write_bytes(exe) + (folder / 'MTLX.dll').write_bytes(b'vendor') + prefix = Path(root) / 'prefix' + (prefix / 'pfx').mkdir(parents=True) + (prefix / 'pfx/user.reg').write_text('WINE REGISTRY Version 2\n') + (prefix / 'pfx/system.reg').write_text('WINE REGISTRY Version 2\n') + service = Path(root) / 'service' + service.mkdir() + (service / 'Launcher32.exe').write_bytes(b'compiled-helper') + sidecar = {'store': 'rockstar', 'id': 'gtavc', 'exe': 'gta-vc.exe', 'args': ['one argument', '&literal']} + answer = {'ok': True, 'pipe': 'GTA-VC_Pipe', 'material': 'A' * 640, + 'expiresAt': int(time.time() * 1000) + 90000, 'ticket': 'must-not-be-exported'} + return folder, sidecar, prefix, service, answer + + def prepare(self, root, modify=lambda values: None): + values = self.setup_game(root) + modify(values) + folder, sidecar, prefix, service, answer = values + config = prefix / 'pfx' / store.ROCKSTAR_FOLDER / 'launch.json' + config.parent.mkdir(parents=True) + config.write_text('stale') + requests = [] + + def ask(channel, request, timeout): + requests.append(request) + return answer + + with patch.object(store, 'ROCKSTAR_SERVICE', service), patch.object(store, 'rockstar_registry', return_value=True): + result = store.prepare_rockstar(folder, sidecar, str(prefix), str(Path(root) / 'channel'), ask_app=ask) + return result, config, requests + + def test_handoff_contains_only_launch_fields_and_preserves_argument_boundaries(self): + with tempfile.TemporaryDirectory() as root: + result, path, requests = self.prepare(root) + self.assertEqual('ready', result) + data = json.loads(path.read_text()) + self.assertEqual({'folder', 'exe', 'workdir', 'args', 'pipe', 'material', 'expiresAt'}, set(data)) + self.assertEqual(['one argument', '&literal'], data['args']) + self.assertNotIn('must-not-be-exported', path.read_text()) + self.assertEqual('rockstar-launch', requests[0]['op']) + self.assertEqual(b'compiled-helper', path.with_name('Launcher.exe').read_bytes()) + + def test_rejected_or_expired_sessions_cannot_reuse_stale_material(self): + for update in ({'ok': False, 'reason': 'not-owned'}, {'material': 'A' * 641}, {'expiresAt': 1}): + with self.subTest(update=update), tempfile.TemporaryDirectory() as root: + result, config, _ = self.prepare(root, lambda values: values[4].update(update)) + self.assertNotEqual('ready', result) + self.assertFalse(config.exists()) + + def test_path_escape_does_not_request_account_data(self): + with tempfile.TemporaryDirectory() as root: + def change(values): + (Path(root) / 'outside.exe').write_bytes(b'MZ') + values[1]['exe'] = '../outside.exe' + result, config, requests = self.prepare(root, change) + self.assertEqual('invalid-game-path', result) + self.assertEqual([], requests) + self.assertFalse(config.exists()) + + def test_writes_both_registry_views_and_escapes_values(self): + with tempfile.TemporaryDirectory() as root: + folder, _, prefix, _, _ = self.setup_game(root) + with patch.object(store, 'wait_for_server', return_value=True): + self.assertTrue(store.rockstar_registry(folder, 'Grand Theft Auto: Vice City', prefix, '')) + text = (prefix / 'pfx/system.reg').read_text() + self.assertIn(r'[Software\\Rockstar Games\\Launcher]', text) + self.assertIn(r'[Software\\Wow6432Node\\Rockstar Games\\Launcher]', text) + self.assertIn('Grand Theft Auto: Vice City', text) + + +if __name__ == '__main__': + unittest.main() diff --git a/tools/tests/test_venus_preload.py b/tools/tests/test_venus_preload.py new file mode 100644 index 0000000000..9f90a78f6b --- /dev/null +++ b/tools/tests/test_venus_preload.py @@ -0,0 +1,66 @@ +import os +from pathlib import Path +import shutil +import subprocess +import tempfile +import unittest + +PRELOAD = Path(__file__).resolve().parents[1] / "linuxfs/preload" + +PROGRAM = r""" +#include +#include +int unsetenv(const char *name) { return -1; } +int setenv(const char *name, const char *value, int overwrite) { return -1; } +int putenv(char *string) { return -1; } +int main(void) { + const char *names[] = {"LIBGL_KOPPER_DISABLE", "LIBGL_KOPPER_DISABLE_X", "ZINK_DEBUG", "VN_DEBUG"}; + for (int i = 0; i < 4; i++) { + const char *value = getenv(names[i]); + printf("%s=%s\n", names[i], value ? value : "(unset)"); + } + return 0; +} +""" + + +@unittest.skipUnless(shutil.which("cc"), "needs cc") +class VenusPreloadTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.tmp = Path(tempfile.mkdtemp()) + source = cls.tmp / "program.c" + source.write_text(PROGRAM) + cls.program = cls.tmp / "program" + cls.library = cls.tmp / "libvenus.so" + subprocess.run(["cc", "-O2", "-Wall", "-Werror", "-o", str(cls.program), str(source)], check=True) + subprocess.run(["cc", "-O2", "-Wall", "-Werror", "-shared", "-fPIC", "-o", str(cls.library), + str(PRELOAD / "venus.c")], check=True) + + @classmethod + def tearDownClass(cls): + shutil.rmtree(cls.tmp, ignore_errors=True) + + def values(self, **extra): + env = {"PATH": os.environ.get("PATH", ""), "LD_PRELOAD": str(self.library), **extra} + result = subprocess.run([str(self.program)], env=env, capture_output=True, text=True, check=True) + return dict(line.split("=", 1) for line in result.stdout.splitlines()) + + def test_kopper_is_kept_when_environment_changes_are_refused(self): + values = self.values(VN_DEBUG="vtest", LIBGL_KOPPER_DISABLE="true", LIBGL_KOPPER_DISABLE_X="1", + ZINK_DEBUG="mem") + self.assertEqual(values["LIBGL_KOPPER_DISABLE"], "(unset)") + self.assertEqual(values["LIBGL_KOPPER_DISABLE_X"], "1") + self.assertEqual(values["ZINK_DEBUG"], "mem") + self.assertEqual(values["VN_DEBUG"], "vtest") + + def test_other_sessions_keep_kopper_disabled(self): + self.assertEqual(self.values(LIBGL_KOPPER_DISABLE="true")["LIBGL_KOPPER_DISABLE"], "true") + self.assertEqual(self.values(VN_DEBUG="init", LIBGL_KOPPER_DISABLE="true")["LIBGL_KOPPER_DISABLE"], "true") + + def test_absent_variable_is_harmless(self): + self.assertEqual(self.values(VN_DEBUG="vtest")["LIBGL_KOPPER_DISABLE"], "(unset)") + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_wayland_clock_domain.py b/tools/tests/test_wayland_clock_domain.py new file mode 100644 index 0000000000..a805ff9c09 --- /dev/null +++ b/tools/tests/test_wayland_clock_domain.py @@ -0,0 +1,267 @@ +import ctypes +import mmap +import shutil +from pathlib import Path +import struct +import subprocess +import tempfile +import unittest + +from tools.tests.test_clock_pause_preload import clock_reset_command +from tools.tests.test_output_refresh import extract_function as extract_void_function +from tools.tests.test_scene_limit_hold import extract_function + +SOURCE = Path(__file__).resolve().parents[2] / "app/src/main/cpp/waylandcomp/src/clock_domain.c" +HEADER = SOURCE.with_suffix(".h") + + +@unittest.skipUnless(shutil.which("cc"), "needs a C compiler") +class WaylandClockDomainTest(unittest.TestCase): + def test_host_timestamp_uses_the_guest_domain(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + control = root / "clock" + control.write_bytes(struct.pack("\n' + '#include "clock_domain.h"\n' + 'int main(int argc, char **argv) { (void)argc;\n' + ' droiddeck_clock_domain_set_control(argv[1]);\n' + ' printf("%lld %u %lld\\n", (long long)droiddeck_clock_domain_adjust_ns(30LL * 1000000000LL), ' + ' droiddeck_clock_domain_now_ms(), (long long)droiddeck_clock_domain_adjust_ns(5LL * 1000000000LL));\n' + ' return 0;\n' + '}\n' + ) + binary = root / "program" + subprocess.run(["cc", "-Wall", "-Wextra", "-Werror", "-O2", "-I", str(SOURCE.parent), "-o", str(binary), str(program), str(SOURCE)], + check=True) + result = subprocess.run([str(binary), str(control)], capture_output=True, text=True, check=True) + adjusted, now_ms, clamped = map(int, result.stdout.split()) + self.assertEqual(adjusted, 20_000_000_000) + self.assertGreaterEqual(now_ms, 0) + self.assertLessEqual(now_ms, 0xFFFFFFFF) + self.assertEqual(clamped, 0) + + def test_paced_release_uses_kernel_time_across_pause_offsets(self): + compositor = SOURCE.with_name("compositor.c").read_text() + functions = extract_function(compositor, "now_ns") + "\n" + extract_void_function(compositor, "arm_release_timer") + harness = r''' +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include +#include "clock_domain.h" + +struct pending_release { void *buffer; int64_t at_ns; struct pending_release *next; }; +static struct pending_release *g_pending_releases; +static int g_release_timer_fd; +#define wl_list_for_each(pr, list, link) for (pr = *(list); pr; pr = pr->next) +static int buffer_release_blocked(void *buffer) { return buffer != NULL; } + +@FUNCTIONS@ + +int main(int argc, char **argv) { + (void)argc; + droiddeck_clock_domain_set_control(argv[1]); + int control = open(argv[1], O_WRONLY); + assert(control >= 0); + g_release_timer_fd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK | TFD_CLOEXEC); + assert(g_release_timer_fd >= 0); + const int64_t offsets[] = {0, 10000000000LL, 300000000000LL}; + for (unsigned i = 0; i < sizeof(offsets) / sizeof(offsets[0]); i++) { + assert(pwrite(control, &offsets[i], sizeof(offsets[i]), 0) == sizeof(offsets[i])); + struct timespec started, ended; + clock_gettime(CLOCK_MONOTONIC, &started); + int64_t start = now_ns(); + struct pending_release blocked = {(void *)1, start + 1000000LL, NULL}; + struct pending_release release = {NULL, start + 60000000LL, &blocked}; + g_pending_releases = &release; + arm_release_timer(); + int64_t next_offset = offsets[i] + 10000000000LL; + assert(pwrite(control, &next_offset, sizeof(next_offset), 0) == sizeof(next_offset)); + struct pollfd pollfd = {g_release_timer_fd, POLLIN, 0}; + assert(poll(&pollfd, 1, 1000) == 1); + clock_gettime(CLOCK_MONOTONIC, &ended); + int64_t elapsed = (ended.tv_sec - started.tv_sec) * 1000000000LL + ended.tv_nsec - started.tv_nsec; + assert(elapsed >= 50000000LL && elapsed < 1000000000LL); + uint64_t expirations; + assert(read(g_release_timer_fd, &expirations, sizeof(expirations)) == sizeof(expirations)); + assert(expirations == 1); + g_pending_releases = &blocked; + arm_release_timer(); + struct itimerspec remaining; + assert(timerfd_gettime(g_release_timer_fd, &remaining) == 0); + assert(remaining.it_value.tv_sec == 0 && remaining.it_value.tv_nsec == 0); + } + close(g_release_timer_fd); + close(control); + return 0; +} +''' + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + control = root / "clock" + control.write_bytes(struct.pack("\n' + '#include "clock_domain.h"\n' + 'int main(int argc, char **argv) { (void)argc;\n' + ' droiddeck_clock_domain_set_control(argv[1]);\n' + ' printf("%lld\\n", (long long)droiddeck_clock_domain_adjust_ns(30LL * 1000000000LL));\n' + ' droiddeck_clock_domain_set_control(argv[2]);\n' + ' printf("%lld\\n", (long long)droiddeck_clock_domain_adjust_ns(30LL * 1000000000LL));\n' + ' return 0;\n' + '}\n' + ) + binary = root / "program" + subprocess.run(["cc", "-Wall", "-Wextra", "-Werror", "-O2", "-I", str(SOURCE.parent), "-o", str(binary), str(program), str(SOURCE)], + check=True) + result = subprocess.run([str(binary), str(control), str(root / "missing")], capture_output=True, text=True, check=True) + self.assertEqual(result.stdout.split(), ["30000000000", "30000000000"]) + + def test_replaced_control_file_updates_offset_without_invalidating_readers(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + control = root / "clock" + replacement = root / "replacement" + control.write_bytes(struct.pack("\n' + '#include "clock_domain.h"\n' + 'int main(int argc, char **argv) { (void)argc;\n' + ' droiddeck_clock_domain_set_control(argv[1]);\n' + ' printf("%lld\\n", (long long)droiddeck_clock_domain_adjust_ns(30LL * 1000000000LL));\n' + ' if (rename(argv[2], argv[1]) != 0) return 1;\n' + ' droiddeck_clock_domain_set_control(argv[1]);\n' + ' printf("%lld\\n", (long long)droiddeck_clock_domain_adjust_ns(30LL * 1000000000LL));\n' + ' return 0;\n' + '}\n' + ) + binary = root / "program" + subprocess.run(["cc", "-Wall", "-Wextra", "-Werror", "-O2", "-I", str(SOURCE.parent), "-o", str(binary), str(program), str(SOURCE)], + check=True) + result = subprocess.run([str(binary), str(control), str(replacement)], capture_output=True, text=True, check=True) + self.assertEqual(result.stdout.split(), ["20000000000", "10000000000"]) + + def test_session_transition_clears_stale_offset_but_live_failures_preserve_it(self): + harness = r''' +#include +#include +#include +#include +#include "clock_domain.h" + +int main(int argc, char **argv) { + (void)argc; + int64_t shift = 10000000000LL; + int fd = open(argv[1], O_CREAT | O_RDWR, 0600); + assert(fd >= 0); + assert(write(fd, &shift, sizeof(shift)) == sizeof(shift)); + droiddeck_clock_domain_set_control(argv[1]); + assert(droiddeck_clock_domain_adjust_ns(30000000000LL) == 20000000000LL); + assert(unlink(argv[1]) == 0); + droiddeck_clock_domain_set_control(argv[1]); + assert(droiddeck_clock_domain_adjust_ns(30000000000LL) == 20000000000LL); + int replacement = open(argv[1], O_CREAT | O_RDWR, 0600); + assert(replacement >= 0); + droiddeck_clock_domain_set_control(argv[1]); + assert(droiddeck_clock_domain_adjust_ns(30000000000LL) == 20000000000LL); + droiddeck_clock_domain_set_control(NULL); + droiddeck_clock_domain_set_control(argv[1]); + assert(droiddeck_clock_domain_adjust_ns(30000000000LL) == 30000000000LL); + shift = 20000000000LL; + assert(write(replacement, &shift, sizeof(shift)) == sizeof(shift)); + droiddeck_clock_domain_set_control(argv[1]); + assert(droiddeck_clock_domain_adjust_ns(30000000000LL) == 10000000000LL); + close(replacement); + close(fd); + return 0; +} +''' + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + program = root / "program.c" + program.write_text(harness) + binary = root / "program" + subprocess.run(["cc", "-Wall", "-Wextra", "-Werror", "-O2", "-I", str(SOURCE.parent), + "-o", str(binary), str(program), str(SOURCE)], check=True) + subprocess.run([str(binary), str(root / "clock")], check=True, timeout=5) + host = SOURCE.parents[3] / "java/com/droiddeck/launcher/wayland/CompositorHost.kt" + self.assertIn("nativeSetClockControl(null)", host.read_text().split("fun newSession() {", 1)[1].split("}", 1)[0]) + + def test_startup_reset_keeps_host_and_guest_on_the_same_inode(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + control = root / "clock" + control.write_bytes(struct.pack("\n' + '#include "clock_domain.h"\n' + 'int main(int argc, char **argv) { (void)argc;\n' + ' droiddeck_clock_domain_set_control(argv[1]);\n' + ' printf("%lld\\n", (long long)droiddeck_clock_domain_adjust_ns(30LL * 1000000000LL));\n' + ' if (rename(argv[2], argv[1]) != 0) return 1;\n' + ' droiddeck_clock_domain_set_control(argv[1]);\n' + ' printf("%lld\\n", (long long)droiddeck_clock_domain_adjust_ns(30LL * 1000000000LL));\n' + ' return 0;\n' + '}\n' + ) + binary = root / "program" + subprocess.run(["cc", "-Wall", "-Wextra", "-Werror", "-O2", "-I", str(SOURCE.parent), + "-o", str(binary), str(program), str(SOURCE)], check=True) + result = subprocess.run([str(binary), str(control), str(replacement)], capture_output=True, text=True, check=True) + self.assertEqual(result.stdout.split(), ["30000000000", "10000000000"]) + + +if __name__ == "__main__": + unittest.main()