chore: merge main into feat/bt-controller-trinket

This commit is contained in:
Kurt Himebauch committed 2026-11-13 11:47:32 -05:00
commit aade03b7cf
291 files changed
+20941 -1020

No files matched your search

+12 -5
View File
@@ -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
+1
View File
@@ -36,3 +36,4 @@ __pycache__/
app/src/main/assets/directaudio/
app/src/main/assets/hybris/
/tools/vr/out/
app/src/main/resources/rockstar/helpers/
+10
View File
@@ -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.
+10
View File
@@ -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'
+16
View File
@@ -18,8 +18,15 @@
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.SECONDARY_HOME" />
</intent>
<intent>
<action android:name="org.adw.launcher.THEMES" />
</intent>
<intent>
<action android:name="com.novalauncher.THEME" />
</intent>
</queries>
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<uses-permission android:name="android.permission.REORDER_TASKS" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />
@@ -146,6 +153,7 @@
<category android:name="android.intent.category.BROWSABLE" />
<category android:name="android.intent.category.CAR_LAUNCHER" />
<data android:scheme="droiddeck" android:host="game" />
<data android:scheme="droiddeck" android:host="soundtrack" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.CREATE_SHORTCUT" />
@@ -339,6 +347,14 @@
android:name=".sync.SyncthingService"
android:exported="false"
android:foregroundServiceType="dataSync" />
<service
android:name=".playback.SoundtrackService"
android:exported="true"
android:foregroundServiceType="mediaPlayback">
<intent-filter>
<action android:name="androidx.media3.session.MediaSessionService" />
</intent-filter>
</service>
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.logs"
+8 -18
View File
@@ -1,27 +1,17 @@
#!/bin/bash
# GitHub sign-in through Android's browser, with the one-time code typed in for the person.
serial=${ADB_SERIAL:-127.0.0.1:5555}
display=${DD_BROWSER_DISPLAY:-0}
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; }
# 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"
+2
View File
@@ -0,0 +1,2 @@
#!/bin/sh
exec python3 /root/.local/share/droiddeck/ctl/droiddeckctl "$@"
@@ -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
@@ -0,0 +1,72 @@
#define _GNU_SOURCE
#include "clock_domain.h"
#include <fcntl.h>
#include <pthread.h>
#include <stdint.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <time.h>
#include <unistd.h>
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);
}
@@ -0,0 +1,11 @@
#ifndef DROIDDECK_CLOCK_DOMAIN_H
#define DROIDDECK_CLOCK_DOMAIN_H
#include <stdint.h>
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
@@ -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,
@@ -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) {
@@ -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;
@@ -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;
@@ -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() {
@@ -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<List<Library.SteamGame>>(emptyList())
private var soundtracksLoaded by mutableStateOf(false)
private var gameStoresSpeedTier by mutableStateOf("fast")
private var navRequest by mutableStateOf<String?>(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<String, SoundtrackRemoval>()
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()
@@ -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()
}
}
@@ -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())
@@ -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<Map<String, Choice>>(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<String, Choice>) {
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<String, Choice>? {
val parts = entry.split(SEPARATOR)
if (parts.size != 3 || parts.any { it.isEmpty() }) return null
return parts[0] to Choice(parts[1], parts[2])
}
}
@@ -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<String, String>, val calendars: Map<String, String>, 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<Pack> {
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<String> {
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<String> {
val names = LinkedHashSet<String>()
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<String, String>()
val calendars = HashMap<String, String>()
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 <T> 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()
}
@@ -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<String?>(null)
private val drawerComponentMenu by lazy { ComponentsMenu(this, uiHandler) }
private var drawerGameProfileId by mutableStateOf<Long?>(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<Library.SteamGame>()
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<Long?>(null)
private var frameGenActiveGameName by mutableStateOf<String?>(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<Long>? = 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"
@@ -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",
)
}
@@ -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
}
@@ -21,16 +21,22 @@ interface AgentHarness {
val signIn: List<String>
/** 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<String>
/** Models to offer besides the CLI's default; [rootfs] is where the CLI's own files can be read. */
fun models(rootfs: File): List<Model>
/** The guest command for one turn; [conversation] is null for the first one. */
fun turn(message: String, conversation: String?, options: Options): List<String>
/** 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<AgentHarness> = 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<AgentHost.Limit>? = 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<AgentHost.Limit>? {
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<AgentHarness.Model> = 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 '<command>'`; the command is what the user wants to read. */
@@ -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<String>)
@@ -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<Entry>()
val queue = mutableStateListOf<Queued>()
@@ -71,6 +87,9 @@ object AgentHost {
/** The chosen model for [harness]; null is the CLI's default. */
var model by mutableStateOf<String?>(null)
private set
/** The chosen reasoning effort for [harness]; null is the CLI's default. */
var effort by mutableStateOf<String?>(null)
private set
var plan by mutableStateOf(false)
private set
var chat by mutableStateOf<String?>(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<List<Limit>>(emptyList())
private set
var lab by mutableStateOf<LabProgress?>(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<String>, workdir: String = "/root", connectAdb: Boolean = true): ProcessBuilder {
fun guest(app: Context, command: List<String>, 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<Limit>) = 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<Limit> = 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)
}
@@ -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)
@@ -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)
}
}
@@ -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)
}
}
@@ -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<String>,
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 ->
@@ -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(
@@ -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<String, String?> =
defaults(preset, forceSsbs) + config.shared + if (scope.isEmpty()) emptyMap() else config.games[scope].orEmpty()
@@ -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<Fixed>)
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<Int, Int>): Pair<Int, Int> = 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<Int, Int>): List<Fixed> {
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)
}
@@ -13,6 +13,11 @@ object HostProcess {
@JvmStatic
fun start(command: String, env: Array<String>?, dir: File?, onExit: Consumer<Int>?, onLine: Consumer<String>?, outputFile: File?): Int {
return start(command, env, dir, onExit, onLine, outputFile, null)
}
@JvmStatic
fun start(command: String, env: Array<String>?, dir: File?, onExit: Consumer<Int>?, onLine: Consumer<String>?, 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() }
}
@@ -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)
}
}
}
@@ -97,7 +97,7 @@ object AddedGames {
return File(LinuxRuntime.rootDir(context), guest.removePrefix("/"))
}
fun candidates(folder: File): List<File> = rank(folder).exes
fun candidates(folder: File, reuse: Boolean = false): List<File> = 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<Game>, 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
@@ -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<Entry>): List<Entry> {
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<Entry> = 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<Entry>): 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<Library.SteamGame> = 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,
)
}
}
@@ -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")
@@ -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<Rom>) {
@@ -123,9 +125,13 @@ object Library {
.distinctBy { runCatching { it.canonicalPath }.getOrDefault(it.absolutePath) }
}
fun soundtracks(context: Context, arch: String = SessionPrefs.activeSteamClientArch(context)): List<SteamGame> =
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<Int>? = null,
): List<SteamGame> {
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<Int> {
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<Pair<Int, File>> {
@@ -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<Int, List<Track>>, val artist: String, val cover: File?) {
val tracks: List<Track> get() = disc.values.flatten()
val discs: List<Int> 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<Raw>): Map<Int, List<Track>> {
if (raws.isEmpty()) return emptyMap()
val unique = LinkedHashMap<String, Raw>()
val home = HashMap<String, String>()
val disc = HashMap<String, Int>()
val track = HashMap<String, Int>()
val title = HashMap<String, String>()
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<Raw>({ 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<String> { 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<File>): List<Raw>? = 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<String, JSONObject>()
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<Raw>) {
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<File> {
val out = ArrayList<File>()
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>): 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<String>) {
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)
}
}
@@ -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<AddedGameArt.Option> {
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<AddedGameArt.SlotState> {
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()
}
}
@@ -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<TrackRef>)
class Snapshot(val favorites: List<TrackRef>, val collections: List<Collection>)
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<TrackRef>, ref: TrackRef): List<TrackRef> =
if (list.any { it.path == ref.path }) list.filterNot { it.path == ref.path } else list + ref
internal fun merged(list: List<TrackRef>, add: List<TrackRef>): List<TrackRef> {
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<Collection>, name: String, except: Int? = null): Boolean =
collections.any { it.id != except && it.name.equals(name, ignoreCase = true) }
internal fun nextId(collections: List<Collection>): Int =
(collections.maxOfOrNull { it.id } ?: FAVORITES_ID).coerceAtLeast(FAVORITES_ID) + 1
private fun encode(s: Snapshot): String {
fun refs(list: List<TrackRef>) = 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<TrackRef> = 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<TrackRef> =
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<TrackRef>): 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<TrackRef>) {
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<String>) {
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<String>) {
load(context)
val s = snapshot
fun arrange(list: List<TrackRef>): List<TrackRef> {
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<TrackRef>): 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<TrackRef>): 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<Library.SteamGame> {
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))
}
}
@@ -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<Hit> = 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<Library.SteamGame>): List<Hit> {
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
}
}
@@ -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<String, List<String>>? = 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<String, List<String>> {
cache?.let { return it }
val out = HashMap<String, List<String>>()
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<String>) {
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<Int, List<Soundtrack.Track>>, order: List<String>): Map<Int, List<Soundtrack.Track>> {
if (order.isEmpty()) return disc
val index = HashMap<String, Int>()
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<Int, List<Soundtrack.Track>>): Map<Int, List<Soundtrack.Track>> {
val order = read(context)[root.path] ?: return disc
return ordered(disc, order)
}
}
@@ -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()
}
}
@@ -0,0 +1,30 @@
package com.droiddeck.launcher.frontend
object SoundtrackTracks {
enum class Sort { DEFAULT, TITLE_ASC, TITLE_DESC, LONGEST, SHORTEST }
fun <T> sort(items: List<T>, sort: Sort, title: (T) -> String, duration: (T) -> Long): List<T> = 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
}
}
}
@@ -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<String, String> {
@@ -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)
}
@@ -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<DroidDeckHudDock, Float>? {
private fun overhang(v: View, dx: Float = 0f, dy: Float = 0f): Map.Entry<DroidDeckHudDock, Float>? {
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)
@@ -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"
@@ -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;
@@ -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<String> 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<Integer, long[][]> 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<long[]> 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;
@@ -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<PadState> 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;
}
@@ -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<String?>(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<Int?>(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<String> = java.util.Collections.synchronizedSet(HashSet())
private var activeRoot: String? = null
private var savedId: String? = null
private var future: ListenableFuture<MediaController>? = 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<MediaItem> {
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<String>) {
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<Int>, 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()
}
}
}
@@ -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<CommandButton>, showPauseButton: Boolean,
): ImmutableList<CommandButton> {
val all = super.getMediaButtons(session, playerCommands, customLayout, showPauseButton)
val custom = all.filter { it.sessionCommand != null }
if (custom.size < 2) return all
return ImmutableList.builder<CommandButton>()
.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<CommandButton> = 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<SessionResult> {
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<MediaItem>,
): ListenableFuture<MutableList<MediaItem>> {
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)
}
}
}
@@ -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<List<Int>>(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<Int>, 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()
}
}
@@ -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,
@@ -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")
@@ -139,15 +139,26 @@ public final class LinuxRuntime {
public static List<String> command(Context context, File sessionRoot, File runtimeDir,
File externalStorage, List<String> extraBinds,
List<String> guestCommand) {
return command(context, sessionRoot, runtimeDir, externalStorage, extraBinds, guestCommand, false);
}
public static List<String> command(Context context, File sessionRoot, File runtimeDir,
File externalStorage, List<String> extraBinds,
List<String> guestCommand, boolean fakeRoot) {
File root = rootDir(context);
List<String> 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<String> commandWithBinds(Context context, File root, List<String> binds,
List<String> guestCommand) {
List<String> cmd = prootPrefix(context, root, "/root");
return commandWithBinds(context, root, binds, guestCommand, false);
}
public static List<String> commandWithBinds(Context context, File root, List<String> binds,
List<String> guestCommand, boolean fakeRoot) {
List<String> 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<String> rootPrefix(Context context, File root, String cwd) {
List<String> cmd = prootPrefix(context, root, cwd, true);
cmd.add(1, "--link2symlink");
return cmd;
}
public static List<String> prootPrefix(Context context, File root, String cwd, boolean fakeRoot) {
List<String> cmd = new ArrayList<>();
cmd.add(prootBinary(context).getPath());
@@ -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 ->
@@ -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 <T> 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))
}
}
@@ -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)
@@ -90,11 +90,11 @@ object GameStorage {
fun gamesFolderLibraries(context: Context): List<Library> {
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) }
@@ -30,6 +30,25 @@ object NoSteamLaunch {
GameEnvironment.gameNoSteam(GameEnvironmentStore.read(context), (appId and 0xFFFFFFFFL).toString())
}.getOrDefault(false)
fun scopeOf(program: String?, args: List<String>, 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<Int, Int>): Pair<Int, Int>? {
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 ->
@@ -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<Int> = 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
@@ -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<String>,
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<String, String>,
gameWindowsComponents: List<String>,
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,
)
}
}
@@ -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
@@ -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)
@@ -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)
}
@@ -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<String> = idList(prefs(context).getString("navTabOrder", null))
fun setNavTabOrder(context: Context, order: List<String>) {
prefs(context).edit().putString("navTabOrder", order.joinToString(",")).apply()
}
fun navTabShelved(context: Context): Set<String> = idList(prefs(context).getString("navTabShelved", "soundtracks,agent")).toSet()
fun setNavTabShelved(context: Context, keys: Set<String>) {
prefs(context).edit().putString("navTabShelved", keys.joinToString(",")).apply()
}
fun navTabHidden(context: Context): Set<String> = idList(prefs(context).getString("navTabHidden", null)).toSet()
fun setNavTabHidden(context: Context, keys: Set<String>) {
prefs(context).edit().putString("navTabHidden", keys.joinToString(",")).apply()
}
private fun idList(raw: String?): List<String> = 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 =
@@ -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) {
@@ -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)
@@ -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()
@@ -82,13 +82,14 @@ object SteamLibraries {
/** Reads storage; call off the main thread. */
fun found(context: Context): List<Found> {
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<Pair<File, Int>>()
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<Pair<File, Int>>()
@@ -101,6 +102,9 @@ object SteamLibraries {
}
}
internal fun offered(taken: List<String>, gamesFolders: List<String>, 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
@@ -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
@@ -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
}
}
@@ -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? {
@@ -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 {
@@ -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
@@ -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())
}
}
@@ -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<CatalogItem>?, new: List<CatalogItem>): List<CatalogItem> {
if (old.isNullOrEmpty()) return new
@@ -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<CatalogItem> = shelves.all)
@Volatile private var memory: Catalog? = null
@Volatile private var memoryAt = 0L
fun cached(): StoreShelves? = cachedCatalog()?.shelves
fun everything(): List<CatalogItem> = 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<String, String>()
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<CatalogItem>?, match: (CatalogItem, CatalogItem) -> Boolean): StoreShelves {
if (library.isNullOrEmpty()) return s
fun mark(list: List<CatalogItem>) = markOwned(list, library, match)
return StoreShelves(mark(s.whatsNew), mark(s.deals), mark(s.free), mark(s.trending), s.art)
}
fun markOwned(list: List<CatalogItem>, library: List<CatalogItem>?, match: (CatalogItem, CatalogItem) -> Boolean): List<CatalogItem> {
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 }
}
}
}
@@ -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<String>()
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)
@@ -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")
@@ -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)
}
@@ -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<String, CompletableFuture<Long?>>,
key: String,
start: () -> CompletableFuture<Long?>,
): CompletableFuture<Long?> {
var created: CompletableFuture<Long?>? = null
val shared = requests.computeIfAbsent(key) { CompletableFuture<Long?>().also { created = it } }
if (created === shared) {
val source = runCatching(start).getOrElse { failure ->
CompletableFuture<Long?>().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<String, Long>()
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)
} }
@@ -236,6 +236,27 @@ object StoresState {
var itchPicking by mutableStateOf<CatalogItem?>(null)
var gameJoltPicking by mutableStateOf<CatalogItem?>(null)
/** Store cards whose free game is being added to the account. */
val claiming = mutableStateMapOf<String, Boolean>()
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<CatalogItem> = 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)
}
@@ -22,6 +22,7 @@ object EaApi {
val downloadable: Boolean,
val trial: Boolean,
val ownership: List<String>,
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<JSONObject> {
val out = ArrayList<JSONObject>()
var next: String? = "0"
@@ -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<CatalogItem> =
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
@@ -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<String> = 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<JSONObject>): Map<String, List<JSONObject>> =
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<String>, gen: Int): Map<String, EaApi.Images> {
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
@@ -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<redacted>\"").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)
@@ -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("""<script id="__NEXT_DATA__" type="application/json">(.*?)</script>""", 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<CatalogItem> {
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<List<CatalogItem>, Int> {
val data = NEXT_DATA.find(html)?.groupValues?.get(1) ?: return emptyList<CatalogItem>() to 0
val props = JSONObject(data).optJSONObject("props")?.optJSONObject("pageProps") ?: return emptyList<CatalogItem>() to 0
val games = props.optJSONArray("games") ?: return emptyList<CatalogItem>() 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<List<CatalogItem>, 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<CatalogItem> {
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<Int, List<CatalogItem>>()
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<CatalogItem>, 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),
)
}
}
@@ -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<String> {
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<String>()
val components = HashMap<String, String>()
val listings = HashMap<File, Map<String, List<String>>>()
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
}
}
}
@@ -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) }
}
@@ -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<CatalogItem> =
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<RockstarBranch>, 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<RockstarApp>, val packages: List<RockstarPackage>)
internal object RockstarApps {
fun parse(root: Element): List<RockstarApp> = 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<RockstarPackage> = 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<RockstarApp>, 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<Int?>(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<RockstarTitle> =
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<CatalogItem> = 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<CatalogItem> = 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<CatalogItem> {
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
}
@@ -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<RockstarChunk>)
internal data class RockstarBuild(val buildId: String, val version: String, val preload: Boolean, val files: List<RockstarFile>) {
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<RockstarChunk>, maxBytes: Long = 48L * 1024 * 1024, maxCount: Int = 16): List<List<RockstarChunk>> {
val out = ArrayList<List<RockstarChunk>>()
var cur = ArrayList<RockstarChunk>()
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<String>().apply { if (ledger.isFile) ledger.readLines().filterTo(this) { it.isNotBlank() } }
val pending = ArrayList<Pair<RockstarFile, RockstarChunk>>()
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<Throwable?>(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<RockstarChunk>): Map<String, String> {
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
}
}
}
@@ -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)
}
@@ -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) }
}
}
@@ -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()
}
@@ -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<Pair<String, String>>): String =
fields.joinToString("&") { (k, v) -> "$k=" + URLEncoder.encode(v, "UTF-8") }
fun call(method: String, fields: List<Pair<String, String>>, host: String = HOST, headers: Map<String, String> = 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<Pair<String, String>>, host: String = HOST, headers: Map<String, String> = 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("<!DOCTYPE", ignoreCase = true)) { "XML document types are not supported" }
val f = DocumentBuilderFactory.newInstance()
f.isNamespaceAware = false
runCatching { f.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true) }
runCatching { f.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true) }
runCatching { f.setFeature("http://xml.org/sax/features/external-general-entities", false) }
runCatching { f.setFeature("http://xml.org/sax/features/external-parameter-entities", false) }
runCatching { f.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false) }
f.isExpandEntityReferences = false
return f.newDocumentBuilder().parse(ByteArrayInputStream(xml.toByteArray(Charsets.UTF_8))).documentElement
}
fun first(root: Element, tag: String): Element? = root.getElementsByTagName(tag).let { if (it.length > 0) it.item(0) as Element else null }
fun all(root: Element, tag: String): List<Element> = 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<Element> {
val out = ArrayList<Element>()
var n = parent.firstChild
while (n != null) {
if (n is Element && n.tagName == tag) out += n
n = n.nextSibling
}
return out
}
}
@@ -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<RockstarTitle> =
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<String, String> = 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,
)
}
Loaded 100 of 291 files, more files were not shown because too many files have changed in this diff. Show more